簡單使用ansible-playbook

筆記內容:簡單使用ansible-playbook
筆記日期:2018-01-30

  • 24.21 ansible安裝包和管理服務
  • 24.22 使用ansible playbook
  • 24.23 playbook裏的變量
  • 24.24 playbook裏的循環
  • 24.25 playbook裏的條件判斷
  • 24.26 playbook中的handlers

24.21 ansible安裝包和管理服務

1.使用以下命令給客戶端安裝httpd服務:

[root@server ~]# ansible testhost -m yum -a "name=httpd"
192.168.77.128 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirrors.cn99.com\n * epel: mirrors.tongji.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.163.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos.6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package      Arch          Version                        Repository      Size\n================================================================================\nInstalling:\n httpd        x86_64        2.4.6-67.el7.centos.6          updates        2.7 M\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-2.4.6-67.el7.centos.6.x86_64                           1/1 \n  Verifying  : httpd-2.4.6-67.el7.centos.6.x86_64                           1/1 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-67.el7.centos.6                                          \n\nComplete!\n"
    ]
}

2.執行以下命令啓動httpd服務:

[root@server ~]# ansible testhost -m service -a "name=httpd state=started enabled=yes"
        ## 然後會輸出一堆狀態信息,只要第一句爲SUCCESS則代表啓動成功

注:這裏的name是centos系統裏的服務名,可以通過chkconfig --list查看到。

其他控制服務的命令:

# 停止服務
[root@server ~]# ansible testhost -m service -a "name=httpd state=stopped"
# 重新啓動服務
[root@server ~]# ansible testhost -m service -a "name=httpd state=restarted"
# 重載服務
[root@server ~]# ansible testhost -m service -a "name=httpd state=reloaded"

3.在name後面還可以加上state=installed或removed,加上removed的話,表示卸載這個服務,如果不指定state的值默認是installed:

[root@server ~]# ansible testhost -m yum -a "name=httpd state=removed"
192.168.77.128 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos.6 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package      Arch          Version                       Repository       Size\n================================================================================\nRemoving:\n httpd        x86_64        2.4.6-67.el7.centos.6         @updates        9.4 M\n\nTransaction Summary\n================================================================================\nRemove  1 Package\n\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Erasing    : httpd-2.4.6-67.el7.centos.6.x86_64                           1/1 \n  Verifying  : httpd-2.4.6-67.el7.centos.6.x86_64                           1/1 \n\nRemoved:\n  httpd.x86_64 0:2.4.6-67.el7.centos.6                                          \n\nComplete!\n"
    ]
}
[root@server ~]# 

然後到客戶端上通過rpm -qa httpd命令查看是否已卸載成功:

[root@client ~]# rpm -qa httpd
[root@client ~]# 

Ansible文檔的使用:

1.列出所有可用的模塊命令:

ansible-doc -l

2.查看指定模塊的文檔,例如我要查看cron模塊的文檔,可使用以下命令:

ansible-doc cron

ansible-doc後面跟模塊名就可以查看該模塊的文檔。


24.22 使用ansible playbook

playbook相當於可以把模塊命令都寫入到配置文件裏面,這樣就可以直接執行配置文件了,有點腳本的意思:

[root@server ~]# vim /etc/ansible/test.yml
---
- hosts: testhost
  remote_user: root
  tasks:
    - name: test_playbook
      shell: touch /tmp/test.txt

文件格式說明:

  • 第一行需要有三個槓,hosts參數指定了對哪些主機進行參作,如果是多臺機器可以用逗號作爲分隔,也可以使用主機組,在/etc/ansible/hosts裏定義;
  • user參數指定了使用什麼用戶登錄遠程主機操作;
  • tasks指定了一個任務,其下面的name參數同樣是對任務的描述,在執行過程中會打印出來,shell是ansible模塊名字

編輯完成之後,使用ansible-playbook命令執行該文件:

[root@server ~]# ansible-playbook /etc/ansible/test.yml

PLAY [testhost] ***********************************************************************************************************

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

TASK [test_playbook] ******************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.77.128]

PLAY RECAP ****************************************************************************************************************
192.168.77.128             : ok=2    changed=1    unreachable=0    failed=0   

[root@server ~]# 

然後到客戶端上看看是否有創建test.txt文件:

[root@client ~]# ls -l /tmp/test.txt 
-rw-r--r-- 1 root root 0 1月  30 11:58 /tmp/test.txt
[root@client ~]# 

如上,代表執行成功。


24.23 playbook裏的變量

我們通過一個創建用戶的例子,來演示一下playbook裏的變量使用方式:

[root@server ~]# vim /etc/ansible/create_user.yml  # 編輯內容如下
---
- name: create_user
  hosts: testhost
  user: root
  gather_facts: false
  vars:
    - user: "test"
  tasks:
    - name: create user
      user: name="{{ user }}"

說明:

  • name參數對該playbook實現的功能做一個概述,後面執行過程中,會打印 name變量的值 ,可以省略;
  • gather_facts參數指定了在以下任務部分執行前,是否先執行setup模塊獲取主機相關信息,如果需要在後面的tasks裏獲取setup收集到的信息,就需要把這個參數設置爲True;
  • vars參數,指定了變量,這裏聲明瞭一個user變量,其值爲test ,需要注意的是,變量值一定要用引號引住;
  • user提定了調用user模塊,name是user模塊裏的一個參數,而增加的用戶名字調用了上面user變量的值。

執行該文件:

[root@server ~]# ansible-playbook /etc/ansible/create_user.yml

PLAY [create_user] ********************************************************************************************************

TASK [create user] ********************************************************************************************************
changed: [192.168.77.128]

PLAY RECAP ****************************************************************************************************************
192.168.77.128             : ok=1    changed=1    unreachable=0    failed=0   

[root@server ~]# 

到客戶端上看看用戶是否已創建:

[root@client ~]# id test
uid=1003(test) gid=1003(test) 組=1003(test)
[root@client ~]# 

24.24 playbook裏的循環

playbook除了有變量,還有循環語句,以下通過一個簡單的例子來演示一下循環的使用方式:

[root@server ~]# vim /etc/ansible/while.yml
---
- hosts: testhost
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} state=touch mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt

說明:

  • file模塊可以對文件進行相關的操作,例如創建文件或者更改文件權限等,具體可以查看該模塊的文檔
  • with_items爲循環的對象,相當於是一個數組或集合,寫在下面的1.txt、2.txt以及3.txt是該集合的元素。而item則表示的是遍歷出來的元素,也就是說item指代的是1.txt、2.txt以及3.txt。
  • state的值設置爲touch表示如果該文件不存在就進行創建
  • path表示文件的路徑
  • mode設置權限

執行該文件:

[root@server ~]# ansible-playbook /etc/ansible/while.yml 

PLAY [testhost] ***********************************************************************************************************

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

TASK [change mode for files] **********************************************************************************************
changed: [192.168.77.128] => (item=1.txt)
changed: [192.168.77.128] => (item=2.txt)
changed: [192.168.77.128] => (item=3.txt)

PLAY RECAP ****************************************************************************************************************
192.168.77.128             : ok=2    changed=1    unreachable=0    failed=0   

[root@server ~]# 

到客戶端上看看文件是否已創建:

[root@client ~]# ll /tmp/*.txt
-rw------- 1 root root  0 1月  30 15:54 /tmp/1.txt
-rw------- 1 root root  0 1月  30 15:54 /tmp/2.txt
-rw------- 1 root root  0 1月  30 15:54 /tmp/3.txt
[root@client ~]# 

24.25 playbook裏的條件判斷

我們都知道在腳本中循環和條件判斷是必不可少的語句,所以在playbook裏這兩種語句也是有的,循環我們已經介紹完了,接下來我們通過一個簡單的創建文件的例子演示一下條件判斷語句的使用方式。

我們一般以setup模塊收集到的主機信息,來作爲判斷條件。所以在編寫代碼之前,我們需要先獲取相應的信息,例如我要以ip地址來作爲判斷條件,那麼我就得先從setup裏獲取主機ip的相關信息。

執行以下命令可以查看到setup收集到的所有的facter信息,輸出的信息是JSON格式的:

ansible testhost -m setup

編寫文件內容如下:

[root@server ~]# vim /etc/ansible/when.yml
---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_eno16777736.ipv4.address == "192.168.77.128"

說明:

  • ansible_eno16777736是一個數組存儲着網卡相關信息,ipv4屬於該數組的子元素,但是ipv4也是一個數組,而address則是ipv4數組的子元素。我們需要使用address 來作爲判斷條件。
  • 所以要訪問address就需要使用這樣的格式:ansible_eno16777736.ipv4.address,address表示的是鍵,而"192.168.77.128"則是值,when爲判斷語句相當於if,所以其判斷條件爲:該鍵的值爲"192.168.77.128"時就執行shell模塊裏定義的語句。

執行該文件:

[root@server ~]# ansible-playbook /etc/ansible/when.yml 

PLAY [testhost] ***********************************************************************************************************

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

TASK [use when] ***********************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.77.128]

PLAY RECAP ****************************************************************************************************************
192.168.77.128             : ok=2    changed=1    unreachable=0    failed=0   

[root@server ~]# 

到客戶端上看看文件是否已創建:

[root@client ~]# ll /tmp/when.txt
-rw-r--r-- 1 root root 0 1月  30 16:33 /tmp/when.txt
[root@client ~]#

24.26 playbook中的handlers

有一種情況就是執行了tasks裏面的內容之後,服務器發生了變化,這時我們可能需要執行一些相關的操作。例如我們修改了某個服務的配置文件後,則需要重啓一下服務。而handlers就是完成這樣的事情的,它相當於編程中的回調函數,當tasks裏的內容執行成功後,就會執行handlers裏定義的內容。也類似於shell腳本中的&&符號,例如 cat 1.txt && rm -f 1.txt ,當cat 1.txt命令執行成功之後就會執行rm -f 1.txt命令,否則不執行。

下面用一個簡單的例子來演示一下handlers的使用方式:

[root@server ~]# vim /etc/ansible/handlers.yml
---
- name: handlers test
  hosts: testhost
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/test_passwd.txt
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "This is a test string" >> /tmp/test_passwd.txt

說明:

  • 只有copy模塊執行成功後,纔會去調用下面的handlers裏定義的內容。也就是說如果/etc/passwd和/tmp/test_passwd.txt內容是一樣的話,就不會去執行handlers裏面的shell相關命令,因爲copy沒有被執行。 這種比較適合配置文件發生更改後,重啓服務的操作。
  • notify用於指定handlers的name參數的值,因爲handlers可以定義多個,所以需要使用notify來進行指定調用哪一個。

執行該文件:

[root@server ~]# ansible-playbook /etc/ansible/handlers.yml 

PLAY [handlers test] ******************************************************************************************************

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

TASK [copy file] **********************************************************************************************************
changed: [192.168.77.128]

RUNNING HANDLER [test handlers] *******************************************************************************************
changed: [192.168.77.128]

PLAY RECAP ****************************************************************************************************************
192.168.77.128             : ok=3    changed=2    unreachable=0    failed=0   

[root@server ~]# 

到客戶端上看看文件末尾的那一行是否是我們echo進去的那一行內容:

[root@client ~]# tail -n1 /tmp/test_passwd.txt 
This is a test string
[root@client ~]# 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章