snailrider
snailrider

Reputation: 55

Using variable for tag name in Ansible AWS modules

ec2_snapshot module allows me to create snapshots of volumes and tag at the same time. This is straight forward while using fix names for tags. But how can I set tag name itself from a variable?

Example task:

- name: AWS EBS Disks Snapshot For Volumes
  ec2_snapshot:
    aws_access_key: "{{ aws_access_key_id }}"
    aws_secret_key: "{{ aws_secret_key_id }}"
    security_token: "{{ aws_security_token }}"
    volume_id: "{{ item.id }}"
    region:  "{{ aws_region }}"
    snapshot_tags: 
      Name: "{{ timestamp.stdout }}"
      "{{ tagname_variable }}": "{{ tagvalue_variable }}"
      type: "{{ item.type }}"
    description: "{{ timestamp.stdout }}_snapshot"
  with_items:
    - "{{ volumeinputs }}"

The tagname_variable is literally created as a tag name, not the value of the variable.
How I can make this work?

Upvotes: 1

Views: 239

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39264

You will need to dynamically create that part of you dictionary, for example, with a combine, as YAML dictionaries key are usually not templated by Ansible.

This can be done in a vars sections of the task itself:

- name: AWS EBS Disks Snapshot For Volumes
  ec2_snapshot:
    aws_access_key: "{{ aws_access_key_id }}"
    aws_secret_key: "{{ aws_secret_key_id }}"
    security_token: "{{ aws_security_token }}"
    volume_id: "{{ item.id }}"
    region:  "{{ aws_region }}"
    snapshot_tags: "{{ _snapshot_tags }}"
    description: "{{ timestamp.stdout }}_snapshot"
  loop: "{{ volumeinputs }}"
  vars:
    _snapshot_tags_static:
      Name: "{{ timestamp.stdout }}"
      type: "{{ item.type }}"
    _snapshot_tags: >-
      {{
        _snapshot_tags_static
        | combine({tagname_variable: tagvalue_variable})
      }}

Upvotes: 1

Related Questions