ansible的主機清單,yml語法,playbook詳解+操作

本章內容:
一.inventory主機清單
二.yml語法
三.playbook詳解+操作

inventory主機清單

ansible默認的主機清單是/etc/ansible/hosts文件
主機清單可以手動設置,也可以通過Dynamic Inventory動態生成
一般主機名使用FQDN

vi /etc/ansible/hosts
[webserver]      #方括號設置組名
www1.example.org    #定義被監控主機,這邊可以是主機名也可以是IP地址,主機名需要修改/etc/hosts文件
www2.example.org:2222     #冒號後定義遠程連接端口,默認是ssh的22端口

如果是名稱類似的主機,可以使用列表的方式標識各個主機
[webserver]
www[01:50].example.org ansible_ssh_user=root ansible_ssh_pass=123456

[dbbservers]
db-[a:f].example.org

下面是Inventory中變量

(1)主機變量
[webserver]
www1.magedu.com http_port=80 maxRequestsChild=808
www2.magedu.com http_port=8080 maxRequestsChild=909
(2)組變量
[servers:vars]
ntp_server=ntp.example.org
nfs_server=nfs.example.org
(3)組嵌套
[apache]
http1.example.org
http2.example.org

[nginx]
ngx1.example.org
ngx2.example.org

[webservers:children]
apache
nginx

(4)inventory變量參數
參數                          說明
ansible_ssh_host    將要連接的遠程主機名.與你想要設定的主機的別名不同的話,可通過此變量設置.
ansible_ssh_port    ssh端口號.如果不是默認的端口號,通過此變量設置.
ansible_ssh_user    默認的 ssh 用戶名
ansible_ssh_pass    ssh 密碼(這種方式並不安全,我們強烈建議使用 --ask-pass 或 SSH 密鑰)
ansible_ssh_private_key_file    ssh 使用的私鑰文件.適用於有多個密鑰,而你不想使用 SSH 代理的情況.
ansible_ssh_common_args 此設置附加到sftp,scp和ssh的缺省命令行
ansible_sftp_extra_args 此設置附加到默認sftp命令行。
ansible_scp_extra_args  此設置附加到默認scp命令行。
ansible_ssh_extra_args  此設置附加到默認ssh命令行。
ansible_ssh_pipelining  確定是否使用SSH管道。 這可以覆蓋ansible.cfg中得設置。
ansible_shell_type  目標系統的shell類型.默認情況下,命令的執行使用 'sh' 語法,可設置爲 'csh' 或 'fish'.
ansible_python_interpreter  目標主機的 python 路徑.適用於的情況: 系統中有多個 Python, 或者命令路徑不是"/usr/bin/python",比如 *BSD, 或者 /usr/bin/python
ansible_*_interpreter   這裏的"*"可以是ruby 或perl 或其他語言的解釋器,作用和ansible_python_interpreter 類似
ansible_shell_executable    這將設置ansible控制器將在目標機器上使用的shell,覆蓋ansible.cfg中的配置,默認爲/bin/sh。

yaml語法

對象和集合的區別:

對象
  屬性1  長:5m
  屬性2  寬:2m
  屬性3  高:1.5m
集合
  對象1
  對象2
  對象3

YAML:另一種標記語言。是用來寫配置文件的語言,非常簡潔和強大。
YAML語法和其他語言類似,也可以表達散列表、標量等數據結構。
結構通過空格來展示;序列裏配置項通過-來代表;Map裏鍵值用:來分隔;YAML的擴展名爲yaml

基本語法規則:

1.大小寫敏感
2.使用縮進表示層級關係
3.縮進時不允許使用Tab鍵,只允許使用空格。
4.縮進的空格數目不重要,只要相同層級的元素左側對齊即可

YAML支持的數據結構:
1.對象:鍵值對的集合,又稱爲映射(mapping)/ 哈希(hashes) / 字典(dictionary)
 例如:name:Example Developer
        鍵     值
2.數組:一組按次序排列的值,又稱爲序列(sequence) / 列表(list)
 例如:-Apple
       -Orange
3.純量:單個的、不可再分的值
 例如:number:12.30
       sure:true

yaml示例:

name:zhangsan
age:20
name:lisi
age:22
people:
-name:zhangsan
      age:20
      -name:lisi
      age:22

playbook詳解+操作

Ansible的腳本---playbook

通過task調用ansible的模板將多個play組織在一個playbook中運行。
playbooks本身由以下各部分組成
(1)Tasks:任務,即調用模塊完成的某操作;相當於事務,沒有執行成功就會回滾
(2)Variables:變量,主機清單,劇本,命令當中-e聲明變量,三種場景
(3)Templates:模板
(4)Handlers:處理器,當某條件滿足時,觸發執行的操作;
(5)Roles:角色。

下面是一個playbook的示例

- hosts: webserver              //定義的主機組,即應用的主機
  vars:                        //定義變量
    http_port: 80
    max_clients: 200
  user: root
  tasks:                               //執行的任務
  - name: ensure apache is at the latest version #友好提示,自己定義
    yum: pkg=httpd state=latest #檢查httpd包是不是最新版本
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify: #調用觸發下面具體的操作
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:                       //處理器
    - name: restart apache #調這個操作
      service: name=httpd state=restarted

執行一個playbook
ansible-playbook [yaml文件名]
例如:ansible-playbook ping.yml
參數:-k(–ask-pass) 用來交互輸入ssh密碼
      -K(-ask-become-pass) 用來交互輸入sudo密碼
      -u   指定用戶
補充命令:
ansible-playbook nginx.yml --syntax-check    #檢查yaml文件的語法是否正確
ansible-playbook nginx.yml --list-task       #檢查tasks任務
ansible-playbook nginx.yml --list-hosts      #檢查生效的主機
ansible-playbook nginx.yml --start-at-task='Copy Nginx.conf'     #指定從某個task開始運行

實驗環境

主控端
被控端01 192.168.136.168
被控端02 192.168.136.185
被控端03 192.168.136.253

ansibel環境部署,加入主機清單

[webserver]
192.168.136.168
[mysql]
192.168.136.185
[ftpserver]
192.168.136.253
#關閉所有主機防火牆
[root@localhost ~]# systemctl stop firewalld.service 
[root@localhost ~]# setenforce 0
#免交戶
ssh-keygen -t rsa #生成密鑰,回車,輸入密碼
#公鑰推給對方主機
ssh-copy-id [email protected]
ssh-copy-id [email protected]    //配置密鑰對驗證
ssh-copy-id [email protected]
root@localhost ~]# ssh-agent bash #ssh代理
[root@localhost ~]# ssh-add #添加密碼

hosts和users介紹

[root@localhost ~]# vim a.yml

- hosts: webserver               #指定主機組,可以是一個或多個組。
  remote_user: root                #指定遠程主機執行的用戶名

[root@localhost ~]# ansible-playbook a.yml 

PLAY [webserver] ***************************************************************

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

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

還可以爲每個任務定義遠程執行用戶:

---
- hosts: mysql
  remote_user: root             
  tasks:
    - name: test connect
      ping:
      remote_user: root          #指定遠程主機執行tasks的運行用戶爲mysql
執行playbook時:ansible-playbook ping.yml
LAY [webserver] *******************************************************************

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

TASK [test connect] ****************************************************************
ok: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=0    unreachable=0    failed=0   

指定遠程主機sudo切換用戶:

---
- hosts: mysql
  remote_user: root            
  become: yes                  #2.6版本以後的參數,之前是sudo,意思爲切換用戶運行
  become_user: mysql          #指定sudo用戶爲mysql
執行playbook時:ansible-playbook ping.yml -K

tasks列表和action
1.Play的主體部分是task列表,task列表中的各任務按次序逐個在hosts中指定的主機上執行,即在所有主機上完成第一個任務後再開始第二個任務。
在運行playbook時(從上到下執行),如果一個host執行task失敗,整個tasks都會回滾,請修正playbook 中的錯誤,然後重新執行即可。
Task的目的是使用指定的參數執行模塊,而在模塊參數中可以使用變量,模塊執行時冪等的,這意味着多次執行是安全的,因爲其結果一致。
2.每一個task必須有一個名稱name,這樣在運行playbook時,從其輸出的任務執行信息中可以很好的辨別出是屬於哪一個task的。如果沒有定義name,‘action’的值將會用作輸出信息中標記特定的task。
3.定義一個task,常見的格式:”module: options” 例如:yum: name=httpd
4.ansible的自帶模塊中,command模塊和shell模塊無需使用key=value格式

小示例:
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
   - name: install httpd
     yum: name=httpd  

 #這邊還可以關閉防火牆,加上一段:
   - name: disable firewalld
     service: name=firewalld state=stopped

   - name: start httpd
     service: name=httpd state=started
[root@localhost ~]# ansible-playbook a.yml 

PLAY [webserver] *******************************************************************

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

TASK [disable selinux] *************************************************************
changed: [192.168.136.168]

TASK [install httpd] ***************************************************************
changed: [192.168.136.168]

TASK [start httpd] *****************************************************************
changed: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=4    changed=3    unreachable=0    failed=0   

play中只要執行命令的返回值不爲0,就會報錯,tasks停止

修改如下:加入執行失敗,我們可以設置一個參數跳過一個問題,繼續下面的操作ignore_errors: True 
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
     ignore_errors: True             #忽略錯誤,強制返回成功
   - name: make sure apache is running
     service: name=httpd state=started

以下是另外一個示例,可以讀一讀

---
- hosts: webserver
  remote_user: root
  tasks:
   - name: create nginx group
     group: name=nginx system=yes gid=208
   - name: create nginx user
     user: name=nginx uid=208 group=nginx system=yes
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file to mysql
     copy: src=/etc/inittab dest=/opt/inittab.back

Handlers介紹

Handlers也是一些task的列表,和一般的task並沒有什麼區別。
是由通知者進行的notify,如果沒有被notify,則Handlers不會執行,假如被notify了,則Handlers被執行
不管有多少個通知者進行了notify,等到play中的所有task執行完成之後,handlers也只會被執行一次

示例
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: install httpd package
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      -restart httpd
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:
   - name: restart httpd
     service: name=httpd state=restarted

也可以引入變量
    ---
- hosts: webserver
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
   - name: install httpd package
     yum: name={{package}} state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      -restart httpd
   - name: start httpd service
     service: enabled=true name={{service}} state=started
  handlers:
   - name: restart httpd
     service: name={{service}} state=restarted

#寫一個創建用戶的引入變量的小事列
[root@localhost ~]# vim b.yml 
- hosts: ftpserver
  remote_user: root
  vars:
   - username: lisi
  tasks:
   - name: create user
     user: name={{username}}
[root@localhost ~]# ansible-playbook b.yml --syntax-check

playbook: b.yml
[root@localhost ~]# ansible-playbook b.yml 

PLAY [ftpserver] *******************************************************************

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

TASK [create user] *****************************************************************
ok: [192.168.136.253]

PLAY RECAP *************************************************************************
192.168.136.253            : ok=2    changed=0    unreachable=0    failed=0   
ansible-playbook b.yml -e username=lisi
主機清單也可以加入要使用的用戶

playbook使用變量的方法:
1.通過ansible命令傳遞
例如:編輯如下yaml
vi a.yml
---
- hosts: mysql
  remote_user: root
  vars:
  - user:
  tasks:
  - name: add new user
    user: name={{user}}
然後執行命令: ansible-playbook a.yml -e "user=testvar"
可以執行命令查看:ansible mysql -m command -a 'tail /etc/passwd'

2.直接在yaml中定義變量---如上handlers示例
3.直接引用一些變量
如:引用ansible的固定變量
#content指定文件內容到路徑下
vi test.yml
---
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}}," dest=/opt/vars.txt
執行命令:ansible-playbook test.yml
去253上查看vars.txt文件內容
[root@localhost opt]# cat add.txt 
["192.168.122.1", "192.168.136.253"]

再如:引用主機變量
vi /etc/ansible/hosts
在mysql組的主機後面添加如下
[mysql]
192.168.80.183 testvar="80.183"          #定義testvar變量的值爲80.183
vi test.yml      #添加{{testvar}}主機變量
---
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}},{{testvar}}" dest=/opt/vars.txt
執行命令:ansible-playbook test.yml
去183上查看vars.txt文件內容

--------條件測試--------

如果需要根據變量、facts(setup)或此前任務的執行結果來作爲某task執行與否的前提時要用到條件測試,在Playbook中條件測試使用when子句。
在task後添加when子句即可使用條件測試:when子句支持jinjia2表達式或語法,例如:
vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shutdown CentOS"
      command: /sbin/shutdown -h now #-r重啓
      when: ansible_distribution == "CentOS"
PLAY [mysql] ***********************************************************************

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

TASK [shutdown CentOS] *************************************************************
fatal: [192.168.136.185]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to 192.168.136.185 closed.\r\n", "unreachable": true}
    to retry, use: --limit @/root/b.retry

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

多條件判斷

vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shut down CentOS 6 systems"
      command: /sbin/shutdown -r now
      when:
        - ansible_distribution == "CentOS"
        - ansible_distribution_major_version == "6"

組條件判斷(和,且,或)

vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shut down CentOS 6 and Debian 7 systems"
      command: /sbin/shutdown -t now
      when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
            (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")

自定義變量進行條件測試

#滿足爲true就創建文件,滿足爲False舊刪除
vi when.yml
---
- hosts: all
  vars:
    exist: "True"
  tasks:
  - name: creaet file
    command:  touch /tmp/test.txt
    when: exist | match("True") #match:匹配

  - name: delete file
    command:  rm -rf /tmp/test.txt
    when: exist | match("False")    

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.253]
ok: [192.168.136.168]
ok: [192.168.136.185]

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

changed: [192.168.136.185]
changed: [192.168.136.253]
changed: [192.168.136.168]

TASK [delete file] *****************************************************************
skipping: [192.168.136.253]
skipping: [192.168.136.168]
skipping: [192.168.136.185]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.185            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.253            : ok=2    changed=1    unreachable=0    failed=0   

----------迭代-------------#相當於遍歷

當有需要重複性執行的任務時,可以使用迭代機制。其使用格式爲將需要迭代的內容定義爲item變量引用,並通過with_items語句指明迭代的元素列表即可。例如:
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: "Install Packages"
      yum: name={{ item }} state=latest #item:去下面的集合遍歷
      with_items: #一步一步安裝
        - httpd
        - mysql-server
        - php   
也可以自己定義(還可以設置數組,看做一整行,後面根據調某一個屬性變量名,就調出來了)
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: "Add users"
      user: name={{ item.name }} state=present groups={{ item.groups }}
      with_items:
        - { name:'test1', groups:'wheel'}
        - { name:'test2', groups:'root'}

#小事列
- hosts: all
  vars:
    exist: "False"
  tasks:
  - name: create users
    user: name={{item}}
    with_items:
     - t01
     - t02
     - t03

ok: [192.168.136.253]
ok: [192.168.136.168]
ok: [192.168.136.185]

TASK [create users] ****************************************************************
changed: [192.168.136.253] => (item=t01)
changed: [192.168.136.168] => (item=t01)
changed: [192.168.136.185] => (item=t01)
changed: [192.168.136.253] => (item=t02)
changed: [192.168.136.168] => (item=t02)
changed: [192.168.136.185] => (item=t02)
changed: [192.168.136.253] => (item=t03)
changed: [192.168.136.168] => (item=t03)
changed: [192.168.136.185] => (item=t03)

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.185            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.253            : ok=2    changed=1    unreachable=0    failed=0   
#去主機查看有沒有這些用戶
t01:x:1001:1001::/home/t01:/bin/bash
t02:x:1002:1002::/home/t02:/bin/bash
t03:x:1003:1003::/home/t03:/bin/bash

Templates模塊

#把168的httpd配置文件複製過來
[root@localhost ~]# vim /etc/ansible/hosts 
[root@localhost ~]# scp [email protected]:/etc/httpd/conf/httpd.conf ./
httpd.conf                                        100%   11KB   4.0MB/s   00:00  
#修改httpd配置文件
Listen {{http_port}} #變量
ServerName {{server_name}}
MaxClients {{access_num}}

mv httpd.conf httpd.conf.j2

#賦值
[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]
192.168.136.168 http_port=192.168.136.168:80  server_name="www.yun.com:80" access_num=200 #指定端口,域名,訪問次數200

[root@localhost ~]# vim apache.yml
- hosts: webserver
  remote_user: root
  vars:
   - package: httpd
   - service: httpd
  tasks:
    - name: check latest
      yum: name-{{package}} state=latest
    - name: configure apache
      template: src=/etc/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #源在本地的控制端,指定對方的被控端
      notify:
        - restart httpd
    - name: start httpd
      service: name={{server}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{server}} state=restarted

[root@localhost ~]# ansible-playbook apache.yml --syntax-check

playbook: apache.yml
[root@localhost ~]# ansible-playbook apache.yml 

PLAY [webserver] *******************************************************************

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

TASK [check latest] ****************************************************************
ok: [192.168.136.168]

TASK [configure apache] ************************************************************
changed: [192.168.136.168]

TASK [start httpd] *****************************************************************
changed: [192.168.136.168]

RUNNING HANDLER [restart httpd] ****************************************************
changed: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=5    changed=3    unreachable=0    failed=0   
#有了模板就根據這個模板就統一修改其他被控端的所有主機的配置文件

去兩臺遠程主機上查看
grep -i listen /etc/httpd/conf/httpd.conf
grep -i maxClient /etc/httpd/conf/httpd.conf
grep -i servername /etc/httpd/conf/httpd.conf

tags模塊

在一個playbook中,我們一般會定義很多個task,如果我們只想執行其中的某一個task或多個task時就可以使用tags標籤功能了,格式如下:
vi hosts.yml
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/etc/hosts
      tags:
      - only #打上標記我只執行我標記的操作
    - name: touch file
      file: path=/opt/hosts state=touch
執行命令:ansible-playbook hosts.yml --tags="only"
PLAY [webserver] *******************************************************************

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

TASK [Copy hosts file] *************************************************************
ok: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=0    unreachable=0    failed=0   

ansible-playbook hosts.yml

事實上,不光可以爲單個或多個task指定同一個tags。playbook還提供了一個特殊的tags爲always。作用就是當使用always當tags的task時,無論執行哪一個tags時,定義有always的tags都會執行。
vi hosts.yml
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/etc/hosts
      tags:
      - only
    - name: touch file
      file: path=/opt/hosts state=touch
      tags:
      - always
執行命令:ansible-playbook hosts.yml --tags="only"
分別去兩臺被管理服務器上去查看文件創建情況
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章