I'm trying to use Ansible to create two instances, one each in two subnets using the play below. I'm using exact_count with tag Name to keep track of instances. There are two issues here:
- Ansible ends up creating two instances in the first subnet and reports [ok] for the second subnet.
- Ansible doesn't seem to care about stopped instances. It creates new instances, instead of starting existing ones, or atleast considering them as part of the group of instances.
- name: Create kafka instances with_items: - "{{ vpc_pvt_subnet_2 }}" - "{{ vpc_pvt_subnet_1 }}" ec2: group: "{{ kafka_sg }}" key_name: "{{ ec2_keypair }}" region: "{{ region }}" image: "{{ ami_id }}" wait: true instance_type: "{{ kafka_inst_type }}" vpc_subnet_id: "{{ item }}" instance_tags: Name: "kafka-instance" Owner: data exact_count: 2 count_tag: Name: "kafka-instance" register: ec2
Can someone please tell me what's wrong with the playbook here?
Assuming that you want to create 1 EC2 instance in each subnet, one visible error in the snippet you provided is that the value of
exact_count
should be set to 1 (not 2) becausewith_items
will loop to runec2
module twice in your playbook. You want each iteration to create exactly 1 instance.Next, I will answer according to your questions -
1] You need to specify
zone
parameter as well toec2
module. Sincezone
is dynamic according to avpc_subnet_id
, I would suggest the following structure -In your vars -
In the
ec2
task -2] Yes, the above way will always create new instance even if an instance already exists in a subnet with "stopped" state as if this instance never existed. If you want to explicitly start the "stopped" instances by tags, you can achieve that by passing the
state
parameter to a newec2
task - you cannot usestate
andexact_count
parameters together in the same task.Hope this helps!