在Ansible中,如何使用数组迭代stdout?

时间:2018-10-25 20:05:18

标签: ansible ansible-2.x

Ansible v2.6.3

我有一个简单的任务,它可以在我的jenkins ECS集群中获取AWS ARN

  tasks:
  - command: aws ecs list-container-instances --cluster jenkins
    register: jenkins_ecs_containers

  - debug: var=jenkins_ecs_containers.stdout

并具有以下输出

TASK [debug] *******************************************************************
ok: [localhost] => {
    "jenkins_ecs_containers.stdout": {
        "containerInstanceArns": [
           "arn:aws:ecs:us-east-1:arn0", 
           "arn:aws:ecs:us-east-1:arn1"
        ]
    }
}

如何遍历ARN?我尝试过

- debug: var=item
  with_items: jenkins_ecs_containers.stdout.containerInstanceArns

给予

TASK [debug] *******************************************************************
ok: [localhost] => (item=jenkins_ecs_containers.stdout.containerInstanceArns) => {
    "item": "jenkins_ecs_containers.stdout.containerInstanceArns"
}

- debug: var=item
  with_items: "{{ jenkins_ecs_containers.stdout.containerInstanceArns }}"

给予

TASK [debug] *******************************************************************
fatal: [localhost]: FAILED! => {"msg": "'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'containerInstanceArns'"}
    to retry, use: --limit @/Users/cfouts/git-repos/ansible/playbooks/loop.retry

谢谢!

2 个答案:

答案 0 :(得分:0)

我用您的输出创建了一个文件。因此,我使用了set_fact。否则,它只是一个字符串,而不是JSON对象:

  tasks:

  - command: cat files/stdout.txt
    register: result

  - debug: var=result.stdout

  - set_fact:
      jenkins_ecs_containers: "{{ result.stdout }}"

  - debug:
      msg: "{{ item }}"
    with_items: "{{ jenkins_ecs_containers.containerInstanceArns }}"

这给了我以下输出:

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "result.stdout": {
        "containerInstanceArns": [
            "arn:aws:ecs:us-east-1:arn0", 
            "arn:aws:ecs:us-east-1:arn1"
        ]
    }
}

TASK [set_fact] ****************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => (item=None) => {
    "msg": "arn:aws:ecs:us-east-1:arn0"
}
ok: [localhost] => (item=None) => {
    "msg": "arn:aws:ecs:us-east-1:arn1"
}

PLAY RECAP *********************************************************************
localhost                  : ok=5    changed=1    unreachable=0    failed=0   

答案 1 :(得分:0)

您可以这样迭代:

'div'

浏览此link,它将使内容更清晰。