skip to Main Content

I have this playbook, and it’s not working. what I want to do is that I want to apply the specific tag or tags for the ec2 instance to the attached ebs volumes. form the amazon.aws.ec2_instance_info: I get the all information for the ec2 and then with
"{{ item | flatten | map(attribute='block_device_mappings') | flatten | map(attribute='ebs') | flatten | map(attribute='volume_id') }}" we can extract the volume ids, but it return the list of ids like below

[
  vol-xxxxxxx,
  vol-zzzzzzz,
]

how to make sure for each loop it choose one of the volume id and passed it to amazon.aws.ec2_tag:

thanks for your help

playbook:

---
- name: Ansible Test Playbook
  gather_facts: false
  hosts: localhost
  vars_files:
    - vars/regions.yaml

  tasks:
    - name: Gather information about all instances
      amazon.aws.ec2_instance_info:
        region: "{{ item }}"
      register: instance_info
      loop: "{{ region }}"

    - name: Copy tags from EC2 to EBS
      amazon.aws.ec2_tag:
        region: us-east-1
        resource: "{{ item | flatten | map(attribute='block_device_mappings') | flatten | map(attribute='ebs') | flatten | map(attribute='volume_id') }}" 
        state: present
        tags:
          "team": "{{ item | flatten | map(attribute='tags') | flatten | map(attribute='team') | join }}"
      loop: "{{ instance_info.results | map(attribute='instances') }}"

2

Answers


  1. Chosen as BEST ANSWER

    Thank you so much @Vladimir Botka it is working finally, now I have only one problem, at the beginning of the playbook I defined the

    vars_files: 
      - vars/regions.yaml 
    

    and that file contains the list of regions like below

    region: 
     - us-east-1 
     - us-east-2 
    

    now how to use the region in the

     - amazon.aws.ec2_tag: 
         region: us-east-1
    

    instead of hardcoding the region name!


  2. Q: "Each loop passes one of the volume ids to amazon.aws.ec2_tag"

    A: Declare volume_ids and teams (the same way you do it in the loop) and use them in the task

        - amazon.aws.ec2_tag:
            region: us-east-1
            resource: "{{ item }}"
            state: present
            tags:
              team: "{{ teams }}"
          loop: "{{ volume_ids }}"
          vars:
            volume_ids: "{{ instance_info.results|
                            map(attribute='instances')|flatten|
                            map(attribute='block_device_mappings')|flatten|
                            map(attribute='ebs')|flatten|
                            map(attribute='volume_id') }}"
            teams: "{{ instance_info.results|
                       map(attribute='instances')|flatten|
                       map(attribute='tags')|flatten|
                       map(attribute='team')|join }}"
    

    (not tested)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search