68-ansible實驗總結


環境準備

默認所有虛擬機已關閉防火牆、關閉SELINUX、時間同步
虛擬機三臺:

主機版本 主/被 主機IP 主機名
CentOS 7 主控端 192.168.124.5 C7
CentOS 7 被控端 192.168.124.13 C7-3
CentOS 7 被控端 192.168.124.14 C7-4

實驗準備

#在主控端 主機C7上操作:
#安裝ansible
[root@C7 ~]# yum install ansible
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.neusoft.edu.cn
 * extras: mirrors.aliyun.com
 * updates: mirrors.neusoft.edu.cn
No package ansible available.
Error: Nothing to do

#很顯然,我們的光盤倉庫中缺失ansible相關依賴包
#搜索一下epel並添加epel源
[root@C7 ~]# yum list | grep epel-release
epel-release.noarch                         7-11                       extras   
[root@C7 ~]# yum install epel-release -y

#這次安裝成功
[root@C7 ~]# yum install ansible
……………
Total download size: 20 M
Installed size: 114 M
Is this ok [y/d/N]: y
…………
Installed:
  ansible.noarch 0:2.9.9-1.el7                                                                                                      

Dependency Installed:
  python-babel.noarch 0:0.9.6-8.el7           python-httplib2.noarch 0:0.9.2-1.el7      python-jinja2.noarch 0:2.7.2-4.el7        
  python-markupsafe.x86_64 0:0.11-10.el7      python-paramiko.noarch 0:2.1.1-9.el7      python2-jmespath.noarch 0:0.9.4-2.el7     
  sshpass.x86_64 0:1.06-2.el7                

Complete!


#在繼續實驗之前我們需要提前配置好遠程被控主機的免密鑰登錄
#全部直接回車直到結束
[root@C7-3 ~]# ssh-keygen -t rsa -C "ansible@linux"
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:KLIoqlICPAnj9JYIHr5opUN8gH4gnziRF56LlxFyweQ ansible@linux
The key's randomart image is:
+---[RSA 2048]----+
|o+*o             |
|OXoo             |
|%*E..            |
|+&o@   .         |
|=.& . . S        |
|oB.o .           |
|+oo              |
|+                |
|=                |
+----[SHA256]-----+
#這裏的 id_rsa 爲私鑰文件,id_rsa.pub 爲公鑰文件
#特別注意:.ssh目錄的權限需是700
[root@C7-3 ~]# ll /root/.ssh/
total 8
-rw------- 1 root root 1675 Jun  2 17:21 id_rsa
-rw-r--r-- 1 root root  395 Jun  2 17:21 id_rsa.pub

[root@C7 ~]# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
[root@C7 ~]# ll /root/.ssh/
total 16
-rw-r--r-- 1 root root  395 Jun  3 08:39 authorized_keys
-rw------- 1 root root 1675 Jun  2 17:15 id_rsa
-rw-r--r-- 1 root root  395 Jun  3 08:39 id_rsa.pub

#當前登錄遠程被控主機提示需要輸入密碼
[root@C7 ~]# ssh 192.168.124.13
[email protected]'s password: 


#將authorized_keys 文件發送到另外兩臺被控主機
#中間輸入yes;密碼輸入被控主機的root密鑰
[root@C7 ~]# scp /root/.ssh/authorized_keys 192.168.124.13:/root/.ssh/
The authenticity of host '192.168.124.13 (192.168.124.13)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes     #輸入yes
Warning: Permanently added '192.168.124.13' (ECDSA) to the list of known hosts.
[email protected]'s password:       #輸入被控主機的root密鑰
authorized_keys                                                                                        100%  395   121.4KB/s   00:00    

[root@C7 ~]# scp /root/.ssh/authorized_keys 192.168.124.14:/root/.ssh/
The authenticity of host '192.168.124.14 (192.168.124.14)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes     #輸入yes
Warning: Permanently added '192.168.124.14' (ECDSA) to the list of known hosts.
[email protected]'s password:        #輸入被控主機的root密鑰
authorized_keys                                                                                        100%  395   212.5KB/s   00:00    


#現在我們來嘗試以下是否可以在主控端遠程免密鑰登錄兩臺被控主機
[root@C7 ~]# ssh 192.168.124.13
Last login: Tue Jun  2 17:19:57 2020 from 192.168.124.5
[root@C7-3 ~]# exit
logout
Connection to 192.168.124.13 closed.

[root@C7 ~]# ssh 192.168.124.14
Last login: Tue Jun  2 16:14:35 2020 from 192.168.124.1
[root@C7-4 ~]# exit
logout
Connection to 192.168.124.14 closed.
#如果你覺得輸入主機IP 進行遠程連接過於麻煩,你可以在主控端的 /etc/hosts 文件中配置IP解析
[root@C7 ~]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
#追加以下兩行就行了
192.168.124.13 C7-3
192.168.124.14 C7-4

[root@C7 ~]# ssh C7-3
The authenticity of host 'c7-3 (192.168.124.13)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'c7-3' (ECDSA) to the list of known hosts.
Last login: Tue Jun  2 17:32:53 2020 from 192.168.124.5
[root@C7-3 ~]# exit
logout
Connection to c7-3 closed.

[root@C7 ~]# ssh C7-4
The authenticity of host 'c7-4 (192.168.124.14)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'c7-4' (ECDSA) to the list of known hosts.
Last login: Tue Jun  2 17:33:05 2020 from 192.168.124.5
[root@C7-4 ~]# exit
logout
Connection to c7-4 closed.


#覺得手動操作有些不夠逼格呢?這裏提供參考腳本
#利用 sshpass 批量實現基於 key 驗證
#!/bin/bash
ssh-keygen -f /root/.ssh/id_rsa  -P ''
NET=192.168.124
export SSHPASS=linux
for IP in {10..20}; do
    sshpass -e ssh-copy-id  ${NET}.${IP}
done

建議從此刻狀態對所有主機創建虛擬機快照


實驗開始

#終於可以配置ansible了,前期工作基本就是這些
#ansible有三個重要的文件,在yum安裝下文件默認在:/etc/ansible/ 下
[root@C7 ~]# ls /etc/ansible/
ansible.cfg  hosts  roles

#ansible.cfg 毫無疑問這是ansible的主配置文件
#hosts 遠程控制主機清單
#roles 存放角色的目錄

#配置hosts文件
[root@C7 ~]# vim /etc/ansible/hosts 
#隨便找個位置寫即可

[srvs]    # []中的英文儘量寫的好記一點,因爲後面的終端中要輸入
192.168.124.13    #被控主機IP
192.168.124.14    #被控主機IP

#查看被ansible管理的所有主機列表
[root@C7 ~]# ansible srvs --list
  hosts (2):
    192.168.124.13
    192.168.124.14

#測試一下被管理的主機能否ping通
[root@C7 ~]# ansible all -m ping
192.168.124.14 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.124.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

#你是否想過:倘若這裏管理的主機多達100臺,是否我就必須寫100行主機IP呢?
#當然不必如此,對於被管理主機非常多的情況下,我們有另一種寫法
[root@C7 ~]# vim /etc/ansible/hosts 
#將前面兩臺主機IP註釋掉,添加新行

[srvs]
#192.168.124.13    #被控主機IP
#192.168.124.14    #被控主機IP
192.168.124.[10:20]    #表示10到20的主機IP

#重新查看被ansible管理的所有主機列表
[root@C7 ~]# ansible srvs --list
  hosts (11):
    192.168.124.10
    192.168.124.11
…………..#省略不寫
    192.168.124.19
    192.168.124.20

#當然,我這裏僅部署了兩臺被控主機,若此時測試所有主機能否ping通,其餘18臺主機是不通的
#不僅這些主機ping不通,其ping的過程也並不是按照主機IP順序進行的
[root@C7 ~]# ansible all -m ping
192.168.124.10 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.124.10 port 22: Connection refused", 
    "unreachable": true
}
192.168.124.14 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.124.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.124.11 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.124.11 port 22: No route to host", 
    "unreachable": true
}

#爲了試驗正常進行,還是把hosts主機清單改回來吧

#ansible中擁有非常多的模塊,通過這些模塊能夠幫助我們完成及減少工作當中一些繁瑣重複的內容
#例舉ansible常用模塊:篇幅有限這裏僅做例舉而不進行詳細說明
#若你對此很感興趣的話,這裏提供詳細博客鏈接:點擊跳轉
Command 模塊;Shell 模塊;Script 模塊;Copy 模塊;Fetch 模塊;File 模;
unarchive 模塊;Archive 模塊;Hostname 模塊;Cron 模塊;Yum 模塊;
Service 模塊;User 模塊;Group 模塊;Setup 模塊;
#倘若你對這些如此多的模塊感到非常迷茫,那麼使用ansible-doc是個辦法
#其作用是ansible-doc +指定模塊 查看該模塊的幫助信息

#例如yum模塊
[root@C7 ~]# ansible-doc yum
> YUM    (/usr/lib/python2.7/site-packages/ansible/modules/packaging/os/yum.py)

        Installs, upgrade, downgrades, removes, and lists packages and groups with the `yum‘ package
        manager. This module only works on Python 2. If you require Python 3 support see the [dnf]
        module.

  * This module is maintained by The Ansible Core Team
  * note: This module has a corresponding action plugin.
………

#若後面跟 --list 或 -l 則可以查看所有支持的ansible模塊
[root@C7 ~]# ansible-doc --list
fortios_router_community_list                                 Configure community lists in Fortinet's FortiOS and FortiGate    
azure_rm_devtestlab_info                                      Get Azure DevTest Lab facts  
……….

劇本

#ansible中有一個非常重要的組成部分,那就是Playbook(劇本)
#通過劇本我們可以實現一次同時部署多臺主機
#playbook由YAML語法構成,文件首行固定爲 ---,且對縮進有嚴格要求,敏感大小寫
#一個完整的代碼塊最少包括name和task,且一個name只能包含一個task
#YAML文件擴展名通常爲yml或yaml

#嘗試編寫一個簡單的劇本
[root@C7 ~]# mkdir /etc/ansible/roles/playbook
[root@C7 ~]# vim !$/hi.yml
---
- hosts: srvs
  tasks:
    - name: test
      shell: /bin/echo "Hi,I'm `who am i`" > /data/hi.txt

#編輯結束應進行運行測試,是否有語法錯誤
#俗稱幹跑,而不進行實際操作
[root@C7 ~]# ansible-playbook --check -C /etc/ansible/roles/playbook/hi.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [test] ************************************************************************************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

#現在進行真正執行操作
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/hi.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [test] ************************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
#執行完,我們是否可以在本機查看遠程被控主機的文件內容呢?
[root@C7 ~]# ansible all -a "cat /data/hi.txt"
192.168.124.14 | CHANGED | rc=0 >>
Hi,I'm root     pts/3        2020-06-03 09:23 (192.168.124.5)
192.168.124.13 | CHANGED | rc=0 >>
Hi,I'm root     pts/3        2020-06-03 09:23 (192.168.124.5)

#很明顯可以直接看到內容,那麼如果我只想在某一臺主機上執行剛纔的yml文件呢?
#略微修改一下之前的yml文件內容以作區分
[root@C7 ~]# vim /etc/ansible/roles/playbook/hi.yml
---
- hosts: srvs
  tasks:
    - name: test
      shell: /bin/echo "You can see !" > /data/see.txt


#這次我就不幹跑測試了,直接運行
#這次我們只對C7-3主機執行操作
[root@C7 ~]# ansible-playbook --limit 192.168.124.13 /etc/ansible/roles/playbook/hi.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]

TASK [test] ************************************************************************************************************************
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看執行後,遠程主機C7-3上的文件內容
#注意,命令參數有順序要求
[root@C7 ~]# ansible -a 192.168.124.13 "cat /data/see.txt"
[WARNING]: Could not match supplied host pattern, ignoring: cat
[WARNING]: Could not match supplied host pattern, ignoring: /data/see.txt
[WARNING]: No hosts matched, nothing to do

[root@C7 ~]# ansible 192.168.124.13 -a "cat /data/see.txt"
192.168.124.13 | CHANGED | rc=0 >>
You can see !

#很顯然我只是把 -a參數寫在了前面,但這樣會導致命令執行失敗

部署httpd

#讓我們更近一步,嘗試使用ansible-playbook 來完成遠程主機的httpd服務的部署
#在部署遠程主機httpd服務之前,首先我們要在主控端安裝httpd

[root@C7 ~]# yum -y install httpd
[root@C7 ~]# cp /etc/httpd/conf/httpd.conf /etc/ansible/roles/playbook/

[root@C7 ~]# vim /etc/ansible/roles/playbook/index.html
If you can see,that‘s good!


#編寫httpd_install.yml  playbook腳本
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes

#在C7-3主機上進行幹跑測試
[root@C7 ~]# ansible-playbook --check --limit 192.168.124.13 -C /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
ok: [192.168.124.13]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   



#顯示無報錯,在C7-3被控主機真正運行操作
[root@C7 ~]# ansible-playbook --limit 192.168.124.13 /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
ok: [192.168.124.13]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#訪問C7-3 httpd頁面
[root@C7 ~]# curl 192.168.124.13:80
If you can see,that's good!

#查看C7-3 httpd監聽端口
[root@C7 ~]# ansible 192.168.124.13 -a "ss -ntul"
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:80                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  

#查看所有主機 httpd監聽端口使用 ansible all -a "ss -ntul"
#編寫notify 和handlers 實現修改配置文件後觸發httpd 服務重啓
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify: restart httpd service        #新行
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes
  handlers:                                #新行
    - name: restart httpd service          #新行
      service: name=httpd state=restarted  #新行

#順便把httpd 服務端口改了
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd.conf
#Listen 80
Listen 88

#任何時候都不要忘記測試
[root@C7 ~]# ansible-playbook --check -C /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.14]
ok: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
changed: [192.168.124.14]
ok: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ********************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#測試無誤後,在所有被控主機上執行操作
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ********************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.14]
ok: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
ok: [192.168.124.13]
changed: [192.168.124.14]

RUNNING HANDLER [restart httpd service] ********************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#訪問兩臺被控主機httpd 頁面
[root@C7 ~]# curl C7-3:88
If you can see,that's good!
[root@C7 ~]# curl C7-4:88
If you can see,that's good!

#除了可以這樣執行之外,我們還可以利用ansible-playbook僅執行指定的tags任務
#給指定的tasks打標籤,以供調用
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml 
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify: restart httpd service        
      tags: config                         #新行
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes
  handlers:                                
    - name: restart httpd service          
      service: name=httpd state=restarted  

#修改httpd 端口
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd.conf
#Listen 80
Listen 8888

#列出playbook中所有的tags
[root@C7 ~]# ansible-playbook --list-tags /etc/ansible/roles/playbook/httpd_install.yml 

playbook: /etc/ansible/roles/playbook/httpd_install.yml

  play #1 (srvs): srvs	TAGS: []
      TASK TAGS: [config]

#用ansible-playbook 僅執行指定的tags 任務
[root@C7 ~]# ansible-playbook -t config /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ********************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#查看遠程被控主機httpd 監聽端口
[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      128    [::]:8888               [::]:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      128       *:8888                  *:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  

#訪問
[root@C7 ~]# curl C7-3:8888
If you can see,that's good!
[root@C7 ~]# curl C7-4:8888
If you can see,that's good!

變量使用

#接下來,讓我們初步瞭解ansible-playbook的變量如何使用
#變量僅由字母、數字和下劃線組成,且只能以數字開頭
#變量可在/etc/ansible/hosts 中定義,或者在獨立的變量YAML文件中定義
#變量調用方式:通過 {{ variable_name }} 調用變量,且變量名前後必須有空格
#有時用 "{{ variable_name }}" 纔會生效

#實際應用一下,編寫一個簡單的yml文件測試
[root@C7 ~]# vim /etc/ansible/roles/playbook/vartest.yml
---
- hosts: srvs
  tasks:
    - name: playbook var test
      shell: /bin/echo "laowang is pig {{ ansible_distribution_major_version }}" > /data/vartest.txt

#日常測試幹跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [playbook var test] ***********************************************************************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   


#測試無誤,進行執行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [playbook var test] ***********************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#查看遠程被控主機文件內容
[root@C7 ~]# ansible all -a "cat /data/vartest.txt"
192.168.124.14 | CHANGED | rc=0 >>
laowang is pig 7
192.168.124.13 | CHANGED | rc=0 >>
laowang is pig 7

#除了使用setup 模塊提供的遠程主機變量還可以在ansible 的hosts 文件中自定義變量
[root@C7 ~]# vim /etc/ansible/hosts 
[srvs]    # []中的英文儘量寫的好記一點
192.168.124.13    name=zhangsan course=linux #被控主機IP
192.168.124.14    name=lisi course=centos #被控主機IP

#修改之前的yml文件
[root@C7 ~]# vim /etc/ansible/roles/playbook/vartest.yml
---
- hosts: srvs
  tasks:
    - name: playbook var test
      shell: /bin/echo "Hi,my name is {{ name }},and I like study {{ course }}." > /data/vartest.txt

#日常測試幹跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [playbook var test] ***********************************************************************************************************
skipping: [192.168.124.14]
skipping: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

#運行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [playbook var test] ***********************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看
[root@C7 ~]# ansible all -a "cat /data/vartest.txt"
192.168.124.14 | CHANGED | rc=0 >>
Hi,my name is lisi,and I like study centos.
192.168.124.13 | CHANGED | rc=0 >>
Hi,my name is zhangsan,and I like study linux.


#嘗試在playbook文件中直接定義變量使用
[root@C7 ~]# vim /etc/ansible/roles/playbook/useradd.yml 
---
- hosts: srvs
  vars:
    - username: zhangsan
    - usergroup: studylinux
  tasks:
    - name: create group
      group: name={{ usergroup }} state=present
    - name: create user
      user: name={{ username }} group={{ usergroup }} state=present

#測試幹跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#運行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看遠程被控主機中 zhangsan 的用戶信息
[root@C7 ~]# ansible all -a "id zhangsan"
192.168.124.14 | CHANGED | rc=0 >>
uid=1001(zhangsan) gid=1001(studylinux) groups=1001(studylinux)
192.168.124.13 | CHANGED | rc=0 >>
uid=1001(zhangsan) gid=1001(studylinux) groups=1001(studylinux)

#當我們不斷的定義變量,隨着時間累積其數量將會變得愈來愈多,編輯和管理也隨着變得繁瑣
#因此,我們可以單獨創建定義變量的yml文件,再在playbook中引用即可
[root@C7 ~]# vim /etc/ansible/roles/playbook/vars.yml
usergroup: teachers
username: lisi

[root@C7 ~]# vim /etc/ansible/roles/playbook/useradd.yml 
---
- hosts: srvs
  vars_files:    #新行
    - vars.yml   #新行
#  vars:
#    - username: zhangsan
#    - usergroup: studylinux
  tasks:
    - name: create group
      group: name={{ usergroup }} state=present
    - name: create user
      user: name={{ username }} group={{ usergroup }} state=present


#測試幹跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#運行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


查看遠程被控主機中 lisi 的用戶信息
[root@C7 ~]# ansible all -a "id lisi"
192.168.124.13 | CHANGED | rc=0 >>
uid=1002(lisi) gid=1002(teachers) groups=1002(teachers)
192.168.124.14 | CHANGED | rc=0 >>
uid=1002(lisi) gid=1002(teachers) groups=1002(teachers)

條件判斷

#除此之外,我們還可以在ansible-playbook中使用條件判斷when
#爲了展示實驗效果,我們臨時添加一臺虛擬機

主機版本 主/被 主機IP 主機名
CentOS 6 被控端 192.168.124.20 C6
#將免密驗證執行完成
[root@C7 ~]# scp /root/.ssh/authorized_keys 192.168.124.20:/root/.ssh/
[email protected]‘s password: 
authorized_keys                                           100%  395   229.9KB/s   00:00    
[root@C7 ~]# ssh 192.168.124.20
Last login: Mon Mar 30 08:49:10 2020 from 192.168.124.1
[root@C6 ~]# exit
logout
Connection to 192.168.124.20 closed.

#添加hosts被控主機清單
[root@C7 ~]# vim /etc/ansible/hosts
[srvs]
192.168.124.13    
192.168.124.14    
192.168.124.20    #新行

#查看一下,確實已被添加進去
[root@C7 ~]# ansible all --list
  hosts (3):
    192.168.124.13
    192.168.124.14
    192.168.124.20

#編寫yml文件
[root@C7 ~]# vim /etc/ansible/roles/playbook/dbserver.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: Install DBserver software in CentOS6
      yum: name=mysql-server
      when: ansible_distribution_major_version=="6"
    - name: Install DBserver software in CentOS7
      yum: name=mariadb-server
      when: ansible_distribution_major_version=="7"

#測試
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/dbserver.yml 

PLAY [srvs] ********************************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [192.168.124.20]
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [Install DBserver software in CentOS6] ************************************************
skipping: [192.168.124.14]
skipping: [192.168.124.13]
changed: [192.168.124.20]

TASK [Install DBserver software in CentOS7] ************************************************
skipping: [192.168.124.20]
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *********************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.20             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   


[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/dbserver.yml 

PLAY [srvs] ********************************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [192.168.124.20]
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [Install DBserver software in CentOS6] ************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]
fatal: [192.168.124.20]: FAILED! => {"changed": false, "changes": {"installed": ["mysql-server"]}, 
……………………..#報錯
\nInstall       4 Package(s)\n\nTotal download size: 10 M\nInstalled size: 29 M\nDownloading Packages:\n"]}

TASK [Install DBserver software in CentOS7] ************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *********************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.20             : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   
#CentOS6主機出現報錯,經過我檢查排錯確認是由於該主機網關不通導致無法進行軟件包安裝
#解決方法:在CentOS6主機上添加網管並ping測試
[root@C6 ~]# vim /etc/resolv.conf 
#添加一條或多條
nameserver 192.168.124.10    #此IP是我個人虛擬機的網關
nameserver 114.114.114.114    #通用網關

[root@C6 ~]# ping www.baidu.com
PING www.a.shifen.com (61.135.169.125) 56(84) bytes of data.
64 bytes from 61.135.169.125: icmp_seq=1 ttl=128 time=7.43 ms
64 bytes from 61.135.169.125: icmp_seq=2 ttl=128 time=6.12 ms
^C
--- www.a.shifen.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2715ms
rtt min/avg/max/mdev = 6.129/7.320/8.395/0.934 ms


#在主控端重新執行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/dbserver.yml 

PLAY [srvs] ********************************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [192.168.124.20]
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [Install DBserver software in CentOS6] ************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]
changed: [192.168.124.20]

TASK [Install DBserver software in CentOS7] ************************************************
skipping: [192.168.124.20]
ok: [192.168.124.13]
ok: [192.168.124.14]

PLAY RECAP *********************************************************************************
192.168.124.13             : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.20             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   


#查看遠程被控主機安裝包信息,忽略WARNING警告信息
[root@C7 ~]# ansible all -a "rpm -q mariadb"
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'.  If you
need to use command because yum, dnf or zypper is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.
192.168.124.14 | CHANGED | rc=0 >>
mariadb-5.5.65-1.el7.x86_64
192.168.124.13 | CHANGED | rc=0 >>
mariadb-5.5.65-1.el7.x86_64
192.168.124.20 | FAILED | rc=1 >>
package mariadb is not installednon-zero return code

[root@C7 ~]# ansible all -a "rpm -q mysql"
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'.  If you
need to use command because yum, dnf or zypper is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.
192.168.124.20 | CHANGED | rc=0 >>
mysql-5.1.73-8.el6_8.x86_64
192.168.124.13 | FAILED | rc=1 >>
package mysql is not installednon-zero return code
192.168.124.14 | FAILED | rc=1 >>
package mysql is not installednon-zero return code

#CentOS6的使命暫時結束,從hosts文件中移除
[root@C7 ~]# vim /etc/ansible/hosts
[srvs] 
192.168.124.13
192.168.124.14 
#192.168.124.20    #註釋
#ansible-playbook 使用循環 with_items
#使用循環結構多次執行同一個task任務


[root@C7 ~]# vim /etc/ansible/roles/playbook/addusers.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: add more group
      group: name={{ item }} state=present
      with_items:
      - group1
      - group2
      - group3
    - name: add more user
      user: name={{ item.username }} group={{ item.usergroup }} state=present
      with_items:
        - { username: 'user1', usergroup: 'group1' }
        - { username: 'user2', usergroup: 'group2' }
        - { username: 'user3', usergroup: 'group3' }


#測試
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/addusers.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [add more group] *********************************************************************************************
changed: [192.168.124.14] => (item=group1)
changed: [192.168.124.13] => (item=group1)
changed: [192.168.124.14] => (item=group2)
changed: [192.168.124.13] => (item=group2)
changed: [192.168.124.14] => (item=group3)
changed: [192.168.124.13] => (item=group3)

TASK [add more user] **********************************************************************************************
changed: [192.168.124.14] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.13] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.14] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.13] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.14] => (item={u'username': u'user3', u'usergroup': u'group3'})
changed: [192.168.124.13] => (item={u'username': u'user3', u'usergroup': u'group3'})

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#運行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/addusers.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [add more group] *********************************************************************************************
changed: [192.168.124.14] => (item=group1)
changed: [192.168.124.13] => (item=group1)
changed: [192.168.124.14] => (item=group2)
changed: [192.168.124.13] => (item=group2)
changed: [192.168.124.14] => (item=group3)
changed: [192.168.124.13] => (item=group3)

TASK [add more user] **********************************************************************************************
changed: [192.168.124.14] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.13] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.14] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.13] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.14] => (item={u'username': u'user3', u'usergroup': u'group3'})
changed: [192.168.124.13] => (item={u'username': u'user3', u'usergroup': u'group3'})

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看用戶信息
[root@C7 ~]# ansible all -m shell -a "cat /etc/passwd|grep user"
192.168.124.14 | CHANGED | rc=0 >>
user1:x:1003:1003::/home/user1:/bin/bash
user2:x:1004:1004::/home/user2:/bin/bash
user3:x:1005:1005::/home/user3:/bin/bash
192.168.124.13 | CHANGED | rc=0 >>
user1:x:1003:1003::/home/user1:/bin/bash
user2:x:1004:1004::/home/user2:/bin/bash
user3:x:1005:1005::/home/user3:/bin/bash

#ansible-playbook 使用模板
#templates 可以使用ansible-playbook 中定義的變量用以生成指定的文件
#下面我以httpd_install.yml 文件進行演示
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml 
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
#      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf  #新行
      notify: restart httpd service
      tags: config
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes
  handlers:
    - name: restart httpd service
      service: name=httpd state=restarted

[root@C7 ~]# mkdir /etc/ansible/roles/playbook/templates
[root@C7 ~]# cp /etc/ansible/roles/playbook/httpd.conf /etc/ansible/roles/playbook/templates/httpd.conf.j2

[root@C7 ~]# vim !$
#Listen 8888
Listen {{httpd_port}}

#也許有人看不明白 vim !$ 是什麼意思,!$表示的是調用上一次執行的命令行中最後一個參數
#對於這裏而言,執行 vim !$ 等同於 vim /etc/ansible/roles/playbook/templates/httpd.conf.j2
#掌握技巧能夠使我們工作效率大大增加
[root@C7 ~]# ansible-playbook -e httpd_port=10086 /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看端口
[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:10086              [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:10086              [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


[root@C7 ~]# ansible all -m shell -a "cat /etc/httpd/conf/httpd.conf|grep ^Listen"
192.168.124.14 | CHANGED | rc=0 >>
Listen 10086
192.168.124.13 | CHANGED | rc=0 >>
Listen 10086

#變量除了可以直接引用之外,還可以進行變量運算
[root@C7 ~]# vim /etc/ansible/hosts 
[srvs] 
192.168.124.13 httpd_port=110 
192.168.124.14 httpd_port=150 

[root@C7 ~]# vim /etc/ansible/roles/playbook/templates/httpd.conf.j2
#Listen {{httpd_port}}
Listen {{httpd_port*2}}


[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:300                [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:220                [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


[root@C7 ~]# ansible all -m shell -a "cat /etc/httpd/conf/httpd.conf|grep ^Listen"
192.168.124.14 | CHANGED | rc=0 >>
Listen 300
192.168.124.13 | CHANGED | rc=0 >>
Listen 220


#模板中還可以使用循環結構動態生成內容
[root@C7 ~]# vim /etc/ansible/hosts 
[srvs] 
192.168.124.13
192.168.124.14

[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml
---
- hosts: srvs
  remote_user: root
  vars:
    httpd_vhosts:
      - web01:
        listen: 8001
        documentroot: '/data/web01'

      - web02:
        listen: 8002
        documentroot: '/data/web02'

  tasks:
    - name: install httpd
      yum: name=httpd

    - name: config httpd service
#      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      template: src=vhostport.conf.j2 dest=/etc/httpd/conf.d/vhostport.conf
      notify: restart httpd service
      tags: config

    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html

    - name: manage httpd service
      service: name=httpd state=started enabled=yes

  handlers:
    - name: restart httpd service
      service: name=httpd state=restarted

[root@C7 ~]# vim /etc/ansible/roles/playbook/vhostport.conf.j2
{% for vhost in httpd_vhosts %}
listen {{vhost.listen}}
{% endfor %}

{% for vhost in httpd_vhosts %}
<virtualhost *.{{vhost.listen}}>
        documentroot {{vhost.documentroot}}
        <directory {vhost.documentroot}>
                require all granted
        </directory>
</virtualhost>
{% endfor %}

#測試幹跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#運行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:8001               [::]:*                  
tcp    LISTEN     0      128    [::]:8002               [::]:*                  
tcp    LISTEN     0      128    [::]:300                [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:220                [::]:*                  
tcp    LISTEN     0      128    [::]:8001               [::]:*                  
tcp    LISTEN     0      128    [::]:8002               [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


[root@C7 ~]# curl C7-3:8001
If you can see,that's good!
[root@C7 ~]# curl C7-3:8002
If you can see,that's good!
[root@C7 ~]# curl C7-4:8002
If you can see,that's good!
[root@C7 ~]# curl C7-4:8001
If you can see,that's good!

模塊化安裝httpd

#讓我們稍微升級一下,以模塊化的方式安裝httpd服務
#將所有主機還原到剛剛配置完成免密鑰登錄遠程被控主機的狀態,並且只保留C7 與C7-3 兩臺虛擬機
#使用時間管理技能:時光回溯……….完成

#配置遠程被控主機清單
[root@C7 ~]# vim /etc/ansible/hosts
[srvs]
192.168.124.13

#測試能否ping通
[root@C7 ~]# ansible all -m ping
192.168.124.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}


[root@C7 ~]# mkdir -p /etc/ansible/roles/playbook/httpd/{tasks,handlers,files,templates,vars}
[root@C7 ~]# tree /etc/ansible/ -d
/etc/ansible/
└── roles
    └── playbook
        └── httpd
            ├── files
            ├── handlers
            ├── tasks
            ├── templates
            └── vars

[root@C7 ~]# cd /etc/ansible/roles/playbook/httpd/tasks/
[root@C7 tasks]# vim main.yml
- include: install.yml
- include: config.yml
- include: index.yml
- include: service.yml


[root@C7 tasks]# vim install.yml
- name: Install httpd package
  yum: name=httpd


[root@C7 tasks]# vim index.yml
- name: index.html
  copy: src=index.html dest=/var/www/html/


[root@C7 tasks]# vim config.yml
- name: config file
  copy: src=httpd.conf dest=/etc/httpd/conf/ backup=yes
  notify: restart


[root@C7 tasks]# vim service.yml
- name: start service
  service: name=httpd state=started enabled=yes


[root@C7 tasks]# vim /etc/ansible/roles/playbook/httpd/handlers/main.yml
- name: restart
  service: name=httpd state=restarted

[root@C7 tasks]# yum install httpd -y

[root@C7 tasks]# cp /etc/httpd/conf/httpd.conf /etc/ansible/roles/playbook/httpd/files/
[root@C7 tasks]# vim /etc/ansible/roles/playbook/httpd/files/index.html
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>HTML語言</title>
</head>
<body>
<a href=https://blog.csdn.net/dushansao>
<img src="https://profile.csdnimg.cn/7/0/B/1_dushansao" /img></a>
<a href=https://blog.csdn.net/dushansao>
<h1 style="color:red">歡迎來到我的博客</h1></a>
<p><a href=https://blog.csdn.net/dushansao>點我,讓你好看!</a> 不點必將後悔!</p>
</body>
</html>

[root@C7 tasks]# vim /etc/ansible/roles/playbook/role_httpd.yml
---
- hosts: srvs
  remote_user: root
  roles:
    - role: /etc/ansible/roles/playbook/httpd


[root@C7 tasks]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── hosts
└── roles
    └── playbook
        ├── httpd
        │   ├── files
        │   │   ├── httpd.conf
        │   │   └── index.html
        │   ├── handlers
        │   │   └── main.yml
        │   ├── tasks
        │   │   ├── config.yml
        │   │   ├── index.yml
        │   │   ├── install.yml
        │   │   ├── main.yml
        │   │   └── service.yml
        │   ├── templates
        │   └── vars
        └── role_httpd.yml


#測試
[root@C7 tasks]# ansible-playbook -C /etc/ansible/roles/playbook/role_httpd.yml

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : Install httpd package] **************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : config file] ************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : index.html] *************************************************************
changed: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : start service] **********************************************************
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#運行
[root@C7 tasks]# ansible-playbook /etc/ansible/roles/playbook/role_httpd.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : Install httpd package] **************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : config file] ************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : index.html] *************************************************************
changed: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : start service] **********************************************************
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#查看遠程被控主機端口
[root@C7 tasks]# ansible all -a "ss -ntul"
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:80                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


#網頁打開

在這裏插入圖片描述

點擊跳至文章末尾

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章