條件判斷
When 語(yǔ)句
在when 后面使用Jinja2 表達(dá)式禽笑,結(jié)果為True則執(zhí)行任務(wù)永丝。
tasks:
- name: "shut down Debian flavored systems"
command: /sbin/shutdown -t now
when: ansible_os_family == "Debian"
若操作系統(tǒng)是Debian 時(shí)就執(zhí)行關(guān)機(jī)操作
可以對(duì)條件進(jìn)行分組在比較漱办。
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")
可以使用列表形式來(lái)表示條件為and的關(guān)系
tasks:
- name: "shut down CentOS 6 systems"
command: /sbin/shutdown -t now
when:
- ansible_distribution == "CentOS"
- ansible_distribution_major_version == "6"
使用jinja2過(guò)濾器
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
- command: /bin/something_else
when: result|succeeded
- command: /bin/still/something_else
when: result|skipped
忽略一個(gè)語(yǔ)句的錯(cuò)誤,然后決定基于成功或失敗有條件地做一些事情。
字符串轉(zhuǎn)換為數(shù)字型再去比較
tasks:
- shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6
使用變量進(jìn)行判斷
vars:
epic: true
tasks:
- shell: echo "This certainly is epic!"
when: epic
tasks:
- shell: echo "This certainly isn't epic!"
when: not epic
判斷變量是否定義
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
與循環(huán)一起使用
tasks:
- command: echo {{ item }}
with_items: [ 0, 2, 4, 6, 8, 10 ]
when: item > 5
依次遍歷列表扫茅,當(dāng)列表里得數(shù)字大于5時(shí)執(zhí)行任務(wù)
- command: echo {{ item }}
with_items: "{{ mylist|default([]) }}"
when: item > 5
- command: echo {{ item.key }}
with_dict: "{{ mydict|default({}) }}"
when: item.value > 5
當(dāng)變量不存在時(shí),直接跳過(guò)
使用自定義的facts值做判斷
tasks:
- name: gather site specific fact data
action: site_facts
- command: /usr/bin/thingy
when: my_custom_fact_just_retrieved_from_the_remote_system == '1234'
角色包含使用when
- include: tasks/sometasks.yml
when: "'reticulating splines' in output"
- hosts: webservers
roles:
- { role: debian_stock_config, when: ansible_os_family == 'Debian' }
基于變量選擇文件和模板
- name: template a file
template: src={{ item }} dest=/etc/myapp/foo.conf
with_first_found:
- files:
- {{ ansible_distribution }}.conf
- default.conf
paths:
- search_location_one/somedir/
- /opt/other_location/somedir/
使用注冊(cè)變量判斷
- name: test play
hosts: all
tasks:
- shell: cat /etc/motd
register: motd_contents
- shell: echo "motd contains the word hi"
when: motd_contents.stdout.find('hi') != -1
failed_when
滿足條件時(shí)育瓜,使任務(wù)失敗
tasks:
- command: echo faild.
register: command_result
failed_when: "'faild' in command_result.stdout"
- debug: msg="echo test"
還可以寫成這樣
tasks:
- command: echo faild.
register: command_result
ignore_errors: True
- name: fail the echo
fail: msg="the command failed"
when: "'faild' in command_result.stdout"
- debug: msg="echo test"
changed_when
更改任務(wù)的狀態(tài)葫隙。
- name: Install dependencies via Composer.
command: "/usr/local/bin/composer global require phpunit/phpunit --prefer-dist"
register: composer
changed_when: "'Nothing to install or update' not in composer.stdout"
當(dāng)使用PHP Composer作為安裝項(xiàng)目依賴項(xiàng)的命令時(shí),知道什么時(shí)候是有用的Composer安裝了一些東西爆雹,或什么都沒(méi)有改變停蕉。
循環(huán)
標(biāo)準(zhǔn)循環(huán)
添加多個(gè)用戶
- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
添加多個(gè)用戶,并將用戶加入不同的組內(nèi)钙态。
- name: add several users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }
嵌套循環(huán)
分別給用戶授予3個(gè)數(shù)據(jù)庫(kù)的所有權(quán)限
- name: give users access to multiple databases
mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
with_nested:
- [ 'alice', 'bob' ]
- [ 'clientdb', 'employeedb', 'providerdb' ]
遍歷字典
輸出用戶的姓名和電話
tasks:
- name: Print phone records
debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: {'alice':{'name':'Alice Appleworth', 'telephone':'123-456-789'},'bob':{'name':'Bob Bananarama', 'telephone':'987-654-3210'} }
并行遍歷列表
tasks:
- debug: "msg={{ item.0 }} and {{ item.1 }}"
with_together:
- [ 'a', 'b', 'c', 'd','e' ]
- [ 1, 2, 3, 4 ]
如果列表數(shù)目不匹配慧起,用None補(bǔ)全
遍歷列表和索引
- name: indexed loop demo
debug: "msg='at array position {{ item.0 }} there is a value {{ item.1 }}'"
with_indexed_items: [1,2,3,4]
item.0 為索引,item.1為值
遍歷文件列表的內(nèi)容
---
- hosts: all
tasks:
- debug: "msg={{ item }}"
with_file:
- first_example_file
- second_example_file
遍歷目錄文件
with_fileglob匹配單個(gè)目錄中的所有文件册倒,非遞歸匹配模式蚓挤。
---
- hosts: all
tasks:
- file: dest=/etc/fooapp state=directory
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:
- /playbooks/files/fooapp/*
當(dāng)在role中使用with_fileglob的相對(duì)路徑時(shí),Ansible解析相對(duì)于roles/<rolename>/files目錄的路徑驻子。
遍歷ini文件
lookup.ini
[section1]
value1=section1/value1
value2=section1/value2
[section2]
value1=section2/value1
value2=section2/value2
- debug: msg="{{ item }}"
with_ini: value[1-2] section=section1 file=lookup.ini re=true
獲取section1 里的value1和value2的值
重試循環(huán) until
- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5
delay: 10
"重試次數(shù)retries" 的默認(rèn)值為3灿意,"delay"為5。
查找第一個(gè)匹配文件
tasks:
- debug: "msg={{ item }}"
with_first_found:
- "/tmp/a"
- "/tmp/b"
- "/tmp/default.conf"
依次尋找列表中的文件崇呵,找到就返回缤剧。如果列表中的文件都找不到,任務(wù)會(huì)報(bào)錯(cuò)域慷。
隨機(jī)選擇with_random_choice
隨機(jī)選擇列表中得一個(gè)值
- debug: msg={{ item }}
with_random_choice:
- "go through the door"
- "drink from the goblet"
- "press the red button"
- "do nothing"
循環(huán)程序的結(jié)果
tasks:
- debug: "msg={{ item }}"
with_lines: ps aux
循環(huán)子元素
定義好變量
#varfile
---
users:
- name: alice
authorized:
- /tmp/alice/onekey.pub
- /tmp/alice/twokey.pub
mysql:
password: mysql-password
hosts:
- "%"
- "127.0.0.1"
- "::1"
- "localhost"
privs:
- "*.*:SELECT"
- "DB1.*:ALL"
- name: bob
authorized:
- /tmp/bob/id_rsa.pub
mysql:
password: other-mysql-password
hosts:
- "db1"
privs:
- "*.*:SELECT"
- "DB2.*:ALL"
---
- hosts: web
vars_files: varfile
tasks:
- user: name={{ item.name }} state=present generate_ssh_key=yes
with_items: "{{ users }}"
- authorized_key: "user={{ item.0.name }} key='{{ lookup('file', item.1) }}'"
with_subelements:
- "{{ users }}"
- authorized
- name: Setup MySQL users
mysql_user: name={{ item.0.name }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}
with_subelements:
- "{{ users }}"
- mysql.hosts
{{ lookup('file', item.1) }} 是查看item.1文件的內(nèi)容
with_subelements 遍歷哈希列表荒辕,然后遍歷列表中的給定(嵌套)的鍵。
在序列中循環(huán)with_sequence
with_sequence以遞增的數(shù)字順序生成項(xiàng)序列犹褒。 您可以指定開始抵窒,結(jié)束和可選步驟值。
參數(shù)應(yīng)在key = value對(duì)中指定叠骑。 'format'是一個(gè)printf風(fēng)格字符串李皇。
數(shù)字值可以以十進(jìn)制,十六進(jìn)制(0x3f8)或八進(jìn)制(0600)指定宙枷。 不支持負(fù)數(shù)掉房。
---
- hosts: all
tasks:
# 創(chuàng)建組
- group: name=evens state=present
- group: name=odds state=present
# 創(chuàng)建格式為testuser%02x 的0-32 序列的用戶
- user: name={{ item }} state=present groups=evens
with_sequence: start=0 end=32 format=testuser%02x
# 創(chuàng)建4-16之間得偶數(shù)命名的文件
- file: dest=/var/stuff/{{ item }} state=directory
with_sequence: start=4 end=16 stride=2
# 簡(jiǎn)單實(shí)用序列的方法:創(chuàng)建4 個(gè)用戶組分表是組group1 group2 group3 group4
- group: name=group{{ item }} state=present
with_sequence: count=4
隨機(jī)選擇with_random_choice
隨機(jī)選擇列表中得一個(gè)值
- debug: msg={{ item }}
with_random_choice:
- "go through the door"
- "drink from the goblet"
- "press the red button"
- "do nothing"
合并列表
# 安裝所有列表中的軟件
- name: flattened loop demo
yum: name={{ item }} state=installed
with_flattened:
- [ 'foo-package', 'bar-package' ]
- [ ['one-package', 'two-package' ]]
- [ ['red-package'], ['blue-package']]
注冊(cè)變量使用循環(huán)
- shell: echo "{{ item }}"
with_items:
- one
- two
register: echo
- name: Fail if return code is not 0
fail:
msg: "The command ({{ item.cmd }}) did not have a 0 return code"
when: item.rc != 0
with_items: "{{ echo.results }}"
循環(huán)主機(jī)清單
# 輸出所有主機(jī)清單里的主機(jī)
- debug: msg={{ item }}
with_items: "{{ groups['all'] }}"
# 輸出所有執(zhí)行的主機(jī)
- debug: msg={{ item }}
with_items: play_hosts
#輸出所有主機(jī)清單里的主機(jī)
- debug: msg={{ item }}
with_inventory_hostnames: all
# 輸出主機(jī)清單中不在www中的所有主機(jī)
- debug: msg={{ item }}
with_inventory_hostnames: all:!www
改變循環(huán)的變量項(xiàng)
# main.yml
- include: inner.yml
with_items:
- 1
- 2
- 3
loop_control:
loop_var: outer_item
# inner.yml
- debug: msg="outer item={{ outer_item }} inner item={{ item }}"
with_items:
- a
- b
- c
更多文章請(qǐng)看 Ansible 專題文章總覽