My playbook is creating multiple instances of application in AWS.I want each of the instance to be tagged with a counter variable to maintain the count and id of each instance (do not want to use instance id and any other random id). Now , since the provisioning happens in parallel i am failing to get a consistent counter variable. I have tried using a global variable to the play and incrementing it but it always returns the initial value as set fact is executed once. I have also tried putting a variable in a file, reading and incrementing it for every host. This leads to race condition and i see same values for different hosts. Is there any way to do this.
Assuming that your ec2.ini file has
all_instances = True
to get stopped instances, they already ARE tagged, in a sense.
webserver[1] is always going to be the same host, until your inventory changes.
However, you can still tag your instances as you want, but if your inventory changes, it might be difficult to tag new instances with unique numbers.
- name: Loop over webserver instances and tag sequentially
ec2_tag:
state: present
tags:
myTag: "webserver{{item}}"
resource: "{{ hostvars[groups['webserver'][item|int]]['ec2_id'] }}"
with_sequence: start=0 end="{{ groups['webserver']|length - 1 }}"
delegate_to: localhost
N.B: item is a string, so we have to use [item|int] when pulling from the groups['webserver'] array.