在一個task中循環某個操作
1、標准循環
- name: add several usersuser:name: "{{ item }}"state: presentgroups: "wheel"loop:- testuser1- testuser2#如果已經在變量文件中,定義了yaml列表,可以這么寫loop: "{{ somelist }}"
note:在2.5 Ansible之前主要使用with_ <lookup>關鍵字來創建循環,循環關鍵字基本上類似於with_list,with_items。
我現在也在用,啊哈!
一些ansible插件,類似yum和apt模塊可以直接列出引用的選項,比使用loop更好,如下:
- name: optimal yumyum:name: "{{list_of_packages}}"state: present- name: non optimal yum, not only slower but might cause issues with interdependenciesyum:name: "{{item}}"state: presentloop: "{{list_of_packages}}"
迭代的items類型也可以是hash列表,例如:
- name: add several usersuser:name: "{{ item.name }}"state: presentgroups: "{{ item.groups }}"loop:- { name: 'testuser1', groups: 'wheel' }- { name: 'testuser2', groups: 'root' }
2、復雜的循環
有時候你不只是需要一個簡單列表,你可以用jinja2表達式創建復雜的列表,例如使用 “netsed" lookup
- name: give users access to multiple databasesmysql_user:name: "{{ item[0] }}"priv: "{{ item[1] }}.*:ALL"append_privs: yespassword: "foo"loop: "{{ query('nested', [ 'alice', 'bob' ], [ 'clientdb', 'employeedb', 'providerdb' ]) }}"
note: with_ 循環實際上是組合了 with_ + lookup(),甚至是with_items。 loop也可以這么搞,類似上邊例子。
3、使用lookup 與 用loop查詢
ansible2.5加入了新的函數 query,為lookup插件增加一些益處,當使用新的關鍵字loop時候。query提供一個更簡單的借口和可預測性更好的輸出,確保兼容loop。
一些情況中,lookup函數不會返回 loop需要的list,下列的調用是相等的:
loop: "{{ query('nested', ['alice', 'bob'], ['clientdb', 'employeedb', 'providerdb']) }}"loop: "{{ lookup('nested', ['alice', 'bob'], ['clientdb', 'employeedb', 'providerdb'], wantlist=True) }}"
4、Do-Until循環
- shell: /usr/bin/fooregister: resultuntil: result.stdout.find("all systems go") != -1retries: 5delay: 10
上例 遞歸執行shell模塊,直到“all systems go”在標准輸出出現,或者每個10s執行1次,執行5次之后無結果。 retries默認值是3,delay默認值是5。
note:如果until參數沒有定義, retries值被強制設置為1。
5、使用loop中的register
- shell: "echo {{ item }}"loop:- "one"- "two"register: echo
與使用loop和register不同的例子
{"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"},{"changed": true,"cmd": "echo \"two\" ","delta": "0:00:00.002920","end": "2013-12-19 12:00:05.245502","invocation": {"module_args": "echo \"two\"","module_name": "shell"},"item": "two","rc": 0,"start": "2013-12-19 12:00:05.242582","stderr": "","stdout": "two"}]}
循環遍歷注冊的變量來檢查結果:
- name: Fail if return code is not 0fail:msg: "The command ({{ item.cmd }}) did not have a 0 return code"when: item.rc != 0loop: "{{ echo.results }}"
在迭代期間,當前item的結果將被放置在變量中
- shell: echo "{{ item }}"loop:- one- tworegister: echochanged_when: echo.stdout != "one"
6、循環inventory
如果想循環inventory中的hosts或者部分hosts,你可以用loop的ansible_play_batch或者groups變量:
# show all the hosts in the inventory- debug:msg: "{{ item }}"loop: "{{ groups['all'] }}"#show all the hosts in the current play- debug:msg: "{{ item }}"loop: "{{ ansible_play_batch }}"
使用lookup 插件 inventory_hostname 實現:
# show all the hosts in the inventory- debug:msg: "{{ item }}"loop: "{{ query('inventory_hostnames', 'all') }}"# show all the hosts matching the pattern, ie all but the group www- debug:msg: "{{ item }}"loop: "{{ query('inventory_hostnames', 'all!www') }}"
7、循環控制
2.0版本你可以使用loops和task includes(不能用playbook includes)。這增加了一次循環一組任務的能力。每次循環,Ansible默認設置循環變量item,這會導致這些嵌套loop覆蓋來自“外部”循環的項目的值。從Ansible 2.1開始,loop_control選項可用於指定要用於循環的變量名。
# main.yml- include: inner.yml- include_tasks: inner.ymlloop:- 1- 2- 3loop_control:loop_var: outer_item# inner.yml- debug:msg: "outer item={{ outer_item }} inner item={{ item }}"loop:- a- b- c
note:如果Ansible檢測到當前循環正在使用已定義的變量,則會引發錯誤以使任務失敗。
當使用復雜的數據結構來循環顯示時,可能會出現busy情況,這就是label指令提供幫助的地方
- name: create serversdigital_ocean:name: "{{ item.name }}"state: presentloop:- name: server1disks: 3gbram: 15Gbnetwork:nic01: 100Gbnic02: 10Gb...loop_control:label: "{{ item.name }}"
現在,它將只顯示標簽字段,而不是每個項目的整個結構,它默認為{{item}}來照常顯示內容。
循環控制的另一個選項是暫停,它允許您控制執行任務循環中的項目之間的時間(以秒為單位)。
# main.yml- name: create servers, pause 3s before creating nextdigital_ocean:name: "{{ item }}"state: presentloop:- server1- server2loop_control:pause: 3
如果您需要跟蹤您在循環中的位置,可以使用index_var選項來循環控制以指定變量名稱以包含當前循環索引。
- name: count our fruitdebug:msg: "{{ item }} with index {{ my_idx }}"loop:- apple- banana- pearloop_control:index_var: my_idx
8、loops和 includes (2.0版本)
由於loop_control在Ansible 2.0中不可用,因此當使用帶有循環的include時,應該使用set_fact保存item的“outer”循環值:
# main.yml- include_tasks: inner.ymlloop:- 1- 2- 3# inner.yml- set_fact:outer_item: "{{ item }}"- debug:msg: "outer item={{ outer_item }} inner item={{ item }}"loop:- a- b- cNote
