简体   繁体   中英

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?

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})
      }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM