Assign aws ec2 tag keys dynamically while creating ec2 instance using ansible

tasks:

  • name: Launch instance
    ec2:
    key_name: “{{ keypair }}”
    group: “{{ security_group }}”
    instance_type: “{{ instance_type }}”
    instance_tags:
    Name : “{{ tagname2 }}”
    image: “{{ image }}”
    wait: true
    region: “{{ region }}”
    vpc_subnet_id: “{{ vpc }}”

In the above snippet can I use Name in instance_tags as a variable and then pass that variables value using extra vars ansible

Hii

As you probably experienced, it's not possible to use variables for
dict keys, so something like this:

instance_tags:
  "{{ tag1 }}": "{{ value1 }}"

would actually result in the literal string '{{ tag1 }}' for the tag...

What I usually end up doing in scenarios like this, is to define a
list of dicts, with 'key' and 'value' keys, where you CAN define their
values, and then transform that structure use items2dict.
So in your case:

- name: Launch instance
  ec2:
    key_name: "{{ keypair }}"
    group: "{{ security_group }}"
    instance_type: "{{ instance_type }}"
    instance_tags: "{{ my_tags|items2dict }}"
    image: "{{ image }}"
    wait: true
    region: "{{ region }}"
    vpc_subnet_id: "{{ vpc }}"
  vars:
    my_tags:
      - key: "{{ tag_name }}"
        value: "{{ tag_value }}"

You can then supply both thee tag name and the value:

-e tag_name=Customer -e tag_value=FooCorp