Search code examples
amazon-web-servicesansibleansible-2.xelastic-ip

How to release an AWS elastic IP with ansible?


I am following the ansible documentation here: https://docs.ansible.com/ansible/latest/modules/ec2_eip_module.html in order to provision an ec2 instance with a new elastic IP. The parameter release_on_disassociation is set to yes but after the disassociation the elastic IP is not released.

First, I created the ec2 with the elastic IP:

- name: provision new instances with ec2
  ec2:
    keypair: mykey
    instance_type: c1.medium
    image: ami-40603AD1
    wait: yes
    group: webserver
    count: 3
  register: ec2

- name: associate new elastic IPs with each of the instances
  ec2_eip:
    device_id: "{{ item }}"
    release_on_disassociation: yes
  loop: "{{ ec2.instance_ids }}"

Afterwards, the elastic IP is disassociated:

- name: Gather EC2 facts
  ec2_instance_facts:
    region: "{{ region }}"
    filters:
      "tag:Type": "{{ server_type }}"
  register: ec2
- name: disassociate an elastic IP with a device
  ec2_eip:
    device_id: '{{ item.instance_id }}'
    ip: '{{ item.public_ip_address }}'
    state: absent
  when: item.public_ip_address is defined
  with_items: "{{ ec2.instances }}"

ansible --version

ansible 2.8.4

Python Version is 3.7.4


Solution

  • I thought perhaps release_on_disassociation: was an AWS feature, but even if it is then it doesn't matter for your case because the module does not examine that parameter during state: present actions. Rather it only consults that parameter during state: absent

    So I believe you need to move that parameter from the top ec2_eip down to the bottom one:

    - name: disassociate an elastic IP with a device
      ec2_eip:
        device_id: '{{ item.instance_id }}'
        ip: '{{ item.public_ip_address }}'
        release_on_disassociation: yes
        state: absent
      when: item.public_ip_address is defined
      with_items: "{{ ec2.instances }}"