在使用ansible做自動化運維的時候,免不了的要重複執行某些操作,如:添加幾個使用者,建立幾個MySQL使用者并為之賦予權限,操作某個目錄下所有檔案等等。好在playbook支援循環語句,可以使得某些需求很容易而且很規範的實作。
with_items是playbooks中最基本也是最常用的循環語句:
上面例子表示,建立三個檔案分别為my.cnf、shadow、fstab
也可以将檔案清單提前指派給一個變量,然後在循環語句中調用:
<code> with_items: </code><code>"{{ somelist }}"</code>
<code>使用with_items疊代循環的變量可以是個單純的清單,也可以是一個較為複雜 的資料結果,如字典類型:</code>
<code><code>tasks:</code></code>
<code><code>- name: add several users</code></code>
<code><code> user: name=` item`.`name ` state=present groups=` item`.`groups `</code></code>
<code><code> with_items:</code></code>
<code><code> - { name: 'testuser1', groups: 'wheel' }</code></code>
<code><code> - { name: 'testuser2', groups: 'root' }</code></code>
<code></code>
示例:
tasks:
- 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' ]
item[0]是循環的第一個清單的值['alice','bob']。item[1]是第二個清單的值。表示循環建立alice和bob兩個使用者,并且為其賦予在三個資料庫上的所有權限。
也可以将使用者清單事先指派給一個變量:
- name: here, 'users' contains the above list of employees
- "`users`"
假如現在需要周遊一個使用者清單,并建立每個使用者,而且還需要為每個使用者配置以特定的SSH key登入。變量檔案内容如下:
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
- /tmp/bob/id_rsa.pub
password: other-mysql-password
- "db1"
- "DB2.*:ALL"
<code>playbook中定義如下:</code>
<code>- user: name=` item`.`name ` state=present generate_ssh_key=yes</code>
<code> with_items: "`users`"</code>
<code>- authorized_key: "user=` item`.`0`.`name ` key='{{ lookup('file', item.1) }}'"</code>
<code> with_subelements:</code>
<code> - users</code>
<code> - authorized</code>
<code>也可以周遊嵌套的子清單:</code>
<code>- name: Setup MySQL users</code>
<code> mysql_user: name=` item`.`0`.`name ` password=` item`.`0`.`mysql`.`password ` host=` item`.`1 ` priv={{ item.0.mysql.privs | join('/') }}</code>
<code> - users</code>
<code> - mysql.hosts</code>
with_sequence可以生成一個自增的整數序列,可以指定起始值和結束值,也可以指定增長步長。 參數以key=value的形式指定,format指定輸出的格式。數字可以是十進制、十六進制、八進制:
- hosts: all
tasks:
# create groups
- group: name=evens state=present
- group: name=odds state=present
# create some test users
- user: name=` item ` state=present groups=evens
with_sequence: start=0 end=32 format=testuser%02d
# create a series of directories with even numbers for some reason
- file: dest=/var/stuff/` item ` state=directory
with_sequence: start=4 end=16 stride=2 # stride用于指定步長
# a simpler way to use the sequence plugin
# create 4 groups
- group: name=group` item ` state=present
with_sequence: count=4
從清單中随機取一個值:
- debug: msg=` item `
with_random_choice:
- "go through the door"
- "drink from the goblet"
- "press the red button"
- "do nothing"
- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5
delay: 10
重複執行shell子產品,當shell子產品執行的指令輸出内容包含"all systems go"的時候停止。重試5次,延遲時間10秒。retries預設值為3,delay預設值為5。任務的傳回值為最後一次循環的傳回結果。
在循環中使用register時,儲存的結果中包含results關鍵字,該關鍵字儲存子產品執行結果的清單
- shell: echo "` item `"
with_items:
- one
- two
register: echo
變量echo内容如下:
{
"changed": true,
"msg": "All items completed",
"results": [
{
"changed": true,
"cmd": "echo \"one\" ",
"delta": "0:00:00.003110",
"end": "2013-12-19 12:00:05.187153",
"invocation": {
"module_args": "echo \"one\"",
"module_name": "shell"
},
"item": "one",
"rc": 0,
"start": "2013-12-19 12:00:05.184043",
"stderr": "",
"stdout": "one"
},
"cmd": "echo \"two\" ",
"delta": "0:00:00.002920",
"end": "2013-12-19 12:00:05.245502",
"module_args": "echo \"two\"",
"item": "two",
"start": "2013-12-19 12:00:05.242582",
"stdout": "two"
}
]
}
周遊注冊變量的結果:
- 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`"
- hosts: webservers
remote_user: root
vars:
alpha: [ 'a','b','c','d']
numbers: [ 1,2,3,4 ]
- debug: msg="` item`.`0 ` and ` item`.`1 `"
with_together:
- "` alpha `"
- "` numbers `"
輸出的結果為:
ok: [192.168.1.65] => (item=['a', 1]) => {
"item": [
"a",
1
],
"msg": "a and 1"
ok: [192.168.1.65] => (item=['b', 2]) => {
"b",
2
"msg": "b and 2"
ok: [192.168.1.65] => (item=['c', 3]) => {
"c",
3
"msg": "c and 3"
ok: [192.168.1.65] => (item=['d', 4]) => {
"d",
4
"msg": "d and 4"
loop子產品一般在下面的場景中使用
類似的配置子產品重複了多遍
fact是一個清單
建立多個檔案,然後使用assemble聚合成一個大檔案
使用with_fileglob比對特定的檔案管理
本文轉自 dengaosky 51CTO部落格,原文連結:http://blog.51cto.com/dengaosky/1852624,如需轉載請自行聯系原作者