Jenkins+Gitlab+Ansible自動化配置(二)

69820 ワード

Jenkins+Gitlab+Ansible自動化配置(二)
Jenkins+Gitlab+Ansbile自動化配置(一):https://www.cnblogs.com/zd520pyx1314/p/10210727.html
Ansibleの構成と導入
ツール名
紹介する
Chef
Ruby作成、C/Sアーキテクチャを採用し、構成にはGit依存、Recipeスクリプト作成規範が必要であり、良好なプログラミング経験が必要である.
Ansible
Python作成、Clientなし、モジュール化配置管理、Playbookスクリプト作成規範を採用し、使いやすく、中小規模の迅速な配置に適している.
Saltstack
Python作成、C/Sアーキテクチャ、モジュール化配置管理、YAMLスクリプト作成規範を採用し、内蔵非同期ファイルサーバーはクライアントファイルのサービス速度を速めることができ、大規模なクラスタ配置に適しているが、クライアントをインストールする必要がある.
 
 
 
 
 
 
Ansibleの利点と適用シーン
メリット:
  • 軽量レベルクライアントなし(Agentless);
  • オープンソースは無料で、学習コストが低く、迅速に手に入る.
  • playbookをコア構成アーキテクチャとして使用し、同意したスクリプトフォーマットのバッチ化配置;
  • 完全なモジュール化拡張、現在の主流の開発環境をサポートする.
  • の強力な安定性と互換性.
  • 活発な公式コミュニティ問題の討論は、troubleshootingとdebug問題を便利にする.

  • Ansible配合virtualenvインストール構成
    python独自のpython virtualenvツールを使用してPython 3を分離します.6、Ansible2.5およびシステムの他のpython依存環境.
    Ansible取付方式
    1.yumワンタッチインストール(推奨しない)
    [root@ansible ~]# yum install -y ansible
    #     ,                

    2.Gitソースコードのインストール(推奨)
    [root@ansible ~]# yum install -y git      #       git  ,          
    [root@ansible ~]# git clone https://github.com/ansible/ansible.git

    Ansible2.5+Python3.6インストール手順
    1.python 3をインストールする.6.5およびvirtualenvツール
    [root@ansible ~]# wget http://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz
    [root@ansible ~]# tar -xf Python-3.6.5.tar.xz -C /usr/local/src/
    [root@ansible ~]# cd /usr/local/src/Python-3.6.5/
    [root@ansible ~]# cd /usr/local/src/Python-3.6.5/
    [root@ansible Python-3.6.5]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
    #    
    configure: error: in `/usr/local/src/Python-3.6.5':
    configure: error: no acceptable C compiler found in $PATH
    See `config.log' for more details
    #       ,    GCC  
    [root@ansible Python-3.6.5]# yum install -y gcc 
    #           ,      
    [root@ansible Python-3.6.5]# make && make altinstall
    #       
    ....
        import pip
    zipimport.ZipImportError: can't decompress data; zlib not available
    make: *** [altinstall] Error 1
    #           
    [root@ansible Python-3.6.5]# yum install zlib*
    #             
    [root@ansible Python-3.6.5]# make && make altinstall
    #    
    .....
    Collecting setuptools
    Collecting pip
    Installing collected packages: setuptools, pip
    Successfully installed pip-9.0.3 setuptools-39.0.1
    #       
    #     virtualenv,      
    [root@ansible bin]# pwd
    /usr/local/bin
    [root@ansible bin]# ./pip --trusted-host pypi.python.org install virtualenv
    pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
    Collecting virtualenv
      Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
      Could not find a version that satisfies the requirement virtualenv (from versions: )
    No matching distribution found for virtualenv
    #              --trusted-host  , ...    
    [root@ansible bin]# ./pip --trusted-host pypi.python.org install virtualenv
    pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
    Collecting virtualenv
      Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
      Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
      Could not find a version that satisfies the requirement virtualenv (from versions: )
    No matching distribution found for virtualenv
    #          
    pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available
    #     openssl     
    [root@ansible bin]# yum install -y openssl*
    #    ,   python2.7   pip    
    [root@ansible bin]# python -m pip uninstall pip
    Uninstalling pip-18.1:
      Would remove:
        /usr/bin/pip
        /usr/bin/pip2
        /usr/bin/pip2.7
        /usr/lib/python2.7/site-packages/pip-18.1.dist-info/*
        /usr/lib/python2.7/site-packages/pip/*
    Proceed (y/n)? y
      Successfully uninstalled pip-18.1
    #         ,          
    [root@ansible Python-3.6.5]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
    [root@ansible Python-3.6.5]# make && make altinstall 
    .......
    Requirement already satisfied: setuptools in /usr/local/lib/python3.6/site-packages
    Requirement already satisfied: pip in /usr/local/lib/python3.6/site-packages
    [root@ansible Python-3.6.5]# cd ../../bin/
    [root@ansible bin]# ll
    total 68
    -rwxr-xr-x. 1 root root   101 Jan  7 11:42 2to3-3.6
    -rwxr-xr-x. 1 root root   242 Jan  7 11:00 easy_install-3.6
    -rwxr-xr-x. 1 root root    99 Jan  7 11:42 idle3.6
    lrwxrwxrwx. 1 root root    21 Jan  7 11:03 pip -> /usr/local/bin/pip3.6
    -rwxr-xr-x. 1 root root   214 Jan  7 11:00 pip3.6
    -rwxr-xr-x. 1 root root    84 Jan  7 11:42 pydoc3.6
    -rwxr-xr-x. 2 root root 17712 Jan  7 11:41 python3.6
    -rwxr-xr-x. 2 root root 17712 Jan  7 11:41 python3.6m
    -rwxr-xr-x. 1 root root  3109 Jan  7 11:42 python3.6m-config
    -rwxr-xr-x. 1 root root   441 Jan  7 11:42 pyvenv-3.6
    [root@ansible bin]# ln -s /usr/local/bin/pip3.6 /usr/local/bin/pip
    #     pip  virtualenv
    [root@ansible bin]# pip install virtualenv
    Collecting virtualenv
      Cache entry deserialization failed, entry ignored
      Cache entry deserialization failed, entry ignored
      Downloading https://files.pythonhosted.org/packages/6a/d1/e0d142ce7b8a5c76adbfad01d853bca84c7c0240e35577498e20bc2ade7d/virtualenv-16.2.0-py2.py3-none-any.whl (1.9MB)
        100% |████████████████████████████████| 1.9MB 64kB/s
    Requirement already satisfied: setuptools>=18.0.0 in /usr/local/lib/python3.6/site-packages (from virtualenv)
    Installing collected packages: virtualenv
    Successfully installed virtualenv-16.2.0
    You are using pip version 9.0.3, however version 18.1 is available.
    You should consider upgrading via the 'pip install --upgrade pip' command.
    #     

    2.ansibleアカウントを作成しpython 3をインストールする.6.5バージョンvirtualenvインスタンス
    [root@ansible ~]# useradd deploy && su - deploy
    [deploy@ansible ~]$ virtualenv -p /usr/local/bin/python3.6 .py3-a2.5-env
    Already using interpreter /usr/local/bin/python3.6
    Using base prefix '/usr/local'
    New python executable in /home/deploy/.py3-a2.5-env/bin/python3.6
    Also creating executable in /home/deploy/.py3-a2.5-env/bin/python
    Installing setuptools, pip, wheel...
    done.
    [deploy@ansible ~]$

    3.Gitソースコードインストールansible 2.5
    #     root    git nss curl      
    [root@ansible ~]# yum install -y git nss curl
    #     deploy  ,       .py3-a2.5-env   
    [deploy@ansible ~]$ cd /home/deploy/.py3-a2.5-env/
    [deploy@ansible .py3-a2.5-env]$ git clone https://github.com/ansible/ansible.git

    4.python 3をロードする.6.5 virtualenv環境
    [deploy@ansible .py3-a2.5-env]$ source /home/deploy/.py3-a2.5-env/bin/activate
    (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$

    5.ansible依存パッケージのインストール
    #      
    (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ pip install paramiko PyYAML jinja2
    (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ ll
    total 8
    drwxrwxr-x. 14 deploy deploy 4096 Jan  7 13:31 ansible
    drwxrwxr-x.  2 deploy deploy 4096 Jan  7 11:52 bin
    drwxrwxr-x.  2 deploy deploy   24 Jan  7 11:52 include
    drwxrwxr-x.  3 deploy deploy   23 Jan  7 11:52 lib
    (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ pwd
    /home/deploy/.py3-a2.5-env

    6.python 3.6.5仮想環境でansible 2をロードする.5
    #   ansible    .py3-a2.5-env   
    #   ansible  
    (.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ cd ansible/
    (.py3-a2.5-env) [deploy@ansible ansible]$ pwd
    /home/deploy/.py3-a2.5-env/ansible
    (.py3-a2.5-env) [deploy@ansible ansible]$ git checkout stable-2.5  # ansible   2.5  
    Branch stable-2.5 set up to track remote branch stable-2.5 from origin.
    Switched to a new branch 'stable-2.5'
    (.py3-a2.5-env) [deploy@ansible ansible]$ source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q  #         ansible2.5  

    7.ansibleバージョンの検証
    (.py3-a2.5-env) [deploy@ansible ansible]$ ansible --version
    ansible 2.5.14 (stable-2.5 6548b7a558) last updated 2019/01/07 13:56:01 (GMT +800)
      config file = None
      configured module search path = ['/home/deploy/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
      ansible python module location = /home/deploy/.py3-a2.5-env/ansible/lib/ansible
      executable location = /home/deploy/.py3-a2.5-env/ansible/bin/ansible
      python version = 3.6.5 (default, Jan  7 2019, 11:40:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
    #   ansible2.5            

    Playbooksフレームワークとフォーマット
    親ディレクトリ
    レベル1サブディレクトリ
    レベル2サブディレクトリ
     
    inventory/
    Server詳細リストディレクトリ
    ホストドメイン名、IPアドレス、および関連パラメータの保存に使用
     
     
    testenv
    部品構成表と変数宣言ファイル
     
    roles/
    rolesタスクリスト
    1つ以上のroleを保存できます
     
     
    testbox/
    testbox詳細タスク
     
     
     
    tasks/
     
     
     
    main.yml
    testboxメインタスクファイル
    deploy.yml
    Playbookタスクエントリファイル
     
     
     
     
     
     
     
     
     
     
     
     
    フォーマットの説明
    testenvファイル
    説明
    [testservers]
    Serverグループのリスト
    test.example.com
    ターゲット配備サーバホスト名
    [testservers:vars]
    Serverグループリストのパラメータ
    server_name=test,example.com
    ターゲットホストKey/Valueパラメータ
    user=root
    output=/root/test.txt
     
     
     
     
     
     
     
     
     
    メインタスクファイルmain.yml
    ファイルの内容
    説明
    - name:Print Server name and user to remote testbox
    タスク名
        shell:"echo 'Currently{{user}} is logining {{server_name}}' > {{output}}"
    shell:shellモジュールを使用してコマンドを実行する
    inventory/testenvファイル[testservers:vars]server_name=test.example.com user=root output=/root/test.txt
     
     
     
     
     
     
     
     
     
    タスクエントリファイルyml
    - hosts:"testservers"      #Server  
      gather_facts:true         #  Server       
       remote_user:root        #            
       roles:
       - testbox                      #  roles/testbox    

    ansibleホストにログインし、ロード前に構成したpython 3.6.5とansible 2.5環境、および検証
    [root@ansible ~]# su - deploy
    Last login: Mon Jan  7 11:51:41 CST 2019 on pts/1
    [deploy@ansible ~]$ source .py3-a2.5-env/bin/activate
    (.py3-a2.5-env) [deploy@ansible ~]$ source .py3-a2.5-env/ansible/hacking/env-setup -q
    (.py3-a2.5-env) [deploy@ansible ~]$ ansible-playbook --version
    ansible-playbook 2.5.14 (stable-2.5 6548b7a558) last updated 2019/01/07 13:56:01 (GMT +800)
      config file = None
      configured module search path = ['/home/deploy/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
      ansible python module location = /home/deploy/.py3-a2.5-env/ansible/lib/ansible
      executable location = /home/deploy/.py3-a2.5-env/ansible/bin/ansible-playbook
      python version = 3.6.5 (default, Jan  7 2019, 11:40:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]

    プレイブックの作成を開始
    (.py3-a2.5-env) [deploy@ansible ~]$ mkdir test-playbooks
    (.py3-a2.5-env) [deploy@ansible ~]$ cd test-playbooks/
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir inventory
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ cd inventory
    (.py3-a2.5-env) [deploy@ansible inventory]$ vim testenv
    [testservers]
    test.example.com
    
    [testservers:vars]
    server_name=test.example.com
    user=root
    output=/root/test.txt
    (.py3-a2.5-env) [deploy@ansible inventory]$ cd ..
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls
    inventory  roles
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ cd roles/
    (.py3-a2.5-env) [deploy@ansible roles]$ mkdir testbox
    (.py3-a2.5-env) [deploy@ansible roles]$ cd testbox/
    (.py3-a2.5-env) [deploy@ansible testbox]$ mkdir tasks
    (.py3-a2.5-env) [deploy@ansible testbox]$ cd tasks/
    (.py3-a2.5-env) [deploy@ansible tasks]$ vim main.yml
    - name: Print server name and user to remote testbox
      shell:"echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}"
    (.py3-a2.5-env) [deploy@ansible tasks]$ cd ../../..
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd
    /home/deploy/test-playbooks
    (.py3-a2.5-env) [deploy@ansible tasks]$ cd ../../..
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd
    /home/deploy/test-playbooks
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim deploy.yml
    
    - hosts: "testservers"
      gather_facts: true
      remote_user: root

     
     
     
     
      roles:
        - testbox

    test_の表示playbooxsディレクトリ構造
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ tree .
    .
    ├── deploy.yml
    ├── inventory
    │?? └── testenv
    └── roles
        └── testbox
            └── tasks
                └── main.yml
    
    4 directories, 3 files

    ここには別のテストが必要です.example.com
    システムバージョン
    ホスト名
    IPアドレス
    CentOS  Linux release 7.5.1804 (core)
    test.example.com
    192.168.244.133
     
     
    配備されたマシンexample.comは他の3台のホストの実験環境と一致した.
    SSH秘密鍵免除認証の構成
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ su - root
    Password:
    Last login: Mon Jan  7 10:05:23 CST 2019 from 192.168.244.1 on pts/1
    [root@ansible ~]# vim /etc/hosts
    ....
    192.168.244.133 test.example.com
    [root@ansible ~]# exit
    logout
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh-keygen -t rsa
    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/deploy/.ssh/id_rsa):
    Created directory '/home/deploy/.ssh'.
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /home/deploy/.ssh/id_rsa.
    Your public key has been saved in /home/deploy/.ssh/id_rsa.pub.
    The key fingerprint is:
    SHA256:Aj+FzKSwqZS19eI/3EQt13L78+u3vjMtseX8YXNFnnY [email protected]
    The key's randomart image is:
    +---[RSA 2048]----+
    |  .. ..          |
    |  o+o=..  . .    |
    | oo.o.+..o + o  .|
    |..  .o... o o .o.|
    |.    .+ S.   . oE|
    |      ooo     + +|
    |       + .     %o|
    |        .     +o@|
    |              oB@|
    +----[SHA256]-----+
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh-copy-id -i /home/deploy/.ssh/id_rsa.pub [email protected]
    /bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/deploy/.ssh/id_rsa.pub"
    The authenticity of host 'test.example.com (192.168.244.133)' can't be established.
    ECDSA key fingerprint is SHA256:66hu+WU6R2SL4+7r/WYk2kjrGi7IwjuJieTrdMhwLc0.
    ECDSA key fingerprint is MD5:af:c7:bd:88:0d:40:d8:19:6d:28:7f:dd:af:aa:3a:c9.
    Are you sure you want to continue connecting (yes/no)? yes
    /bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
    /bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
    [email protected]'s password:
    
    Number of key(s) added: 1
    
    Now try logging into the machine, with:   "ssh '[email protected]'"
    and check to make sure that only the key(s) you wanted were added.
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
    Last login: Mon Jan  7 17:35:38 2019 from 192.168.244.1
    [root@test ~]# whoami
    root
    [root@test ~]# hostname
    test.example.com

    導入のテスト
    (.py3-a2.5-env) [deploy@ansible ~]$ cd test-playbooks/
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls
    deploy.yml  inventory  roles
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml
    
    PLAY [testservers] *************************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [test.example.com]
    
    TASK [testbox : Print server name and user to remote testbox] ******************
    changed: [test.example.com]
    
    PLAY RECAP *********************************************************************
    test.example.com           : ok=2    changed=1    unreachable=0    failed=0  
    #                     test.example.com     test.txt  ,             
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
    Last login: Mon Jan  7 17:42:57 2019 from 192.168.244.132
    [root@test ~]# ls
    anaconda-ks.cfg  test.txt
    [root@test ~]# cat test.txt
    Currently root is loggging test.example.com

    Ansible Playbooks共通モジュール
    Fileモジュール:
    ターゲットホストにファイルまたはディレクトリを作成し、次のようなシステム権限を付与します.
    - name: create a file   #     
      file: 'path=/root/a.txt state=touch mode=0755 owner=sishen group=sishen'
    #     

    Copyモジュール:
    Ansibleサービス側からターゲットホストへのファイル転送を実現する.
    - name: copy a file   #           
      copy: 'remote_src=no src=roles/testbox/files/test.sh dest=/root/test.sh mode=0644 force=yes'
    
    #   
    remote_src:   ansible              
    src:      
    dest:       
    mode:       
    force:    

    Statモジュール:
    次のようなリモート・ファイルのステータス情報を取得します.
    - name: check if test.sh exists
      stat: 'path=/root/test.sh'   #         
      register: script_stat           # stat           script_stat

    Debugモジュール:
    文をAnsibleに印刷して出力します.
    - debug: msf=test.sh exists
      when:script_stat.stat.exists

    Command/Shellモジュール
    Linuxターゲットホストコマンドラインの実行
    - name: run the script
      command: "sh /root/test.sh"
    
    - name: run the script
      shell: "echo 'test' > /root/test.txt" (  )

    Templateモジュール
    Ansibleサービス側からターゲットホストへのjinja 2テンプレート転送を実現
    - name: write the nginx config file
      template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf

    Packagingモジュール
    ターゲットホストシステムパッケージ管理ツール(yum,apt)を呼び出してインストール
    - name: ensure nginx is at the latest version
      yum: pkg=nginx state=latest  #(CentOS/RHEL)
    
    - name: ensure nginx is at the latest version
      apt: pkg=nginx state=latest    #(Debian/Ubuntu)

    サービスモジュール
    ターゲットホストシステムサービスの管理
    - name: start nginx service
      service: name=nginx state=started

    デプロイされたホストにログインし、テストユーザーを作成
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
    Last login: Mon Jan  7 17:44:56 2019 from 192.168.244.132
    [root@test ~]# useradd sishen
    useradd: user 'sishen' already exists
    [root@test ~]# useradd god
    [root@test ~]# useradd deploy
    [root@test ~]# mkdir /etc/nginx
    [root@test ~]# rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
    Retrieving http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
    warning: /var/tmp/rpm-tmp.i5SPeu: Header V4 RSA/SHA1 Signature, key ID 7bd9bf62: NOKEY
    Preparing...                                                            (100%################################# [100%]
    Updating / installing...
       1:nginx-release-centos-7-0.el7.ngx                                   ( 81%################################# [100%]

    デプロイされたホストの終了
    [root@test ~]# exit
    logout
    Connection to test.example.com closed.
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd
    /home/deploy/test-playbooks
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls
    deploy.yml  inventory  roles
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
    - name: Print server name and user to remote testbox
      shell: "echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}"
    #      
    - name: create a file
      file: 'path=/root/god.txt state=touch mode=0755 owner=god group=god'
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml
    
    PLAY [testservers] *************************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [test.example.com]
    
    TASK [testbox : Print server name and user to remote testbox] ******************
    changed: [test.example.com]
    
    TASK [testbox : create a file] *************************************************
    changed: [test.example.com]
    
    PLAY RECAP *********************************************************************
    test.example.com           : ok=3    changed=2    unreachable=0    failed=0  

    リモートホストにログインして表示
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
    Last login: Mon Jan  7 19:05:41 2019 from 192.168.244.132
    [root@test ~]# ls -l
    total 8
    -rw-------. 1 root root 1732 Dec 26 20:03 anaconda-ks.cfg
    -rwxr-xr-x. 1 god  god     0 Jan  7 19:05 god.txt  #             
    -rw-r--r--. 1 root root   44 Jan  7 19:05 test.txt

    あるいは直接
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] ls -l  /root/god.txt
    -rwxr-xr-x. 1 god god 0 Jan  7 19:05 /root/god.txt

    godを作成する.sh
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/files
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/files/god.sh
    echo "this is a test script"
    echo "If you see this message, the script is executed successfully."
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
    - name: Print server name and user to remote testbox
      shell: "echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}"
    - name: create a file
      file: 'path=/root/god.txt state=touch mode=0755 owner=god group=god'
    #      
    - name: copy a file
      copy: 'remote_src=no src=roles/testbox/files/god.sh dest=/root/god.sh mode=0644 force=yes'
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

    検証と表示
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] ls -l /root/god.sh
    -rw-r--r--. 1 root root 99 Jan  7 19:19 /root/god.sh

    プレゼンテーションstatとdebugモジュール
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
    ....
    #           
    - name: check if god.sh exists
      stat: 'path=/root/gid.sh'
      register: script_stat
    
    - debug: msg="god.sh exists"
      when: script_stat.stat.exists
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml
    
    PLAY [testservers] *************************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [test.example.com]
    
    TASK [testbox : Print server name and user to remote testbox] ******************
    changed: [test.example.com]
    
    TASK [testbox : create a file] *************************************************
    changed: [test.example.com]
    
    TASK [testbox : copy a file] ***************************************************
    ok: [test.example.com]
    
    TASK [testbox : check if god.sh exists] ****************************************
    ok: [test.example.com]
    
    TASK [testbox : debug] *********************************************************
    ok: [test.example.com] => {
        "msg": "god.sh exists"
    }
    
    PLAY RECAP *********************************************************************
    test.example.com           : ok=6    changed=2    unreachable=0    failed=0  
    
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$

    プレゼンテーションcommandモジュール
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
    #         
    - name: run the script
      command: 'sh /root/god.sh'
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml
    
    PLAY [testservers] *************************************************************
    
    TASK [Gathering Facts] *********************************************************
    ok: [test.example.com]
    
    TASK [testbox : Print server name and user to remote testbox] ******************
    changed: [test.example.com]
    
    TASK [testbox : create a file] *************************************************
    changed: [test.example.com]
    
    TASK [testbox : copy a file] ***************************************************
    ok: [test.example.com]
    
    TASK [testbox : check if god.sh exists] ****************************************
    ok: [test.example.com]
    
    TASK [testbox : debug] *********************************************************
    ok: [test.example.com] => {
        "msg": "god.sh exists"
    }
    
    TASK [testbox : run the script] ************************************************
    changed: [test.example.com]
    
    PLAY RECAP *********************************************************************
    test.example.com           : ok=7    changed=3    unreachable=0    failed=0  

    templateモジュールのデモ
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim inventory/testenv
    #         
    server_name=test.example.com
    port=80
    user=deploy
    worker_processes=4
    max_open_file=65505
    root=/www
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/templates (.py3
    -a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/templates/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 }}; #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; } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } } main.yml (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml # - name: write the nginx config file template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.c onf - name: ensure nginx is at the latest version yum: pkg=nginx state=latest - name: start nginx service service: name=nginx state=started (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] TASK [testbox : create a file] ************************************************* changed: [test.example.com] TASK [testbox : copy a file] *************************************************** ok: [test.example.com] TASK [testbox : check if god.sh exists] **************************************** ok: [test.example.com] TASK [testbox : debug] ********************************************************* ok: [test.example.com] => { "msg": "god.sh exists" } TASK [testbox : run the script] ************************************************ changed: [test.example.com] TASK [testbox : write the nginx config file] *********************************** changed: [test.example.com] TASK [testbox : ensure nginx is at the latest version] ************************* changed: [test.example.com] TASK [testbox : start nginx service] ******************************************* changed: [test.example.com] PLAY RECAP ********************************************************************* test.example.com : ok=10 changed=6 unreachable=0 failed=0 (.py3-a2.5-env) [deploy@ansible test-playbooks]$

    表示と検証
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] cat /etc/nginx/nginx.conf
    # For more information on configuration, see:
    user              deploy;
    worker_processes  4;
    
    error_log  /var/log/nginx/error.log;
    
    pid        /var/run/nginx.pid;
    
    events {
        worker_connections  65505;
    }
    
    
    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       80 default_server;
            server_name  test.example.com;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
    
            location / {
                root   /www;
                index  index.html index.htm;
            }
    
            error_page  404              /404.html;
            location = /404.html {
                root   /usr/share/nginx/html;
            }
    
            # redirect server error pages to the static page /50x.html
            #
            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                root   /usr/share/nginx/html;
            }
    
        }
    
    }
    (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] ps -ef | grep nginx
    root       5047      1  0 19:49 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
    deploy     5048   5047  0 19:49 ?        00:00:00 nginx: worker process
    deploy     5049   5047  0 19:49 ?        00:00:00 nginx: worker process
    deploy     5050   5047  0 19:49 ?        00:00:00 nginx: worker process
    deploy     5051   5047  0 19:49 ?        00:00:00 nginx: worker process

    これでansibleのインストール、構成、プレゼンテーションがすべて完了しました.
     
    posted on 2019-01-10 19:58 Lucky_7読書(...)コメント(…)コレクションの編集