2015-11-16 34 views
1

我有一個ansible任務是這樣的:ansible如何使用一個變量在for循環

- name: coreos network configuration 
    {% for interface in argument['interfaces'] %} 
     {% if argument[interface]['role'] == 'ingest' %} 
    script: netconfiginput.sh -i {{interface}} #incorrect, how to get the value of the interface variable of the for loop? 
     {% endif %} 
    {% endfor %} 

當運行這個ansible任務,我傳遞一個JSON字符串參數:

ansible-playbook --extra-vars 'argument={"interfaces":["eno1","eno2","ep8s0"],"eno2":{"role":"ingest"}}' network-config.yml 

我想要做的是,循環訪問名爲interfaces的JSON數組,這是一個網絡接口列表,當接口的role被稱爲ingest時,我運行腳本並將網絡接口作爲參數傳遞給腳本,我的實現是不正確,我該怎麼辦這個?

回答

1

您需要使用with_items並用item替換變量名稱。

一個粗略的例子:

name: task name 
script: netconfiginput.sh -i {{ item }} 
with_items: interfaces_array 
when: some_role == 'ingest' 

要了解你要發送什麼樣的數據,使用以下命令:

name: debugging 
debug: 
    var: argument 

這應該告訴你,除其他事項外,無論是否Ansible正在考慮你的變量的結構有效數組的部分或不。

+0

我想這一點,但我得到的錯誤'with_items預計列表或set'。它應該是'參數[某個接口] ['角色']'。 –

+0

我剛剛稍微修改了我的答案。如果你沒有傳遞數組,那麼你應該在前面的命令中使用'debug'來查看它是如何傳遞的。 – Humza

1

Jinja2可用於安全模板而不是劇本。 Ansible支持循環散列。你可以試試這個:

--- 
- hosts: <test_servers> # replace with your hosts 
    vars: 
    interfaces: 
     eno1: 
     role: null 
     eno2: 
     role: ingest 
     ep8s0: 
     role: null 
    tasks: 
    - name: coreos network configuration 
     script: netconfiginput.sh -i {{ item.key }} 
     with_dict: "{{interfaces}}" 
     when: item.value.role == "ingest"