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

**URL:** <https://forum.ansible.com/t/assign-aws-ec2-tag-keys-dynamically-while-creating-ec2-instance-using-ansible/35722>\
**Category:** Ansible Project\
**Tags:** aws\
**Created:** [September 11, 2021, 5:13am UTC](https://forum.ansible.com/t/assign-aws-ec2-tag-keys-dynamically-while-creating-ec2-instance-using-ansible/35722 "2021-09-11T05:13:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![shrutika\_mehta](https://avatars.discourse-cdn.com/v4/letter/s/a587f6/32.png) [@shrutika\_mehta](https://forum.ansible.com/u/shrutika_mehta)\
**Post date:** [September 11, 2021, 5:13am UTC](https://forum.ansible.com/t/assign-aws-ec2-tag-keys-dynamically-while-creating-ec2-instance-using-ansible/35722/1 "2021-09-11T05:13:56Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Dick\_Visser](https://avatars.discourse-cdn.com/v4/letter/d/d9b06d/32.png) [@Dick\_Visser](https://forum.ansible.com/u/Dick_Visser)\
**Post date:** [September 13, 2021, 11:54am UTC](https://forum.ansible.com/t/assign-aws-ec2-tag-keys-dynamically-while-creating-ec2-instance-using-ansible/35722/2 "2021-09-13T11:54:48Z")

</div>

Hii

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

instance\_tags:  
&nbsp;&nbsp;"{{ 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  
&nbsp;&nbsp;ec2:  
&nbsp;&nbsp;&nbsp;&nbsp;key\_name: "{{ keypair }}"  
&nbsp;&nbsp;&nbsp;&nbsp;group: "{{ security\_group }}"  
&nbsp;&nbsp;&nbsp;&nbsp;instance\_type: "{{ instance\_type }}"  
&nbsp;&nbsp;&nbsp;&nbsp;instance\_tags: "{{ my\_tags|items2dict }}"  
&nbsp;&nbsp;&nbsp;&nbsp;image: "{{ image }}"  
&nbsp;&nbsp;&nbsp;&nbsp;wait: true  
&nbsp;&nbsp;&nbsp;&nbsp;region: "{{ region }}"  
&nbsp;&nbsp;&nbsp;&nbsp;vpc\_subnet\_id: "{{ vpc }}"  
&nbsp;&nbsp;vars:  
&nbsp;&nbsp;&nbsp;&nbsp;my\_tags:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- key: "{{ tag\_name }}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value: "{{ tag\_value }}"

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

-e tag\_name=Customer -e tag\_value=FooCorp
