在Ansible中,如何遍历具有数组的stdout?

时间:2019-01-03 18:59:27

标签: ansible-2.x

Ansible v2.6.3

我有一个任务可以像这样获取我的AWS ECS集群中的所有容器ARN

X_data = []
Y_data = []

for i in range(len(input_text)):
    xdata = []
    ydata = []
    xdata = xdata+[wordtovec(word,wrdvecdic) for word in input_text[i]]
    for i in range(len(input_text[i])):
        ydata.append([0 for i in range(300)])

    xdata.append([0 for i in range(300)])
    ydata.append([0 for i in range(300)])

    ydata = ydata+[wordtovec(word, wrdvecdic) for word in out_text[i]]
    for i in range(len(out_text[i])):
        xdata.append([0 for i in range(300)])

    X_data.append(xdata)
    Y_data.append(ydata)

X_data = np.array(X_data)
Y_data = np.array(Y_data)

输出是这个(修改了arn部分)

- name: List jenkins cluster container instances
  command: "aws ecs list-container-instances --cluster jenkins"
  register: jenkins_containers

- debug: var=jenkins_containers.stdout

如何遍历containerInstanceArns字段,以便例如

ok: [localhost] => {
    "jenkins_containers.stdout": {
        "containerInstanceArns": [
            "arn:aws:ecs:us-east-1:arn0", 
            "arn:aws:ecs:us-east-1:arn1", 
            "arn:aws:ecs:us-east-1:arn2"
        ]
    }
}

- debug: msg="Container ARN is {{ item }}"
  with_items: jenkins_containers.stdout.containerInstanceArns

以上两种代码当然都不起作用。

2 个答案:

答案 0 :(得分:0)

好,我必须这样做

- name: List jenkins cluster container instances
  command: "aws ecs list-container-instances --cluster jenkins"
  register: jenkins_containers

- set_fact:
    containers: "{{ jenkins_containers.stdout }}"

- debug: msg="{{ item }}" 
  with_items: "{{ containers.containerInstanceArns }}"

没有更优雅的方式吗?

答案 1 :(得分:0)

可以使用with_subelements。发件人:https://docs.ansible.com/ansible/2.4/playbooks_loops.html#looping-over-subelements

  

子元素遍历一个哈希表(又名字典),然后遍历带有这些记录内的给定(嵌套子)键的列表。

---

- hosts: localhost
  vars:
  - myvar: {'stdout': {'containerInstanceArns': ['arn:aws:ecs:us-east-1:arn0', 'arn:aws:ecs:us-east-1:arn1', 'arn:aws:ecs:us-east-1:arn2']}}

  tasks:
  - debug: 
      msg: '{{ item[1] }}'
    with_subelements:
    - '{{ myvar }}'
    - 'containerInstanceArns'

enter image description here