本章內容:
一.inventory主機清單
二.yml語法
三.playbook詳解+操做php
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
(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。
對象 屬性1 長:5m 屬性2 寬:2m 屬性3 高:1.5m 集合 對象1 對象2 對象3
YAML:另外一種標記語言。是用來寫配置文件的語言,很是簡潔和強大。
YAML語法和其餘語言相似,也能夠表達散列表、標量等數據結構。
結構經過空格來展現;序列裏配置項經過-來表明;Map裏鍵值用:來分隔;YAML的擴展名爲yamlpython
1.大小寫敏感 2.使用縮進表示層級關係 3.縮進時不容許使用Tab鍵,只容許使用空格。 4.縮進的空格數目不重要,只要相同層級的元素左側對齊便可 YAML支持的數據結構: 1.對象:鍵值對的集合,又稱爲映射(mapping)/ 哈希(hashes) / 字典(dictionary) 例如:name:Example Developer 鍵 值 2.數組:一組按次序排列的值,又稱爲序列(sequence) / 列表(list) 例如:-Apple -Orange 3.純量:單個的、不可再分的值 例如:number:12.30 sure:true
name:zhangsan age:20 name:lisi age:22 people: -name:zhangsan age:20 -name:lisi age:22
經過task調用ansible的模板將多個play組織在一個playbook中運行。
playbooks自己由如下各部分組成
(1)Tasks:任務,即調用模塊完成的某操做;至關於事務,沒有執行成功就會回滾
(2)Variables:變量,主機清單,劇本,命令當中-e聲明變量,三種場景
(3)Templates:模板
(4)Handlers:處理器,當某條件知足時,觸發執行的操做;
(5)Roles:角色。mysql
- 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.253linux
[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 root@192.168.136.168 ssh-copy-id root@192.168.136.185 //配置密鑰對驗證 ssh-copy-id root@192.168.136.253 root@localhost ~]# ssh-agent bash #ssh代理 [root@localhost ~]# ssh-add #添加密碼
[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
--- - 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也是一些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
#把168的httpd配置文件複製過來 [root@localhost ~]# vim /etc/ansible/hosts [root@localhost ~]# scp root@192.168.136.168:/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
在一個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" 分別去兩臺被管理服務器上去查看文件建立狀況