-1

i have searched the whole internet and cannot find anwser to this question. "how can i terminate an ec2 instance using dynamic inventory with tags?" so if i can terminate an instance or group of ec2 instances with specific tag(s)

the ec2 module requires one to pass the instance-id but there is nothing automated in doing that. SO looking for a way to target specific tags using dynamic inventory with ansible

- name: terminate single instance
   hosts: all
   tasks:
     - action: ec2_facts
     - name: terminating single instance
       local_action:
         module: ec2
         state: 'absent'
         region: us-east-1
         instance_ids: "{{ ansible_ec2_instance_id }}"

I have tried the above with the following comamnd

ansible-playbook terminate.yml --tags "tag_Name_web_server"

which means i want too delete ec2 instances with Name' tag 'web-server Right now when i run that, it looks through several ec2 instances but it to only target those with the specified tags. Short story, does not work.

Any help will be greatly appreciated

uberrebu
  • 503
  • 6
  • 17
  • 36

2 Answers2

2

I ran into the same problem as you

As of today (Ansible 2.5 to be precise), it is possible to do what you want without host_vars with the ec2_instance module (it's different from the ec2 module)

For example, you want to terminate all ec2 instances with the tag-value pair: Usage:k8s-ansible, this is the task you'll need:

ec2_instance:
  state: absent
  filters:
    tag:Usage: k8s-ansible
Tran Triet
  • 153
  • 2
  • 8
0

--tags switch has nothing common with ec2 tags:

-t TAGS, --tags=TAGS only run plays and tasks tagged with these values

You should use external variables and host pattern:

- name: Terminate tagged instances
  hosts: tag_{{ tag_name }}_{{ tag_value }}
  tasks:
    - ec2_facts:
    - ec2:
        state: absent
        region: "{{ ansible_ec2_placement_region }}"
        instance_ids: "{{ ansible_ec2_instance_id }}"
      delegate_to: localhost

execution: ansible-playbook -e tag_name=Name -e tag_value=web_server terminate.yml

Konstantin Suvorov
  • 3,996
  • 1
  • 12
  • 13