I have this playbook to create ec2 instances and will like to target each ec2 creation by tags but not working...when i run playbook i do not get any errors but notting gets created.

---
- name: Build or Check environment
  hosts: localhost
  connection: local
  become: yes
  vars_files:
    - ../vars/kafka-east.yml

  tasks:

    # name: launch kafka-east-1 ec2 instance
    - ec2:
       image: "{{ ami_id }}"
       key_name: "{{ key_name }}"
       instance_type: "{{ instance_type }}"
       instance_profile_name: "{{ instance_profile_name }}"
       region: us-east-1
       network_interfaces: "{{ item.eni }}"
       with_items:
          - {eni: 'kafka_east_1', tag: 'kafka_east_1'}
          - {eni: 'kafka_east_2', tag: 'kafka_east_2'}
       volumes:
       - device_name: /dev/sda1
         volume_size: "{{ ebs_size }}"
         device_type: "{{ ebs_type }}"
         delete_on_termination: true
       user_data: "{{ lookup('file', '../group_vars/kafka-east/user_data') }}"
       state: present

i get errors but just posted to kind of show what i am trying to accomplish. Anyone know how to properly achieve that? and set tags for each item in the with_items and loop round

so i can run the playbook and target a specific tag like this

ansible-playbook launch_ec2.yml --extra-vars "items_tags=kafka_east_1"

OR

ansible-playbook launch_ec2.yml --tags "kafka_east_1"

whichever way is correct.

Thanks!


First: The correct syntax for the with_items loop is:

- name: task name
  module:
    parameter1: value1
    parameter2: "{{ item }}"
  with_items:
    - item1
    - item2

So thats wrong and I wonder why Ansible didn't trow an error.

Second: You are mixing up tags in AWS with tags in Ansible. Tags in AWS are used to tag resources in AWS and the Ansible AWS modules usually feature this via parameters. But that's different from tags in Ansible. Those are used to tag tasks in a playbook to be able to limit the tasks executed by ansible-playbook to a subset of the tasks in a play.

tag a task in Ansible like this:

- name: task name
  module:
    parameter1: value1
  tags:
    - tag1
    - tag2

You could than limit the tasks executed by ansible-playbook like this:

ansible-playbook --tags=tag1 play.yml