Sudhir Kumar
Sudhir Kumar

Reputation: 153

Error while creating Aws ec2 instance using Ansible

I had run the simple task to create aws instance.

Instance got created after that I terminated the ec2 instance from AWS web console. Later on I added more tasks to it but could never create the ec2 instance using the tasks.

I keep getting the error as:

fatal: [localhost]: FAILED! => {"changed": false, "msg": "Instances with id(s) ['i-0f513aec91787e83d'] were created previously but have since been terminated - use a (possibly different) 'instance-id' parameter"}

It keeps reporting about the previous instance id. I can see that there is no such instance in my AWS console.

Can someone explain to me why is this happening?

- name: get any running ec2 instance
  ec2_instance_info:
    aws_access_key: "{{ec2_access_key}}"
    aws_secret_key: "{{ec2_secret_key}}"
    region: "{{region}}"
    filters:
      instance-state-name: ['running']
  register: ec2_list

- name: Display ec2_list
  debug: msg="{{item.instance_id}}"
  with_items: "{{ec2_list.instances}}"


- name: Terminate Any running Instances
  ec2:
    state: 'absent'
    instance_ids: "{item.instance_id}"
  with_items: "{{ec2_list.instances}}"


- name: Create new ec-2 instance
  ec2:
    aws_access_key: "{{ec2_access_key}}"
    aws_secret_key: "{{ec2_secret_key}}"
    key_name: "{{key_name}}"
    id: "{{id}}"
    instance_type: t2.micro
    image: "{{image}}"
    region: "{{region}}"
    vpc_subnet_id: "{{vpc_subnet_id}}"
    wait: yes
    count: 1
    assign_public_ip: yes
  register: ec2

- name: Wait for ssh to come up
  delegate_to: "{{ item.public_dns_name }}"
  wait_for_connection:
    delay: 60
    timeout: 320
    loop: "{{ ec2.instances }}"

- name: Terminate currently running Instances
  ec2:
    state: 'absent'
    instance_ids: "{{ec2.instance_ids}}"

Upvotes: 1

Views: 1224

Answers (2)

thibaut sanniee
thibaut sanniee

Reputation: 21

The documentation of ec2 ansible module say that:

id: This identifier is valid for at least 24 hours after the termination of the instance, and should not be reused for another call later on.

Did you change this id ?

Upvotes: 1

thibaut sanniee
thibaut sanniee

Reputation: 21

When you remove your EC2, this one is not immediately deleted by AWS. You have to wait several minutes before AWS delete the VM. Moreover, you can't create 2 VMs with the same instance id.

You should avoid to manually defined your own instance id. You can for example use tags to select your EC2 (you can have several VMs with the same tags)

example:

  ec2:
    instance_tags:
      tag1: "tag1"
      tag2: "tag2"
  ....

Then, you can select or delete this VM with the same tags

Upvotes: 1

Related Questions