'need to delete unused elastic IP from aws account with ansible playbook
I have written a playbook as below:
tasks:
- name: List of all EIP
ec2_eip_info:
region: "{{ region }}"
register: list_of_eip
- name: initiate EIP list
set_fact:
eip_list: []
- name: List of all unused EIP
set_fact:
eip_list: "{{ list_of_eip.addresses | json_query(jmesquery) }}"
vars:
jmesquery: "[?instance_id== None].allocation_id"
- name: Release IP
command: aws ec2 release-address --allocation-id {{ eip_list }} --region {{ region }}
vars:
jmesquery: "[?instance_id== None].allocation_id"
In the output, I am getting an error in task Release IP:
aws ec2 release-address --allocation-id [u'eipalloc-xxxxxxxxxxxxxxx'] --region us-east-1", allocation id not found.
I need to pass the allocation id as eipalloc-xxxxxxxxxxxxxxx and I don't know how to fix the above. Also, can someone point me in the right direction on how to loop if I have multiple EIPs?
Solution 1:[1]
You are constructing a list. Your command expects a single string element. You just need to pass that single element. Since you expect to have multiple elements in that list anyway, the obvious solution is to loop over your list so you can manage one or more elements the exact same way (actually 0 as well if the list is empty in which case no loop iteration will take place).
Moreover, there is no need to complexify your playbook with jmespath (great for complex json queries but we are not in that case) nor with setting facts.
The following should meet your requirement. I don't have an example of your data and no access to an aws account to try it myself so it is untested and you may have to tune the filter in rejectattr (and maybe switch to selectattr if easier) depending on your exact input data. See data manipulation in ansible documentation, rejectattr / selectattr in jinja2 documentation.
Note: for you next question consider crafting a correct minimal, complete, verifiable example
- name: List of all EIP
ec2_eip_info:
region: "{{ region }}"
register: list_of_eip
- name: Release IP
command: aws ec2 release-address --allocation-id {{ item }} --region {{ region }}
loop: "{{ list_of_eip.addresses | rejectattr('instance_id') | map(attribute='allocation_id') }}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
