Ansible-与项目一起使用遍历数组

时间:2019-10-29 11:10:04

标签: ansible ansible-2.x ansible-inventory ansible-facts ansible-template

我确实有一个简单的json文件,我需要从每个数组项中提取一组值,但在迭代过程中会失败。

我的剧本看起来像:

code:

---

 - name: direct - this works like charm
   set_fact:
     bb: "{{ pr_json.json.issues[0].fields.customfield_11756.value }}"

 - debug:
     var: bb

 - name: via array - this is not working since iteration is not happening
   set_fact:
     dd_branch: "{{ pr_json.json.issues[{{ item }}].fields.customfield_11756.value }}"
   register: mass

 - debug:
     var: mass

获取输出为:


TASK [jira_update : direct - this works like charm] ********************************************************************************************************************
task path: /home/test/ansible_jira/roles/jira_update/tasks/call.yml:3
ok: [localhost] => {
    "ansible_facts": {
        "bb": "R4.19"
    },
    "changed": false
}

TASK [jira_update : debug] *********************************************************************************************************************************************
task path: /home/test/ansible_jira/roles/jira_update/tasks/call.yml:7
ok: [localhost] => {
    "bb": "R4.19"
}

TASK [jira_update : via array - this is not working since iteratoin is not happening] **********************************************************************************
task path: /home/test/ansible_jira/roles/jira_update/tasks/call.yml:10
fatal: [localhost]: FAILED! => {
    "msg": "template error while templating string: expected token ':', got '}'. String: {{ pr_json.json.issues[{{ item }}].fields.customfield_11756.value }}"
}

请告知我们如何在每个序列上遍历数组变量值。

也尝试过此操作,但是请有人可以帮助迭代数组值。

 - name: Create PR request in TEMS JIRA
   jira:
     uri: "{{ tems_jira }}"
     username: "{{ user }}"
     password: "{{ pass }}"
     operation: create
     project: PR
     issuetype: 'PR-Form'
     summary: "{{ pr_json.json| json_query('issues[].fields.summary') }}"
     description: "{{ pr_json.json | json_query('issues[].fields.description') }}"
   args:
     fields:
       customfield_10303:
         value: "{{ pr_json.json | json_query('issues[].fields.customfield_11756.value') }}"

1 个答案:

答案 0 :(得分:0)

您需要将列表提供给with_items迭代器。那就是为循环目的设置item变量的原因。

- name: via array - this is not working since iteration is not happening
  set_fact:
    dd_branch: "{{ pr_json.json.issues[ item ].fields.customfield_11756.value }}"
  register: mass
  with_items:
    - 0
    - 1

这将遍历pr_json.json.issues的所有列表项,这将使您可以更深入地了解所需的变量结构。您可以在循环中输入许多其他因素,这些可能会引起您的兴趣,您可以在此处找到详细信息。

https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html