Ansible-playbook 應(yīng)用梳理
前面已經(jīng)介紹過Ansible的安裝配置及常見模塊的使用 --《Linux下使用Ansible處理批量操作》
Palybook簡介
palybook是由一個或多個paly組成的列表,play的主要功能在于將事先歸并為一組的主機裝扮成事先通過ansible中的task定義好的角色。從根本上來講,所謂 task 無非是調(diào)用 ansible 的一個 module。將多個play組織在一個 playbook 中,即可以讓它們聯(lián)同起來按事先編排好的機制同唱一臺大戲。
一個playbook由以下幾個部分組成
hosts:運行執(zhí)行任務(wù)(task)的目標(biāo)主機。remote_user:在遠程主機上執(zhí)行任務(wù)的用戶。tasks:任務(wù)集。varniables: 內(nèi)置變量或自定義變量在playbook中調(diào)用,變量替換{{ variable_name }}。templates:模板,即使用模板語法的文件,比如配置文件等,使用jinja2語法。handlers:和notity結(jié)合使用,由特定條件觸發(fā)的操作,滿足條件方才執(zhí)行,否則不執(zhí)行。tags:標(biāo)簽,指定某條任務(wù)執(zhí)行,用于選擇運行playbook中的部分代碼。
注意:
gather_facts是一個play級別的指令設(shè)置,是負責(zé)收集目標(biāo)主機信息的任務(wù),由setup模塊提供。默認情況下,每個play都會先執(zhí)行這個特殊的任務(wù),收集完信息之后才開始執(zhí)行其它任務(wù)。但是,收集目標(biāo)主機信息的效率很低,如果能夠確保playbook中不會使用到所收集的信息,可以顯式指定gather_facts: no來禁止這個默認執(zhí)行的收集任務(wù)。- handler用來執(zhí)行某些條件下的任務(wù),比如當(dāng)配置文件發(fā)生變化的時候,通過
notify觸發(fā)handler去重啟服務(wù)。在saltstack中也有類似的觸發(fā)器,寫法相對Ansible簡單,只需要watch,配置文件即可。
為什么引入Playbook?
- playBook功能比ad-hoc更全,是對ad-hoc的一種編排。
- playBook能很好的控制先后執(zhí)行順序,以及依賴關(guān)系。
- playBook語法展現(xiàn)更加的直觀。
- playbook可以持久使用,ad-hoc無法持久使用。
YAML的基本語法規(guī)則
- playbook文件擴展名可以是
yaml,也可以是yml。使用“#”號表示注釋至行尾。 - 在playbook文件中,可以連續(xù)三個減號(---)區(qū)分多個play。還有選擇性的連續(xù)三個點(...)用來表示play的結(jié)尾,也可省略。
- 第二行開始正常寫playbook的內(nèi)容,一般都會寫上描述該playbook的功能。建議盡量為每個
play和每個task都命名,且名稱具有唯一性。 - 只允許使用空格,縮進的級別必須是一致的,同樣的縮進代表同樣的級別,不能用
Tab鍵縮進;程序判別配置的級別是通過縮進結(jié)合換行實現(xiàn)的。 - YAML文件內(nèi)容是區(qū)分大小寫的,
key/value的值均需大小寫敏感。多個key/value可同行寫也可換行寫。同行使用分號(:)分隔,換行寫需要以減號(-)分隔。
YAML支持以下常用幾種數(shù)據(jù)類型
- 標(biāo)量:單個的、不可再分的值 ;不可在分的量。包括字符串,布爾值,整數(shù),浮點數(shù),Null,時間,日期。key對應(yīng)value
- 對象:鍵值對的集合,又稱為映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 數(shù)組:一組按次序排列的值,又稱為序列(sequence) / 列表(list)
三種常見的數(shù)據(jù)格式
XML:Extensible Markup Language,可擴展標(biāo)記語言,可用于數(shù)據(jù)交換和配置。JSON:JavaScript Object Notation, JavaScript 對象表記法,主要用來數(shù)據(jù)交換或配置,不支持注釋。YAML:YAML Ain't Markup Language YAML 不是一種標(biāo)記語言, 主要用來配置,大小寫敏感,不支持tab。
Playbook命令及用法
ansible-playbook <filename.yml> ... [options]
ansible-playbook官方命令選項:https://docs.ansible.com/ansible/2.9/cli/ansible-playbook.html
[root@AnsibleControl ~]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
[root@AnsibleControl ~]# ansible-playbook --h
optional arguments:
--ask-vault-pass ask for vault password
#加密playbook文件時提示輸入密碼
--flush-cache clear the fact cache for every host in inventory
#清除清單中每個主機的緩存
--force-handlers run handlers even if a task fails
#強制運行handlers的任務(wù),即使任務(wù)失敗也運行處理程序
--list-hosts outputs a list of matching hosts; does not execute anything else
#輸出匹配主機列表;不執(zhí)行任何其他操作
--list-tags list all available tags
#列出所有可用的標(biāo)簽
--list-tasks list all tasks that would be executed
#列出所有將要執(zhí)行的任務(wù)
--skip-tags SKIP_TAGS only run plays and tasks whose tags do not match these values
#跳過指定的tags任務(wù)
--start-at-task START_AT_TASK start the playbook at the task matching this name
#在匹配此名稱的任務(wù)處開始運行劇本
--step one-step-at-a-time: confirm each task before running
#在運行前確認每個任務(wù),逐個執(zhí)行
--syntax-check perform a syntax check on the playbook, but do not execute it
#對playbook執(zhí)行語法檢查,并不實際執(zhí)行
--vault-id VAULT_IDS the vault identity to use
#使用的密碼標(biāo)識
--vault-password-file VAULT_PASSWORD_FILES vault password file
#密碼文件
--version show program's version number, config file location,configured module search path, module location,executable location and exit
#顯示程序的版本號、配置文件位置、配置的模塊搜索路徑、模塊位置、可執(zhí)行文件位置和退出
-C, --check don't make any changes; instead, try to predict some of the changes that may occur
#不做任何改變,不會真正在機器上執(zhí)行(查看執(zhí)行會產(chǎn)生什么變化),只是測試
-D, --diff when changing (small) files and templates, show the differences in those files; works great with --check
#更改(小)文件和模板時,顯示這些文件中的差異;與-C配合使用效果更好
-M MODULE_PATH, --module-path MODULE_PATH
prepend colon-separated path(s) to module library (def
ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
gins/modules)
#將冒號分隔的路徑添加到模塊庫
-e EXTRA_VARS, --extra-vars EXTRA_VARS set additional variables as key=value or YAML/JSON, if filename prepend with @
#在Playbook中引入外部參數(shù)變量
-f FORKS, --forks FORKS specify number of parallel processes to use (default=5)
#指定要使用的并行進程數(shù)(默認值=5)FORKS被指定為一個整數(shù)
-h, --help show this help message and exit
-i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY specify inventory host path or comma separated host list. --inventory-file is deprecated
#指定清單主機路徑或逗號分隔的主機列表,代替--inventory-file
-l SUBSET, --limit SUBSET further limit selected hosts to an additional pattern
#限制選定的主機
-t TAGS, --tags TAGS only run plays and tasks tagged with these values
#只運行帶有tags標(biāo)記的任務(wù)
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
Connection Options:
control as whom and how to connect to hosts
--private-key PRIVATE_KEY_FILE, --key-file PRIVATE_KEY_FILE use this file to authenticate the connection
#使用此文件來驗證連接
--scp-extra-args SCP_EXTRA_ARGS specify extra arguments to pass to scp only (e.g. -l)
#指定僅傳遞給scp的額外參數(shù)
--sftp-extra-args SFTP_EXTRA_ARGS specify extra arguments to pass to sftp only (e.g. -f,-l)
#指定僅傳遞給sftp的額外參數(shù)
--ssh-common-args SSH_COMMON_ARGS specify common arguments to pass to sftp/scp/ssh (e.g.ProxyCommand)
#指定要傳遞給 sftp/scp/ssh 的常用參數(shù)
--ssh-extra-args SSH_EXTRA_ARGS specify extra arguments to pass to ssh only (e.g. -R)
#指定僅傳遞給 ssh 的額外參數(shù)
-T TIMEOUT, --timeout TIMEOUT override the connection timeout in seconds (default=10)
#SSH連接超時時間設(shè)定,默認10s
-c CONNECTION, --connection CONNECTION connection type to use (default=smart)
#指定連接方式
-k, --ask-pass ask for connection password
-u REMOTE_USER, --user REMOTE_USER connect as this user (default=None)
#指定遠程主機以什么用戶身份運行命令
Privilege Escalation Options:
control how and which user you become as on target hosts
--become-method BECOME_METHOD privilege escalation method to use (default=sudo), use `ansible-doc -t become -l` to list valid choices.
#要使用的權(quán)限提升方法 (default=%(default)s),使用ansible-doc -t become -l列出有效選項。
--become-user BECOME_USER run operations as this user (default=root)
#以該用戶身份運行操作(默認=root)
-K, --ask-become-pass ask for privilege escalation password
#要求輸入提權(quán)密碼
-b, --become run operations with become (does not imply password prompting)
#使用指定用戶運行操作(不暗示密碼提示)
在inventory中定義主機及主機組, 默認/etc/ansible/hosts文件中
[root@AnsibleControl ansible]# pwd
/etc/ansible
[root@AnsibleControl ansible]# tail -11 hosts
[ansible]
ansible-01 ansible_host=172.16.70.181
ansible-02 ansible_host=172.16.70.182
AnsibleControl ansible_ssh_host=172.16.70.37
[webservers]
ansible-01 ansible_host=172.16.70.181
ansible-02 ansible_host=172.16.70.182
[control]
AnsibleControl ansible_ssh_host=172.16.70.37
示例:服務(wù)器初始化 init.yaml
[root@AnsibleControl ansible]# cat init.yaml
---
- name: Set Hostname #PLAY名稱
hosts: webservers #在inventory中定義主機及主機組,等其他組合
gather_facts: false #禁止執(zhí)行默認setup模塊,不收集目標(biāo)主機信息
vars: #設(shè)置變量,可在play級別,也可在task級別
hostnames:
- host: 172.16.70.181
name: ansible-01
- host: 172.16.70.182
name: ansible-01
tasks:
- name: set hostname #TASK名稱
hostname:
name: "{{ item.name }}"
when: item.host == inventory_hostname
loop: "{{ hostnames }}"
- name: Disable Selinux
hosts: all
gather_facts: false
tasks:
- block:
- name: disable on the fly
shell: setenforce 0
- name: disable forever in config
lineinfile:
path: /etc/selinux/config
line: "SELINUX=disabled"
regexp: '^SELINUX='
ignore_errors: true
- name: Modify sshd_config
hosts: webservers
gather_facts: false
tasks:
- name: backup sshd config
shell:
/usr/bin/cp -f {{path}} {{path}}.bak
vars:
- path: /etc/ssh/sshd_config
- name: disable root login
lineinfile:
path: "/etc/ssh/sshd_config"
line: "PermitRootLogin no"
insertafter: "^#PermitRootLogin"
regexp: "^PermitRootLogin"
notify: "restart sshd"
- name: disable password auth
lineinfile:
path: "/etc/ssh/sshd_config"
line: "PasswordAuthentication no"
regexp: "^PasswordAuthentication yes"
notify: "restart sshd"
handlers:
- name: "restart sshd"
service:
name: sshd
state: restarted
********** 如果您認為這篇文章還不錯或者有所收獲,請點擊右下角的【推薦】/【贊助】按鈕,因為您的支持是我繼續(xù)創(chuàng)作分享的最大動力! **********
作者:講文張字
出處:http://www.rzrgm.cn/zhangwencheng
版權(quán):本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接
出處:http://www.rzrgm.cn/zhangwencheng
版權(quán):本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接
浙公網(wǎng)安備 33010602011771號