在with_items循环中迭代

时间:2019-05-23 09:25:51

标签: amazon-web-services amazon-ec2 ansible

您好,我在atm试图摆脱与ansible的纠缠,到目前为止,我真的很喜欢它的灵活性。

现在,我的实验开始让我感到困惑。我正在尝试为具有标签 environment:test 的特定实例的卷添加标签 environment:test backup:true 。如果我在with_items循环中指定数组的每个索引,则剧本将按预期工作。到目前为止,这是我的剧本:

---
- name: Tag the EBS Volumes
  hosts: tag_environment_test
  gather_facts: False
  tags: tag
  vars_files:
    - /etc/ansible/vars/aws.yml

  tasks:
  - name: Gather instance instance_ids
    local_action:
        module: ec2_remote_facts
        region: '{{ aws_region }}'
        filters:
            instance-state-name: running
            "tag:environment": test
    register: test_id

  - name: Gather volume information for instance
    local_action:
        module: ec2_vol
        region: '{{ aws_region }}'
        instance: "{{ item.id }}"
        state: list
    with_items:
     - "{{ test_id.instances }}"
    register:  ec2_volumes
  - debug:
      var: ec2_volumes

  - name: Do some actual tagging
    local_action:
       module: ec2_tag
       region: '{{ aws_region }}'
       resource: "{{ item.id }}"
       args:
         tags:
          environment: test
          backup: true
    with_items:
      - "{{ ec2_volumes.results[0].volumes }}"
#      - "{{ ec2_volumes.results[1].volumes }}"

我的问题现在是可以遍历ec2_volumes.results中的整个数组,而无需指定数组中的每个值。例如,例如 _ec2_volumes.results [X] .volumes X = X + 1 _ ,因此每次他通过循环时,他都会+1直到数组末尾。

在剧本其余部分的每个输入都会非常有用(就像我说的那样,仍然试图摆脱ansible的困扰。:)

问候 服装

1 个答案:

答案 0 :(得分:0)

您可以遍历结果列表:

- name: Do some actual tagging
  delegate_to: localhost
  ec2_tag:
    region: '{{ aws_region }}'
    resource: "{{ item.volume.id }}"
    tags:
      environment: test
      backup: true
  with_items: "{{ ec2_volumes.results }}"

  

在剧本的其余部分上进行的所有输入都会非常感激

请考虑使用delegate_to: localhost而不是local_action。考虑一下此任务:

- name: an example
  command: do something

使用delegate_to,我只需要添加一行:

- name: an example
  delegate_to: localhost
  command: do something

使用local_action时,我需要重写任务:

- name: an example
  local_action:
    module: command do something

当然,delegate_to更灵活:您可以使用它来委派除本地主机以外的主机。

更新

在没有看到您实际的剧本的情况下,很难确定错误的来源。这是一本完整的剧本,可以成功运行(使用合成数据并将您的ec2_tag任务包装在debug任务中):

---
- hosts: localhost
  gather_facts: false
  vars:
    aws_region: example
    ec2_volumes:
      results:
        - volume:
            id: 1
        - volume:
            id: 2
  tasks:
    - name: Do some actual tagging
      debug:
        msg:
          ec2_tag:
            region: '{{ aws_region }}'
            resource: '{{ item.volume.id }}'
            tags:
              environment: test
              backup: true
      with_items: "{{ ec2_volumes.results }}"
相关问题