Jenkins + Ansible + Gitlab 自動化部署三劍客

Jenkins + Ansible + Gitlab 自動化部署三劍客

Gitlab

準(zhǔn)備linux初始環(huán)境

# 關(guān)閉防火墻
systemctl stop firewalld
# 開機自動關(guān)閉
systemctl disable firewalld
# 強制關(guān)閉selinux
vim /etc/sysconfig/selinux
SELINUX=disabled
# 查看selinux策略是否被禁用(Disabled)
getenforce
# 安裝gitlab依賴包
yum install -y curl policycoreutils openssh-server openssh-clients postfix git
# 下載gitlab yum倉庫源
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
# 啟動postfix郵件服務(wù)
systemctl start postfix
systemctl enable postfix
# 安裝gitlab
yum install -y gitlab-ce

# 手動配置ssl證書
mkdir -p /etc/gitlab/ssl
openssl genrsa -out "/etc/gitlab/ssl/gitlab.example.com.key" 2048
cd /etc/gitlab/ssl
openssl req -new -key "/etc/gitlab/ssl/gitlab.example.com.key" -out "/etc/gitlab/ssl/gitlab.example.com.csr"
# 進入ssl安裝向?qū)?cn (country)
bj (province)
bj (city)
空格 (organization)
空格 (organization unit)
gitlab.example.com (common name gitlab域名)
admin@example.com (email)
1234qwer (證書密碼)
空格 (company name)
# /etc/gitlab/ssl 目錄下可以看到密鑰和csr證書
# 利用ssl密鑰和證書創(chuàng)建簽署crt證書
openssl x509 -req -days 365 -in "/etc/gitlab/ssl/gitlab.example.com.csr" -signkey "/etc/gitlab/ssl/gitlab.example.com.key" -out "/etc/gitlab/ssl/gitlab.example.com.crt"
# 利用openssl簽署pem證書
openssl dhparam -out /etc/gitlab/ssl/dhparams.pem  2048
# 更改ssl下的所有證書權(quán)限
chmod 600 *

# 配置證書到gitlab配置文件中
vim /etc/gitlab/gitlab.rb 
external_url 'https://gitlab.example.com'
nginx['redirect_http_to_https'] = true (去掉注釋)
nginx['ssl_certificate'] = "/etc/gitlab/ssl/gitlab.example.com.crt" (注釋不去掉)
nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/gitlab.example.com.key" (注釋不去掉)
nginx['ssl_dhparam'] = /etc/gitlab/ssl/dhparams.pem (注釋不去掉)
# 初始化gitlab相關(guān)服務(wù)配置
gitlab-ctl reconfigure 
# 找到gitlab下的ningx反向代理工具, 更改gitlab的http配置文件
vim /var/opt/gitlab/nginx/conf/gitlab-http.conf
# 在 server_name 下面一行添加如下梗摇,用來重定向所有g(shù)etlab的http請求
rewrite ^(.*)$ https://$host$1 permanent;
gitlab-ctl restart
# 即可訪問服務(wù)器地址訪問gitlab頁面,在主機添加dns

gitlab-ctl reconfigure 錯誤:

運存必須大于2GB

如果卡在 ruby_block[wait for postgresql service socket] action run 長時間不動

退出配置 另一個終端開啟 /opt/gitlab/embedded/bin/runsvdir-start

然后重新 gitlab-ctl reconfigure

如果卡在 bash[migrate gitlab-rails database] action run 長時間不動 或者如下錯誤

bash[migrate gitlab-rails database] (gitlab::database_migrations line 55) had an error: Mixlib::Shel

解決辦法 :

gitlab-ctl stop

chmod 755 /var/opt/gitlab/postgresql

另一個終端開啟 systemctl restart gitlab-runsvdir

gitlab-ctl reconfigure

gitlab-ctl restart

搭建Gitlab倉庫


# 在gitlab頁面建好第一個項目
# 登錄gitlab主界面抬纸,添加一個New project,輸入 Project name 和 Project description种柑,Visibility Level 選擇默認(rèn) Private务蝠,創(chuàng)建好后復(fù)制倉庫http地址 COPY URL
# 回到服務(wù)器击奶,在用戶下創(chuàng)建 repo目錄
mkdir repo
cd repo
# 這里的 -c http.sslVerify=false 用來避免本地證書無法進行clone操作辈双,如果沒有添加dns,則直接訪問ip/root/test-repo.git 輸入用戶名和密碼
git -c http.sslVerify=false clone https://gitlab.example.com/root/test-repo.git
vim test.py print "This is test code"
# 添加test.py到本地倉庫
git add . 
# 提交
git commit -m"First commit"
# 提示創(chuàng)建本地git全局的郵箱和用戶名柜砾,再次運行 git commit -m"First commit" 即可提交成功
git config --global user.email "admin@example.com"
git config --global user.name "admin"
# 輸入賬號密碼辐马,同步本地master分支到遠(yuǎn)程服務(wù)器當(dāng)中
git -c http.sslVerify=false push origin master

# 查看當(dāng)前全局用戶配置
git config --global --list
# 創(chuàng)建代碼分支release-1.0
git checkout -b release-1.0
# 修改代碼
vim test.py print "This is test code for release-1.0"
# 添加修改
git add .
# 提交
git commit -m"release-1.0"
#  輸入賬號密碼,同步本地release-1.0分支到遠(yuǎn)程服務(wù)器當(dāng)中
git -c http.sslVerify=false push origin release-1.0

完全卸載刪除gitlab

# 停止gitlab
gitlab-ctl stop
# 卸載gitlab(注意這里寫的是gitlab-ce)
rpm -e gitlab-ce
# 查看gitlab進程
ps aux | grep gitlab
# 殺掉第一個進程(就是帶有好多.............的進程)
kill -9 18777
# 殺掉后,在ps aux | grep gitlab確認(rèn)一遍喜爷,還有沒有g(shù)itlab的進程
# 刪除所有包含gitlab文件
find / -name gitlab | xargs rm -rf

Ansible

安裝與配置

# 關(guān)閉防火墻
systemctl stop firewalld
# 開機自動關(guān)閉
systemctl disable firewalld
# 強制關(guān)閉selinux
vim /etc/sysconfig/selinux
SELINUX=disabled
# 查看selinux策略是否被禁用(Disabled)
getenforce

# 安裝Python和pip
yum -y install git nss curl wget libffi-devel openssl-devel
wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz
tar -zxvf Python-3.8.0.tgz
cd Python-3.8.0
# --with-ensurepip 用來安裝 pip 包管理工具,--enable-shared LDFLAGS 配置python 匹配當(dāng)前系統(tǒng)的參數(shù)值
./configure --prefix=/usr/local/python3 --enable-optimizations --with-ssl
make && make install

# 安裝python虛擬環(huán)境
pip3 install virtualenv
# 在新用戶下創(chuàng)建 virtualenv
useradd deploy
su - deploy
virtualenv -p /usr/local/bin/python3.8 .py3-a2.5-env

# git 拉取Ansible源碼
git clone https://github.com/ansible/ansible.git
# 加載virtualenv環(huán)境
source /home/deploy/.py3-a2.5-env/bin/activate
# 安裝ansible依賴包
pip3 install paramiko PyYAML jinja2
# 把ansible源代碼移動到python3.6的virtualenv環(huán)境下
mv ansible .py3-a2.5-env/
cd .py3-a2.5-env/ansible/
# 切換到ansible到2.5版本
git checkout stable-2.5
# 加載
source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
# 看是否安裝成功
ansible-playbook --version

pip3 安裝包時報錯ModuleNotFoundError: No module named '_ctypes'的解決辦法

pip3 install時報錯“pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

yum install libffi-devel 重新編譯安裝python3

如果安裝完jinja2后還是出現(xiàn) No module named jinja2萄唇, 可以直接yum安裝 yum install -y python-jinja2 python-yaml

playbooks 測試 (需要先配置好服務(wù)器和部署主機的ssh無密碼訪問)

# 加載virtualenv環(huán)境
source /home/deploy/.py3-a2.5-env/bin/activate
# 加載ansible
source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
# 驗證是否開啟ansible服務(wù)
ansible-playbook --version
# 創(chuàng)建如下目錄結(jié)構(gòu)
(py3-a2.5-env) [root@k8s-master test_playbooks]# tree .
.
├── deploy.yml
├── inventory
│   └── testenv
└── roles
    └── testbox
        └── tasks
            └── main.yml

4 directories, 3 files

# inventory 為Server詳細(xì)清單目錄檩帐,里面存放具體清單與變量聲明文件,用于保存目標(biāo)部署主機的相關(guān)域名和ip地址以及變量參數(shù)
# roles 為詳細(xì)任務(wù)列表目錄另萤,里面存放一個或者多個 role湃密,通常被命名為具體的APP或者項目名稱,這里命名為 testbox 作為項目名稱四敞,下面的 tasks 目錄用來保存 testbox 主任務(wù)文件 main.yml泛源,deploy.yml 作為 playbook 任務(wù)入口文件,將調(diào)度 roles 下需要部署的項目忿危,以及該項目下的所有任務(wù)达箍,最終將該任務(wù)部署在 inventory 下定義的目標(biāo)主機中

vim testenv

[testservers]
test.example.com

[testservers:vars]
server_name=test.example.com
user=root
output=/root/test.txt

# [testservers] 為 Server 組列表,下面包含目標(biāo)部署服務(wù)器的主機名铺厨,可以是域名也可以是ip地址
# [testservers:vars] 為 testservers 組的列表參數(shù)缎玫,下面包含該組下的目標(biāo)主機需要的 Key/value 鍵值對參數(shù)

vim main.yml

- name: Print server name and user to remote testbox
  shell: "echo 'Currently {{ user }} is logining {{ server_name}}' > {{ output}}" 
  
# name 為任務(wù)名稱,方便知道該 task 是做什么用的
# shell 為使用shell模塊執(zhí)行命令解滓,雙括號里為引入 testenv 中的 [testservers:vars] 參數(shù)

vim deploy.yml

- hosts: "testservers" # 對應(yīng) testenv 中的 server 標(biāo)簽赃磨,調(diào)用該標(biāo)簽下的目標(biāo)主機
  gather_facts: true  # 獲取目標(biāo)主機下的信息
  remote_user: root   # 在目標(biāo)主機下使用root權(quán)限
  roles:
    - testbox        # 進入目標(biāo)下的testbox目錄

# ansible 核心文件,與 ansible-playbook 命令直接對話
# 執(zhí)行部署
ansible-playbook -i inventory/testenv ./deploy.yml

Ansible Playbooks 常用模塊應(yīng)用

# File模塊  創(chuàng)建文件或目錄洼裤,并賦予系統(tǒng)權(quán)限
- name: create a file
  file: 'path=/root/foo.txt state=touch mode=0775 owner=foo group=foo'
# 實現(xiàn)Ansible服務(wù)端到目標(biāo)主機的文件傳送 force=yes 強制執(zhí)行
- name: copy a file
  copy: 'remote_src=no src=roles/testbox/files/foo.sh dest=/root/foo.sh mode=0644 force=yes'
# Stat模塊 獲取遠(yuǎn)程文件狀態(tài)信息 register: script_stat 把狀態(tài)信息賦值給script_stat 變量
- name: check if foo.sh exists
  stat: 'path=/root/foo.sh'
  register: script_stat
# Debug模塊 打印語句到Ansible執(zhí)行輸出 debug: msg=foo.sh exists 表示輸出信息為foo.sh exists
- debug: msg="foo.sh exists"
  when: script_stat.stat.exists
# Command/Shell模塊 用來執(zhí)行Linux目標(biāo)主機命令行 shell會調(diào)用linux下的bin/bash邻辉,就可以使用系統(tǒng)環(huán)境變量、重定向符腮鞍、管道符等
- name: run the script
  command: "sh /root/foo.sh"
- name: run the script
  shell: "echo 'test' > /root/test.txt"
# Template模塊 實現(xiàn)Ansible服務(wù)端到目標(biāo)主機的jinja2模板傳送 nginx.conf.j2中的變量參數(shù)會調(diào)用server清單里的var變量參數(shù)值
- name: write the nginx config file
  template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf
# Packaging模塊 調(diào)用目標(biāo)主機系統(tǒng)包管理工具(yum,apt)進行安裝 yum包裝目標(biāo)系統(tǒng)為CentOS/Redhat值骇,apt則為Debian/Ubuntu
- name: ensure nginx is at the latest version
  yum: pkg=nginx state=latest
- name: ensure nginx is at the latest version
  apt: pkg=nginx state=latest
# Service模塊 管理目標(biāo)主機系統(tǒng)服務(wù)
- name: start nginx service
  service: name=nginx state=started

注意 commond 模塊和 shell 模塊類似,但有區(qū)別

command 模塊命令將不會使用 shell 執(zhí)行. 因此, 像 $HOME 這樣的變量是不可用的缕减。還有像<, >, |, ;, &都將不可用雷客。

shell 模塊通過shell程序執(zhí)行, 默認(rèn)是/bin/sh, <, >, |, ;, & 可用桥狡。但這樣有潛在的 shell 注入風(fēng)險搅裙, 后面會詳談.

command 模塊更安全,因為他不受用戶環(huán)境的影響裹芝。 也很大的避免了潛在的 shell 注入風(fēng)險.

register 是將該模塊執(zhí)行后的輸出寫入到變量部逮,變量的命名不能用 -中橫線,比如dev-sda6_result嫂易,則會被解析成sda6_result兄朋,dev會被丟掉,所以不要用 - 怜械。全局變量或者 role 下的vars 變量也不要用 -

ignore_errors這個關(guān)鍵字很重要颅和,一定要配合設(shè)置成True傅事,否則如果命令執(zhí)行不成功,即 echo $?不為0峡扩,則在其語句后面的ansible語句不會被執(zhí)行蹭越,導(dǎo)致程序中止。

實例

# 加載virtualenv環(huán)境
source /home/deploy/.py3-a2.5-env/bin/activate
# 加載ansible
source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
# 驗證是否開啟ansible服務(wù)
ansible-playbook --version

# 進入目標(biāo)主機配置教届,為了保證目標(biāo)服務(wù)器的任務(wù)順利執(zhí)行
ssh root@test.example.com
useradd foo
useradd deploy
mkdir /etc/nginx
rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
exit

# 創(chuàng)建file和templates
mkdir /root/testbox/files
vi roles/testbox/files/foo.sh
echo "This is a test script"
mkdir roles/testbox/templates
vim roles/testbox/templates/nginx.conf.j2

user                    {{ user }};
worker_processes        {{ worker_processes }};
error_log               /var/log/nginx/error.log;
pid                     /var/run/logs/nginx.pid;
events {
    worker_connections  {{ max_open_file }};
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   {{ root }};
            index  index.html index.htm;
        }

        error_page   404  /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

    }
}


# 修改 testenv
vim inventory/testenv

server_name=test.example.com
port=80
user=deploy
worker_processes=4
max_open_file=65505
root=/www

# 修改 testenv
vim roles/testbox/tasks/main.yml

- name: Print server name and user to remote testbox
  shell: "echo 'Currently {{ user }} is logining {{ server_name}}' > {{ output}}"
- name: create a file
  file: 'path=/root/foo.txt state=touch mode=0775 owner=foo group=foo'
- name: copy a file
  copy: 'remote_src=no src=roles/testbox/files/foo.sh dest=/root/foo.sh mode=0644 force=yes'
- name: check if foo.sh exists
  stat: 'path=/root/foo.sh'
  register: script_stat
- debug: msg="foo.sh exists"
  when: script_stat.stat.exists
- name: run the script
  command: 'sh /root/foo.sh'
- name: write the nginx config file
  template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf
- name: ensure nginx is at the latest version
  yum: pkg=nginx state=latest
- name: start nginx service
  service: name=nginx state=started
  
# 執(zhí)行部署
ansible-playbook -i inventory/testenv ./deploy.yml
# 查看是否啟動成功
ssh root@test.example.com  ps -ef | grep nginx

# 添加test.py到本地倉庫
cd test_playbooks
git add . 
# 提交
git commit -m"ansible-playbook repo"
# 輸入賬號密碼响鹃,同步本地master分支到遠(yuǎn)程服務(wù)器當(dāng)中
git -c http.sslVerify=false push origin master

jenkins

安裝與配置

# 關(guān)閉防火墻
systemctl stop firewalld
# 開機自動關(guān)閉
systemctl disable firewalld
# 強制關(guān)閉selinux
vim /etc/sysconfig/selinux
SELINUX=disabled
# 查看selinux策略是否被禁用(Disabled)
getenforce
# 下載yum源,并在本地導(dǎo)入yum源案训,驗證yum倉庫的安全性
wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
# 安裝 java 環(huán)境
yum install -y java

# 安裝jenkins
yum install -y jenkins
# 添加新用戶
useradd deploy
# 編輯 jenkins 配置文件
vim /etc/sysconfig/jenkins

JENKINS_USER="deploy"
JENKINS_PORT="8080"
# 改編jenkins默認(rèn)的家目錄买置,以及l(fā)og日志目錄的屬組和屬組權(quán)限
chown -R deploy:deploy /var/lib/jenkins
chown -R deploy:deploy /var/log/jenkins
# 啟動jenkins服務(wù)
systemctl start jenkins
# 確認(rèn)服務(wù)是否正常啟動
lsof -i:8080

# 訪問主機的ip:8080 可配置dns訪問,這里配置jenkins.example.com
# 解鎖jenkins强霎,在服務(wù)器找到日志中的密碼
cat /var/lib/jenkins/secrets/initialAdminPassword

# 如果遇到 Please wait while Jenkins is getting ready to work...(Jenkins訪問資源慢的問題)
vim /var/lib/jenkins/hudson.model.UpdateCenter.xml

<?xml version='1.1' encoding='UTF-8'?>
<sites>
  <site>
    <id>default</id>
    <url>https://mirrors.tuna.tsinghua.edu.cn/jenkins/</url>
  </site>
</sites>

# 根據(jù)web提示安裝即可

Jenkins Job 構(gòu)建配置

環(huán)境配置

# 配置 Jenkins server 本地 Gitlab DNS
如果使用域名登錄就綁定下本機的host
# 安裝 git client, curl 工具依賴
yum install -y git curl
# 關(guān)閉系統(tǒng) Git http.sslVerify 安全認(rèn)證
su - deploy
$git config --global http.sslVerify false
# 添加 Jenkins 后臺 Git client user 與 email
進入 Jenkins -> Manage Jenkins忿项, Git Plugin 加入user.name為root user.email為root@example.com 
如果沒有 Git Plugin 的話需要進入的 Jenkins -> Manage Jenkins -> Manage Plugins -> Available 搜索 Git Plugin 找到 Git 安裝插件后重啟
# 添加 Jenkins 后臺 Git Credential 憑據(jù)
進入 Manage Jenkins, Manage Credentials, 進入 Stores scoped to Jenkins 的Jenkins 添加憑據(jù),輸入 root和密碼

Jenkins freestyle Job 構(gòu)建配置

# Jenkins 進入 New Item 新建任務(wù)
輸入 test-freestyle-job 選擇Freestyle project
# 編輯描述信息
Description:This is my first test freestyle job
# 添加參數(shù)配置
選則 This project is parameterized 
選擇 add Parameter 選擇 Choice Parameter (選項參數(shù))
Name : deploy_env
Choices : dev
         prod (分別為開發(fā)環(huán)境和生產(chǎn)環(huán)境)
Description : Choose deploy environment
選擇 add Parameter 選擇 String Parameter (文本參數(shù))
Name : version
Default Value : 1.0.0
Description : Build version
# 配置源代碼管理
進入 gitlab 倉庫脆栋, 選擇 Administrator / test-repo 代碼倉庫 clone URL
將 https://gitlab.example.com/root/test-repo.git 粘貼到
Jenkins Source Code Management 的 Git 選項中的 Repository URL
Credentials 選擇之前創(chuàng)建的 Git Credential 憑據(jù) (憑據(jù)驗證通過可以看到錯誤消失)
# Build配置
選則 Build倦卖,點擊 Add build step,選則 Execute shell
在 command 中輸入
#!/bin/sh

export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"

# Print env variable
echo "[INFO] Print env variable"
echo "Current deployment environment is $deploy_env" >> test.properties
echo "The Build is $version" >> test.properties
echo "[INFO] Done..."

# Check test properties
echo "[INFO] Check test properties"
if [ -s test.properties ]
then
  cat test.properties
  echo "[INFO] Done..."
else
  echo "no such file for test.properties"
fi

echo "[INFO] Build finished..."

Jenkins Pipeline Job 構(gòu)建配置

# Jenkins -> Manage Jenkins -> Manage Plugins -> Available 搜索 pipeline 找到 Pipeline 安裝插件后重啟
# Jenkins 進入 New Item 新建任務(wù)
輸入 test-pipeline-job 選擇 Pipeline 流水線
# 編輯描述信息
Description:This is my first test pipeline job
# 編寫 groovy 腳本, 添加到 Pipeline 下的 Pipleline Script
#!groovy
 
pipeline {
    agent {node {label 'master'}}
 
    environment {
        PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
    }
 
    parameters {
        choice(
            choices: 'dev\nprod',
            description: 'choose deploy environment',
            name: 'deploy_env'
            )
        string (name: 'version', defaultValue: '1.0.0', description: 'build version')
    }
 
    stages {
        stage("Checkout test repo") {
            steps{
                sh 'git config --global http.sslVerify false'
                dir ("${env.WORKSPACE}") {
                    git branch: 'master', credentialsId:"0031dc09-1c94-495f-a0fa-33aab7d0e227", url: 'https://gitlab.example.com/root/test-repo.git'
                }
            }
        }
        stage("Print env variable") {
            steps {
                dir ("${env.WORKSPACE}") {
                    sh """
                    echo "[INFO] Print env variable"
                    echo "Current deployment environment is $deploy_env" >> test.properties
                    echo "The build is $version" >> test.properties
                    echo "[INFO] Done..."
                    """
                }
            }
        }
        stage("Check test properties") {
            steps{
                dir ("${env.WORKSPACE}") {
                    sh """
                    echo "[INFO] Check test properties"
                    if [ -s test.properties ]
                    then 
                        cat test.properties
                        echo "[INFO] Done..."
                    else
                        echo "no such file for test.properties"
                    fi
                    """
 
                    echo "[INFO] Build finished..."
                }
            }
        }
    }
}

Jenkins Linux Shell 集成

# Jenkins 進入 New Item 新建任務(wù)
輸入 shell-freestyle-job 選擇Freestyle project
# 編輯描述信息
Description:This is my first test shell job
# Build配置
選則 Build椿争,點擊 Add build step怕膛,選則 Execute shell
在 command 中輸入

#!/bin/sh
user=`whoami`
if [ $user == 'deploy' ]
then
    echo "Hello, my name is $user"
else
    echo "Sorry, I am $user"
fi
 
ip addr
cat /etc/system-release
free -m
df -h
py_cmd=`which python`

Jenkins 參數(shù)集成

# Jenkins 進入 New Item 新建任務(wù)
輸入 parameter-freestyle-job 選擇Freestyle project
# 編輯描述信息
Description:This is my first parameter job
# 選擇參數(shù)化構(gòu)建過程,添加參數(shù)
This project is parameterized -> Add Parameter -> Choice Parameter (選項參數(shù))
Name : deploy_env
Choices : dev
         uat
         stage 
         prod
Description : Choose deploy environment

Add Parameter -> String Parameter (文本參數(shù))
Name : version
Default Value : 1.0.0
Description : Fill in build version

Add Parameter -> Boolean Parameter (布爾參數(shù))
Name : bool
Default Value : 勾選
Description : Choose bool value

Add Parameter -> Password Parameter (密碼參數(shù))
Name : pass
Default Value : 123456
Description : Type your password

# Build配置
選則 Build秦踪,點擊 Add build step褐捻,選則 Execute shell
在 command 中輸入

#!/bin/sh
echo "Current deploy environment is $deploy_env"
echo "The build is $version"
echo "The paasword is $pass"
 
if $bool
then
    echo "Request is approved"
else
    echo "Request is rejected"
fi

Jenkins Ansible 集成

# 需要配置被遠(yuǎn)程部署的機器無密碼訪問,且需要準(zhǔn)備testserver文件
vim testservers

[testserver]
k8s-node1 ansible_user=root

# Jenkins 進入 New Item 新建任務(wù)
輸入 ansible-freestyle-job 選擇Freestyle project
# 編輯描述信息
Description:This is my first ansible job
# Build配置
選則 Build椅邓,點擊 Add build step柠逞,選則 Execute shell
在 command 中輸入

#!/bin/sh
set +x
source /root/ansible/hacking/env-setup -q

cd /root/
ansible --version
ansible-playbook --version
cat testservers
ansible -i testservers testserver -m command -a "ip addr"
set -x

Freestyle Job 實戰(zhàn)

三劍客環(huán)境搭建

確保兩臺服務(wù)器一臺 gitlab.example.com 提供 gitlab 代碼倉庫服務(wù), 一臺 jenkins.example.com 提供 jenkins + ansible 服務(wù)景馁。兩臺服務(wù)器三個服務(wù)部署主機 test.example.com 靜態(tài)網(wǎng)頁

環(huán)境配置

# 克隆 ansible-playbook 項目到本地
cd repo
git -c http.sslVerify=false clone https://gitlab.example.com/root/ansible-playbook-repo.git
cp -a test_playbooks nginx-playbooks
cd nginx-playbooks

# 編輯 ansible 入口文件
vim deploy.yml

- hosts: "nginx"
  gather_facts: true
  remote_user: root
  roles:
    - nginx
    
# 編輯 inverntory 服務(wù)詳細(xì)清單目錄
cd inverntory/
vim testenv

[nginx]
test.example.com

[nginx:vars]
server_name=test.example.com
port=80
user=deploy
worker_processes=4
max_open_file=65505
root=/www

cp testenv prod
mv testenv dev

# 編輯 roles 詳細(xì)任務(wù)列表目錄
cd ../roles/
mv testbox/ nginx
cd nginx/
cd files/
rm -rf foo.sh
echo "This is my first website" > index.html
vim health_check.sh

#!/bin/sh
URL=$1
curl -Is http://$URL > /dev/null && echo "The remote side is healthy" || echo "The remote side is failed, please check"

vim ../tasks/main.yml

- name: Disable system firewall
  service: name=firewalld state=stopped

- name: Disable SELINUX
  selinux: state=disabled

- name: setup nginx yum source
  yum: pkg=epel-release state=latest

- name: write then nginx config file
  template: src=roles/nginx/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf

- name: create nginx root folder
  file: 'path={{ root }} state=directory owner={{ user }} group={{ user }} mode=0755'

- name: copy index.html to remote
  copy: 'remote_src=no src=roles/nginx/files/index.html dest=/www/index.html mode=0755'

- name: restart nginx service
  service: name=nginx state=restarted

- name: run the health check locally
  shell: "sh roles/nginx/files/health_check.sh {{ server_name }}"
  delegate_to: localhost
  register: health_status

- debug: msg="{{ health_status.stdout }}"

# delegate_to: localhost 代表在本地執(zhí)行腳本 而不是目標(biāo)主機

# 添加修改后的 ansible-playbook 項目到 gitlab
git add .
# 提交
git commit -m"This is my first nginx commit"
#  輸入賬號密碼板壮,同步本地master分支到遠(yuǎn)程服務(wù)器當(dāng)中
git -c http.sslVerify=false push origin master

Freestyle 任務(wù)構(gòu)建和自動化部署

# 進入 Jenkins 
# Jenkins 進入 New Item 新建任務(wù)
輸入 shell-freestyle-job 選擇Freestyle project
# 編輯描述信息
Description:This is my first nginx shell job
# 選擇參數(shù)化構(gòu)建過程,添加參數(shù)
# This project is parameterized -> Add Parameter -> Choice Parameter (選項參數(shù))
Name : deploy_env
Choices : dev
         prod
Description : Choose deploy environment
# 選擇 add Parameter 選擇 String Parameter (文本參數(shù))
Name : branch
Default Value : master
Description : Build branch
# 配置源代碼管理
進入 gitlab 倉庫合住, 選擇 Administrator / test-repo 代碼倉庫 clone URL
將 https://gitlab.example.com/root/ansible-playbook-repo.git 粘貼到
Jenkins Source Code Management 的 Git 選項中的 Repository URL
Credentials 選擇之前創(chuàng)建的 Git Credential 憑據(jù) (憑據(jù)驗證通過可以看到錯誤消失)
# Build配置 -e branch=$branch -e env=$deploy_env 表示在 jenkins 的環(huán)境變量引入到 ansible
選則 Build绰精,點擊 Add build step,選則 Execute shell
在 command 中輸入

#!/bin/sh

set +x
source /home/deploy/.py3-a2.5-env/bin/activate
source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q

cd $WORKSPACE/nginx-playbooks
ansible --version
ansible-playbook --version

ansible-playbook -i inventory/$deploy_env ./deploy.yml -e project=nginx -e branch=$branch -e env=$deploy_env

# 保存并開始構(gòu)建
# 訪問部署目標(biāo)主機的域名或ip地址透葛,即可訪問

Pipeline Job 實戰(zhàn)

Nginx + Mysql + PHP + Wordpress 自動化部署交付

三劍客平臺初始環(huán)境構(gòu)建

編寫 ansible playbook 腳本實現(xiàn)WordPress遠(yuǎn)程部署

將WordPress源碼與playbook部署腳本提交到GitLab倉庫

編寫Pipeline Job 腳本實現(xiàn) Jenkins 流水線持續(xù)交付流程

Jenkins 集成 Ansible 與 GitLab 實現(xiàn) Wordpress的自動化部署

環(huán)境配置

# 克隆 ansible-playbook 項目到本地
cd repo
git -c http.sslVerify=false clone https://gitlab.example.com/root/ansible-playbook-repo.git
cp -a test_playbooks wordpress-playbooks
cd wordpress-playbooks
# 關(guān)閉 gitssl 安全認(rèn)證
git config --global http.sslVerify false

# 編輯 ansible 入口文件
vim deploy.yml

- hosts: "wordpress"
  gather_facts: true
  remote_user: root
  roles:
    - wordpress
    
# 編輯 inverntory 服務(wù)詳細(xì)清單目錄
cd inverntory/
vim testenv

[wordpress]
test.example.com

[wordpress:vars]
server_name=test.example.com
port=80
user=deploy
worker_processes=4
max_open_file=65505
root=/data/www
gitlab_user='root'
gitlab_pass='1234qwer'

cp testenv prod
mv testenv dev

# 編輯 roles 詳細(xì)任務(wù)列表目錄
cd ../roles/
mv testbox/ wordpress
cd files/
rm -rf foo.sh
echo "<?php phpinfo(); ?>" > info.php
vim health_check.sh

#!/bin/sh
URL=$1
PORT=$2
curl -Is http://$URL:$PORT/info.php > /dev/null && echo "The remote side is healthy" || echo "The remote side is failed, please check"

# php-fpm配置笨使,www.conf文件信息在下方
vim www.conf

# 配置 nginx
cd ../templates
vim nginx.conf.j2

vim ../tasks/main.yml

- name: Update yum dependency
  shell: 'yum update -y warn=False'

- name: Disable system firewall
  service: name=firewalld state=stopped

- name: Disable SELINX
  selinux: state=disabled

- name: Setup epel yum source for nginx and mariadb(mysql)
  yum: pkg=epel-release state=latest

- name: Setup webtatic yum source for php-fpm
  yum: name=https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

- name: Ensure nginx is at the latest version
  yum: pkg=nginx state=latest

- name: Write the nginx config file
  template: src=roles/wordpress/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf

- name: Create nginx root folder
  file: 'path={{ root }} state=directory owner={{ user }} group={{ user }} mode=0755'

- name: Copy info.php to remote
  copy: 'remote_src=no src=roles/wordpress/files/info.php dest=/data/www/info.php mode=0755'

- name: Restart nginx service
  service: name=nginx state=restarted

- name: Setup php-fpm
  command: 'yum install -y php70w php70w-fpm php70w-common php70w-mysql php70w-gd php70w-xml php70w-mbstring php70w-mcrypt warn=False'

- name: Restart php-fpm service
  service: name=php-fpm state=restarted

- name: Copy php-fpm config file to remote
  copy: 'remote_src=no src=roles/wordpress/files/www.conf dest=/etc/php-fpm.d/www.conf mode=0755 owner={{ user }} group={{ user }} force=yes'

- name: Restart php-fpm service
  service: name=php-fpm state=restarted

- name: Run the health check locally
  shell: "sh roles/wordpress/files/health_check.sh {{ server_name }} {{ port }}"
  delegate_to: localhost
  register: health_status

- debug: msg="{{ health_status.stdout }}"

- name: Setup mariadb(mysql)
  command: "yum install -y mariadb mariadb-server warn=False"

- name: Backup current www folder
  shell: 'mv {{ root }} {{ backup_to }}'

- name: Close git ssl verification
  shell: 'git config --global http.sslVerify false'

- name: Clone WordPress repo to remote
  git: "repo=https://{{ gitlab_user | urlencode }}:{{ gitlab_pass | urlencode }}@gitlab.example.com/root/Wordpress-project.git dest=/data/www version={{ branch }}"
  when: project == 'wordpress'

- name: Change www folder permission
  file: "path=/data/www mode=0755 owner={{ user }} group={{ user }}"

# delegate_to: localhost 代表在本地執(zhí)行腳本 而不是目標(biāo)主機

# 添加修改后的 ansible-playbook 項目到 gitlab
git add .
# 提交
git commit -m"This is my first wordpress commit"
#  輸入賬號密碼,同步本地master分支到遠(yuǎn)程服務(wù)器當(dāng)中
git -c http.sslVerify=false push origin master

Pipeline 任務(wù)構(gòu)建和自動化部署

# 進入 Jenkins 
# Jenkins 進入 New Item 新建任務(wù)
輸入 shell-freestyle-job 選擇 Pipeline project
# 編輯描述信息
Description:This is my first nginx shell job
# 編寫 groovy 腳本, 添加到 Pipeline 下的 Pipleline Script
#!groovy

pipeline {
    agent {node {label 'master'}}

    environment {
        PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
    }

    parameters {
        choice(
            choices: 'dev\nrprod',
            description: 'Choose deploy environment',
            name: 'deploy_env'
        )
        string (name: 'branch', defaultValue: 'master', description: 'Fill in your ansible repo branch')
    }

    stages {
        stage ("Pull deploy code") {
            steps{
                sh 'git config --global http.sslVerify false'
                dir ("${env.WORKSPACE}"){
                    git branch: 'master', credentialsId: '9aa11671-aab9-47c7-a5e1-a4be146bd587', url: 'https://gitlab.example.com/root/ansible-playbook-repo.git'
                }
            }

        }

        stage ("Check env") {
            steps {
                sh """
                set +x
                user=`whoami`
                if [ $user == deploy ]
                then
                    echo "[INFO] Current deployment user is $user"
                    source /home/deploy/.py3-a2.5-env/bin/activate
                    source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
                    echo "[INFO] Current python version"
                    python --version
                    echo "[INFO] Current ansible version"
                    ansible-playbook --version
                    echo "[INFO] Remote system disk space"
                    ssh root@test.example.com df -h
                    echo "[INFO] Rmote system RAM"
                    ssh root@test.example.com free -m
                else
                    echo "Deployment user is incorrect, please check"
                fi

                set -x
                """
            }
        }

        stage ("Anisble deployment") {
            steps {
                input "Do you approve the deployment?"
                dir("${env.WORKSPACE}/wordpress_playbooks"){
                    echo "[INFO] Start deployment"
                    sh """
                    set +x
                    source /home/deploy/.py3-a2.5-env/bin/activate
                    source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
                    ansible-playbook -i inventory/$deploy_env ./deploy.yml -e project=wordpress -e branch=$branch -e env=$deploy_env
                    set -x
                    """
                    echo "[INFO] Deployment finished..."
                }
            }
        }

    }

}
# 進入被部署主機僚害,初始化數(shù)據(jù)庫
systemctl start mariadb
mysql_secure_installation
y
root
1234qwer
y
y
y
y
mysql -uroot -p1234qwer
create database wordpress character set utf8;

# 訪問ip+8080端口 輸入數(shù)據(jù)庫空戶名密碼安裝wordpress即可

www.conf (用戶和所屬組為deploy)

; Start a new pool named 'www'.
[www]

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = deploy
; RPM: Keep a group allowed to write in log dir.
group = deploy

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
;listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php-fpm.sock


; Set listen(2) backlog.
; Default Value: 511 (-1 on FreeBSD and OpenBSD)
;listen.backlog = 511

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions.
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = deploy
listen.group = deploy
;listen.mode = 0660
; When POSIX Access Control Lists are supported you can set them using
; these options, value is a comma separated list of user/group names.
; When set, listen.owner and listen.group are ignored
;listen.acl_users =
;listen.acl_groups =

; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
listen.allowed_clients = 127.0.0.1

; Specify the nice(2) priority to apply to the pool processes (only if set)
; The value can vary from -19 (highest priority) to 20 (lower priority)
; Note: - It will only work if the FPM master process is launched as root
;       - The pool processes will inherit the master process priority
;         unless it specified otherwise
; Default Value: no set
; process.priority = -19

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives. With this process management, there will be
;             always at least 1 children.
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
;  ondemand - no children are created at startup. Children will be forked when
;             new requests will connect. The following parameter are used:
;             pm.max_children           - the maximum number of children that
;                                         can be alive at the same time.
;             pm.process_idle_timeout   - The number of seconds after which
;                                         an idle process will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 50

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 5

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 5

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 35

; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
;pm.process_idle_timeout = 10s;

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. It shows the following informations:
;   pool                 - the name of the pool;
;   process manager      - static, dynamic or ondemand;
;   start time           - the date and time FPM has started;
;   start since          - number of seconds since FPM has started;
;   accepted conn        - the number of request accepted by the pool;
;   listen queue         - the number of request in the queue of pending
;                          connections (see backlog in listen(2));
;   max listen queue     - the maximum number of requests in the queue
;                          of pending connections since FPM has started;
;   listen queue len     - the size of the socket queue of pending connections;
;   idle processes       - the number of idle processes;
;   active processes     - the number of active processes;
;   total processes      - the number of idle + active processes;
;   max active processes - the maximum number of active processes since FPM
;                          has started;
;   max children reached - number of times, the process limit has been reached,
;                          when pm tries to start more children (works only for
;                          pm 'dynamic' and 'ondemand');
; Value are updated in real time.
; Example output:
;   pool:                 www
;   process manager:      static
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          62636
;   accepted conn:        190460
;   listen queue:         0
;   max listen queue:     1
;   listen queue len:     42
;   idle processes:       4
;   active processes:     11
;   total processes:      15
;   max active processes: 12
;   max children reached: 0
;
; By default the status page output is formatted as text/plain. Passing either
; 'html', 'xml' or 'json' in the query string will return the corresponding
; output syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
;   http://www.foo.bar/status?xml
;
; By default the status page only outputs short status. Passing 'full' in the
; query string will also return status for each pool process.
; Example:
;   http://www.foo.bar/status?full
;   http://www.foo.bar/status?json&full
;   http://www.foo.bar/status?html&full
;   http://www.foo.bar/status?xml&full
; The Full status returns for each process:
;   pid                  - the PID of the process;
;   state                - the state of the process (Idle, Running, ...);
;   start time           - the date and time the process has started;
;   start since          - the number of seconds since the process has started;
;   requests             - the number of requests the process has served;
;   request duration     - the duration in μs of the requests;
;   request method       - the request method (GET, POST, ...);
;   request URI          - the request URI with the query string;
;   content length       - the content length of the request (only with POST);
;   user                 - the user (PHP_AUTH_USER) (or '-' if not set);
;   script               - the main script called (or '-' if not set);
;   last request cpu     - the %cpu the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because CPU calculation is done when the request
;                          processing has terminated;
;   last request memory  - the max amount of memory the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because memory calculation is done when the request
;                          processing has terminated;
; If the process is in Idle state, then informations are related to the
; last request the process has served. Otherwise informations are related to
; the current request being served.
; Example output:
;   ************************
;   pid:                  31330
;   state:                Running
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          63087
;   requests:             12808
;   request duration:     1250261
;   request method:       GET
;   request URI:          /test_mem.php?N=10000
;   content length:       0
;   user:                 -
;   script:               /home/fat/web/docs/php/test_mem.php
;   last request cpu:     0.00
;   last request memory:  0
;
; Note: There is a real-time FPM status monitoring sample web page available
;       It's available in: @EXPANDED_DATADIR@/fpm/status.html
;
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;pm.status_path = /status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;ping.path = /ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
;ping.response = pong

; The access log file
; Default: not set
;access.log = log/$pool.access.log

; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request
;      it can accept the following format:
;      - %{user}C for user CPU only
;      - %{system}C for system CPU only
;      - %{total}C  for user + system CPU (default)
;  %d: time taken to serve the request
;      it can accept the following format:
;      - %{seconds}d (default)
;      - %{miliseconds}d
;      - %{mili}d
;      - %{microseconds}d
;      - %{micro}d
;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some exemples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
;  %f: script filename
;  %l: content-length of the request (for POST request only)
;  %m: request method
;  %M: peak of memory allocated by PHP
;      it can accept the following format:
;      - %{bytes}M (default)
;      - %{kilobytes}M
;      - %{kilo}M
;      - %{megabytes}M
;      - %{mega}M
;  %n: pool name
;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o
;      - ....
;  %p: PID of the child that serviced the request
;  %P: PID of the parent of the child that serviced the request
;  %q: the query string
;  %Q: the '?' character if query string exists
;  %r: the request URI (without the query string, see %q and %Q)
;  %R: remote IP address
;  %s: status (response code)
;  %t: server time the request was received
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;      The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
;  %T: time the log has been written (the request has finished)
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;      The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"

; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
slowlog = /var/log/php-fpm/www-slow.log

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: chrooting is a great security feature and should be used whenever
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot =

; Chdir to this directory at the start.
; Note: relative path can be used.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Note: on highloaded environement, this can cause some delay in the page
; process time (several ms).
; Default Value: no
;catch_workers_output = yes

; Clear environment in FPM workers
; Prevents arbitrary environment variables from reaching FPM worker processes
; by clearing the environment in workers before env vars specified in this
; pool configuration are added.
; Setting to "no" will make all environment variables available to PHP code
; via getenv(), $_ENV and $_SERVER.
; Default Value: yes
;clear_env = no

; Limits the extensions of the main script FPM will allow to parse. This can
; prevent configuration mistakes on the web server side. You should only limit
; FPM to .php extensions to prevent malicious users to use other extensions to
; exectute php code.
; Note: set an empty value to allow all extensions.
; Default Value: .php
;security.limit_extensions = .php .php3 .php4 .php5 .php7

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'.
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 128M

; Set session path to a directory owned by process user
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/lib/php/session
php_value[soap.wsdl_cache_dir]  = /var/lib/php/wsdlcache

nginx.conf.j2

# For more information on configuration, see: 
user              {{ user }};  
worker_processes  {{ worker_processes }};  
  
error_log  /var/log/nginx/error.log;  
  
pid        /var/run/nginx.pid;  
  
events {  
    worker_connections  {{ max_open_file }};  
}  
  
  
http {  
    include       /etc/nginx/mime.types;  
    default_type  application/octet-stream;  
  
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '  
                      '$status $body_bytes_sent "$http_referer" '  
                      '"$http_user_agent" "$http_x_forwarded_for"';  
  
    access_log  /var/log/nginx/access.log  main;  
  
    sendfile        on;  
    #tcp_nopush     on;  
  
    #keepalive_timeout  0;  
    keepalive_timeout  65;  
  
    #gzip  on;  
      
    # Load config files from the /etc/nginx/conf.d directory  
    # The default server is in conf.d/default.conf  
    #include /etc/nginx/conf.d/*.conf;  
    server {  
        listen       {{ port }} default_server;  
        server_name  {{ server_name }};  
        root         {{ root }};
        #charset koi8-r;  
  
        location / {  
            index  index.html index.htm index.php;  
        }  
  
        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
  
    }  
  
}
---
# possible saved as remove_oldder_version_docker.yml
- name: remove oldder version docker
  yum: 
    name: "{{ item }}"
    state: absent
  with_items:
    - docker
    - docker-client
    - docker-client-latest
    - mysql-devel
    - openssl-devel
    - python-devel
    - python-setuptools
    - python-virtualenv
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末硫椰,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌靶草,老刑警劉巖蹄胰,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異爱致,居然都是意外死亡烤送,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門糠悯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人妻往,你說我怎么就攤上這事互艾。” “怎么了讯泣?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵纫普,是天一觀的道長。 經(jīng)常有香客問我好渠,道長昨稼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任拳锚,我火速辦了婚禮假栓,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘霍掺。我一直安慰自己匾荆,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布杆烁。 她就那樣靜靜地躺著牙丽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪兔魂。 梳的紋絲不亂的頭發(fā)上烤芦,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音析校,去河邊找鬼构罗。 笑死,一個胖子當(dāng)著我的面吹牛勺良,可吹牛的內(nèi)容都是我干的绰播。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼尚困,長吁一口氣:“原來是場噩夢啊……” “哼蠢箩!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤谬泌,失蹤者是張志新(化名)和其女友劉穎滔韵,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體掌实,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡陪蜻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了贱鼻。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宴卖。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖邻悬,靈堂內(nèi)的尸體忽然破棺而出症昏,到底是詐尸還是另有隱情,我是刑警寧澤父丰,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布肝谭,位于F島的核電站,受9級特大地震影響蛾扇,放射性物質(zhì)發(fā)生泄漏攘烛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一镀首、第九天 我趴在偏房一處隱蔽的房頂上張望坟漱。 院中可真熱鬧,春花似錦蘑斧、人聲如沸靖秩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽沟突。三九已至,卻和暖如春捕传,著一層夾襖步出監(jiān)牢的瞬間惠拭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工庸论, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留职辅,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓聂示,卻偏偏與公主長得像域携,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鱼喉,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355