Ansible-遍历动态生成的列表项

时间:2018-07-30 16:00:12

标签: list loops variables ansible

有关过滤JSON的初始问题已发布here。为了便于查看,通过注册ec2_vol模块的“列表”输出生成的JSON为(stdout):

<div class="items-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>

正如我上一篇文章的“答案”中所建议的那样,添加列表元素(例如{ "msg": { "failed": false, "changed": false, "volumes": [ { "status": "in-use", "zone": "us-east-1a", "tags": { "Name": "voltag:/" }, "encrypted": false, "iops": 120, "create_time": "2018-04-11T20:47:49.948Z", "snapshot_id": "snap-id", "attachment_set": { "device": "/dev/sda1", "instance_id": "iid", "deleteOnTermination": "true", "status": "attached", "attach_time": "2018-04-11T20:47:50.000Z" }, "type": "gp2", "id": "volid", "size": 40 }, { "status": "in-use", "zone": "us-east-1a", "tags": { "Name": "voltag:/pgdata" }, "encrypted": false, "iops": 120, "create_time": "2018-05-07T18:32:52.810Z", "snapshot_id": "", "attachment_set": { "device": "/dev/sdb", "instance_id": "iid", "deleteOnTermination": "false", "status": "attached", "attach_time": "2018-05-07T18:33:39.000Z" }, "type": "gp2", "id": "volid", "size": 40 } ] }, "changed": false, "_ansible_verbose_always": true, "_ansible_no_log": false } )确实可行,但是我仍然需要遍历所有列表元素。通过使用以下代码,我能够获得上面列表的索引(范围从1到6,但在这种情况下只有2):

"{{ stdout.volumes[0].attachment_set.device }}"

现在的问题是,由于我正在动态生成所有这些数据(JSON和索引),所以我不知道如何将它们组合到下一个代码块中,即:

    - name: Get device indices
      set_fact:
        device_index: "{{ item }}"
      with_sequence: start=0 end={{stdout.volumes | length -1}}

如您所见,我基本上是在尝试合并2个“注册”任务(一个寄存器,一个set_fact)的输出,并且上面的代码不起作用,因为“小胡子不会堆叠”。我还尝试了以下组合:

    - name: Delete any existing snapshot
      ec2_snapshot:
        region: us-east-1
        aws_access_key: "{{ access }}"
        aws_secret_key: "{{ secret }}"
        instance_id: "{{ ec2_id }}"
        device_name: "{{ stdout.volumes[{{ item }}].attachment_set.device }}"
      with_items: "{{ device_index }}"
      tags: delete_existing

但是上面的代码导致 - name: Get device indices set_fact: devices: stdout.volumes[{{ item }}].attachment_set.device with_sequence: start=0 end={{stdout.volumes | length -1}} - name: Delete any existing snapshot ec2_snapshot: region: us-east-1 aws_access_key: "{{ access }}" aws_secret_key: "{{ secret }}" instance_id: "{{ ec2_id }}" device_name: "{{ item }}" state: absent with_items: "{{ devices }}" tags: delete_existing (依此类推)直接作为字符串输入到任务中,并且变量没有得到解释。

0 个答案:

没有答案