美文网首页
Jenkins + Ansible + Gitlab 自动化部署

Jenkins + Ansible + Gitlab 自动化部署

作者: 全村滴希望 | 来源:发表于2020-06-22 21:07 被阅读0次

    Jenkins + Ansible + Gitlab 自动化部署三剑客

    Gitlab

    准备linux初始环境

    # 关闭防火墙
    systemctl stop firewalld
    # 开机自动关闭
    systemctl disable firewalld
    # 强制关闭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邮件服务
    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安装向导
    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密钥和证书创建签署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下的所有证书权限
    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相关服务配置
    gitlab-ctl reconfigure 
    # 找到gitlab下的ningx反向代理工具, 更改gitlab的http配置文件
    vim /var/opt/gitlab/nginx/conf/gitlab-http.conf
    # 在 server_name 下面一行添加如下,用来重定向所有getlab的http请求
    rewrite ^(.*)$ https://$host$1 permanent;
    gitlab-ctl restart
    # 即可访问服务器地址访问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 选择默认 Private,创建好后复制仓库http地址 COPY URL
    # 回到服务器,在用户下创建 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"
    # 提示创建本地git全局的邮箱和用户名,再次运行 git commit -m"First commit" 即可提交成功
    git config --global user.email "admin@example.com"
    git config --global user.name "admin"
    # 输入账号密码,同步本地master分支到远程服务器当中
    git -c http.sslVerify=false push origin master
    
    # 查看当前全局用户配置
    git config --global --list
    # 创建代码分支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分支到远程服务器当中
    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确认一遍,还有没有gitlab的进程
    # 删除所有包含gitlab文件
    find / -name gitlab | xargs rm -rf
    

    Ansible

    安装与配置

    # 关闭防火墙
    systemctl stop firewalld
    # 开机自动关闭
    systemctl disable firewalld
    # 强制关闭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 匹配当前系统的参数值
    ./configure --prefix=/usr/local/python3 --enable-optimizations --with-ssl
    make && make install
    
    # 安装python虚拟环境
    pip3 install virtualenv
    # 在新用户下创建 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环境
    source /home/deploy/.py3-a2.5-env/bin/activate
    # 安装ansible依赖包
    pip3 install paramiko PyYAML jinja2
    # 把ansible源代码移动到python3.6的virtualenv环境下
    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后还是出现 No module named jinja2, 可以直接yum安装 yum install -y python-jinja2 python-yaml

    playbooks 测试 (需要先配置好服务器和部署主机的ssh无密码访问)

    # 加载virtualenv环境
    source /home/deploy/.py3-a2.5-env/bin/activate
    # 加载ansible
    source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
    # 验证是否开启ansible服务
    ansible-playbook --version
    # 创建如下目录结构
    (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详细清单目录,里面存放具体清单与变量声明文件,用于保存目标部署主机的相关域名和ip地址以及变量参数
    # roles 为详细任务列表目录,里面存放一个或者多个 role,通常被命名为具体的APP或者项目名称,这里命名为 testbox 作为项目名称,下面的 tasks 目录用来保存 testbox 主任务文件 main.yml,deploy.yml 作为 playbook 任务入口文件,将调度 roles 下需要部署的项目,以及该项目下的所有任务,最终将该任务部署在 inventory 下定义的目标主机中
    
    vim testenv
    
    [testservers]
    test.example.com
    
    [testservers:vars]
    server_name=test.example.com
    user=root
    output=/root/test.txt
    
    # [testservers] 为 Server 组列表,下面包含目标部署服务器的主机名,可以是域名也可以是ip地址
    # [testservers:vars] 为 testservers 组的列表参数,下面包含该组下的目标主机需要的 Key/value 键值对参数
    
    vim main.yml
    
    - name: Print server name and user to remote testbox
      shell: "echo 'Currently {{ user }} is logining {{ server_name}}' > {{ output}}" 
      
    # name 为任务名称,方便知道该 task 是做什么用的
    # shell 为使用shell模块执行命令,双括号里为引入 testenv 中的 [testservers:vars] 参数
    
    vim deploy.yml
    
    - hosts: "testservers" # 对应 testenv 中的 server 标签,调用该标签下的目标主机
      gather_facts: true  # 获取目标主机下的信息
      remote_user: root   # 在目标主机下使用root权限
      roles:
        - testbox        # 进入目标下的testbox目录
    
    # ansible 核心文件,与 ansible-playbook 命令直接对话
    # 执行部署
    ansible-playbook -i inventory/testenv ./deploy.yml
    

    Ansible Playbooks 常用模块应用

    # File模块  创建文件或目录,并赋予系统权限
    - name: create a file
      file: 'path=/root/foo.txt state=touch mode=0775 owner=foo group=foo'
    # 实现Ansible服务端到目标主机的文件传送 force=yes 强制执行
    - name: copy a file
      copy: 'remote_src=no src=roles/testbox/files/foo.sh dest=/root/foo.sh mode=0644 force=yes'
    # Stat模块 获取远程文件状态信息 register: script_stat 把状态信息赋值给script_stat 变量
    - name: check if foo.sh exists
      stat: 'path=/root/foo.sh'
      register: script_stat
    # Debug模块 打印语句到Ansible执行输出 debug: msg=foo.sh exists 表示输出信息为foo.sh exists
    - debug: msg="foo.sh exists"
      when: script_stat.stat.exists
    # Command/Shell模块 用来执行Linux目标主机命令行 shell会调用linux下的bin/bash,就可以使用系统环境变量、重定向符、管道符等
    - name: run the script
      command: "sh /root/foo.sh"
    - name: run the script
      shell: "echo 'test' > /root/test.txt"
    # Template模块 实现Ansible服务端到目标主机的jinja2模板传送 nginx.conf.j2中的变量参数会调用server清单里的var变量参数值
    - name: write the nginx config file
      template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf
    # Packaging模块 调用目标主机系统包管理工具(yum,apt)进行安装 yum包装目标系统为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模块 管理目标主机系统服务
    - name: start nginx service
      service: name=nginx state=started
    

    注意 commond 模块和 shell 模块类似,但有区别

    command 模块命令将不会使用 shell 执行. 因此, 像 $HOME 这样的变量是不可用的。还有像<, >, |, ;, &都将不可用。

    shell 模块通过shell程序执行, 默认是/bin/sh, <, >, |, ;, & 可用。但这样有潜在的 shell 注入风险, 后面会详谈.

    command 模块更安全,因为他不受用户环境的影响。 也很大的避免了潜在的 shell 注入风险.

    register 是将该模块执行后的输出写入到变量,变量的命名不能用 -中横线,比如dev-sda6_result,则会被解析成sda6_result,dev会被丢掉,所以不要用 - 。全局变量或者 role 下的vars 变量也不要用 -

    ignore_errors这个关键字很重要,一定要配合设置成True,否则如果命令执行不成功,即 echo $?不为0,则在其语句后面的ansible语句不会被执行,导致程序中止。

    实例

    # 加载virtualenv环境
    source /home/deploy/.py3-a2.5-env/bin/activate
    # 加载ansible
    source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
    # 验证是否开启ansible服务
    ansible-playbook --version
    
    # 进入目标主机配置,为了保证目标服务器的任务顺利执行
    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
    
    # 创建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
      
    # 执行部署
    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分支到远程服务器当中
    git -c http.sslVerify=false push origin master
    

    jenkins

    安装与配置

    # 关闭防火墙
    systemctl stop firewalld
    # 开机自动关闭
    systemctl disable firewalld
    # 强制关闭selinux
    vim /etc/sysconfig/selinux
    SELINUX=disabled
    # 查看selinux策略是否被禁用(Disabled)
    getenforce
    # 下载yum源,并在本地导入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 环境
    yum install -y java
    
    # 安装jenkins
    yum install -y jenkins
    # 添加新用户
    useradd deploy
    # 编辑 jenkins 配置文件
    vim /etc/sysconfig/jenkins
    
    JENKINS_USER="deploy"
    JENKINS_PORT="8080"
    # 改编jenkins默认的家目录,以及log日志目录的属组和属组权限
    chown -R deploy:deploy /var/lib/jenkins
    chown -R deploy:deploy /var/log/jenkins
    # 启动jenkins服务
    systemctl start jenkins
    # 确认服务是否正常启动
    lsof -i:8080
    
    # 访问主机的ip:8080 可配置dns访问,这里配置jenkins.example.com
    # 解锁jenkins,在服务器找到日志中的密码
    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>
    
    # 根据web提示安装即可
    

    Jenkins Job 构建配置

    环境配置

    # 配置 Jenkins server 本地 Gitlab DNS
    如果使用域名登录就绑定下本机的host
    # 安装 git client, curl 工具依赖
    yum install -y git curl
    # 关闭系统 Git http.sslVerify 安全认证
    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 凭据
    进入 Manage Jenkins, Manage Credentials, 进入 Stores scoped to Jenkins 的Jenkins 添加凭据,输入 root和密码
    

    Jenkins freestyle Job 构建配置

    # Jenkins 进入 New Item 新建任务
    输入 test-freestyle-job 选择Freestyle project
    # 编辑描述信息
    Description:This is my first test freestyle job
    # 添加参数配置
    选则 This project is parameterized 
    选择 add Parameter 选择 Choice Parameter (选项参数)
    Name : deploy_env
    Choices : dev
             prod (分别为开发环境和生产环境)
    Description : Choose deploy environment
    选择 add Parameter 选择 String Parameter (文本参数)
    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 选择之前创建的 Git Credential 凭据 (凭据验证通过可以看到错误消失)
    # 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 构建配置

    # Jenkins -> Manage Jenkins -> Manage Plugins -> Available 搜索 pipeline 找到 Pipeline 安装插件后重启
    # Jenkins 进入 New Item 新建任务
    输入 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 新建任务
    输入 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 参数集成

    # Jenkins 进入 New Item 新建任务
    输入 parameter-freestyle-job 选择Freestyle project
    # 编辑描述信息
    Description:This is my first parameter job
    # 选择参数化构建过程,添加参数
    This project is parameterized -> Add Parameter -> Choice Parameter (选项参数)
    Name : deploy_env
    Choices : dev
             uat
             stage 
             prod
    Description : Choose deploy environment
    
    Add Parameter -> String Parameter (文本参数)
    Name : version
    Default Value : 1.0.0
    Description : Fill in build version
    
    Add Parameter -> Boolean Parameter (布尔参数)
    Name : bool
    Default Value : 勾选
    Description : Choose bool value
    
    Add Parameter -> Password Parameter (密码参数)
    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 集成

    # 需要配置被远程部署的机器无密码访问,且需要准备testserver文件
    vim testservers
    
    [testserver]
    k8s-node1 ansible_user=root
    
    # Jenkins 进入 New Item 新建任务
    输入 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 实战

    三剑客环境搭建

    确保两台服务器一台 gitlab.example.com 提供 gitlab 代码仓库服务, 一台 jenkins.example.com 提供 jenkins + ansible 服务。两台服务器三个服务部署主机 test.example.com 静态网页

    环境配置

    # 克隆 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 服务详细清单目录
    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 详细任务列表目录
    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 代表在本地执行脚本 而不是目标主机
    
    # 添加修改后的 ansible-playbook 项目到 gitlab
    git add .
    # 提交
    git commit -m"This is my first nginx commit"
    #  输入账号密码,同步本地master分支到远程服务器当中
    git -c http.sslVerify=false push origin master
    

    Freestyle 任务构建和自动化部署

    # 进入 Jenkins 
    # Jenkins 进入 New Item 新建任务
    输入 shell-freestyle-job 选择Freestyle project
    # 编辑描述信息
    Description:This is my first nginx shell job
    # 选择参数化构建过程,添加参数
    # This project is parameterized -> Add Parameter -> Choice Parameter (选项参数)
    Name : deploy_env
    Choices : dev
             prod
    Description : Choose deploy environment
    # 选择 add Parameter 选择 String Parameter (文本参数)
    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 选择之前创建的 Git Credential 凭据 (凭据验证通过可以看到错误消失)
    # Build配置 -e branch=$branch -e env=$deploy_env 表示在 jenkins 的环境变量引入到 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
    
    # 保存并开始构建
    # 访问部署目标主机的域名或ip地址,即可访问
    

    Pipeline Job 实战

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

    三剑客平台初始环境构建

    编写 ansible playbook 脚本实现WordPress远程部署

    将WordPress源码与playbook部署脚本提交到GitLab仓库

    编写Pipeline Job 脚本实现 Jenkins 流水线持续交付流程

    Jenkins 集成 Ansible 与 GitLab 实现 Wordpress的自动化部署

    环境配置

    # 克隆 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
    # 关闭 gitssl 安全认证
    git config --global http.sslVerify false
    
    # 编辑 ansible 入口文件
    vim deploy.yml
    
    - hosts: "wordpress"
      gather_facts: true
      remote_user: root
      roles:
        - wordpress
        
    # 编辑 inverntory 服务详细清单目录
    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 详细任务列表目录
    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 代表在本地执行脚本 而不是目标主机
    
    # 添加修改后的 ansible-playbook 项目到 gitlab
    git add .
    # 提交
    git commit -m"This is my first wordpress commit"
    #  输入账号密码,同步本地master分支到远程服务器当中
    git -c http.sslVerify=false push origin master
    

    Pipeline 任务构建和自动化部署

    # 进入 Jenkins 
    # Jenkins 进入 New Item 新建任务
    输入 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..."
                    }
                }
            }
    
        }
    
    }
    
    # 进入被部署主机,初始化数据库
    systemctl start mariadb
    mysql_secure_installation
    y
    root
    1234qwer
    y
    y
    y
    y
    mysql -uroot -p1234qwer
    create database wordpress character set utf8;
    
    # 访问ip+8080端口 输入数据库空户名密码安装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
    

    相关文章

      网友评论

          本文标题:Jenkins + Ansible + Gitlab 自动化部署

          本文链接:https://www.haomeiwen.com/subject/awwffktx.html