Search code examples
amazon-ec2ansibleeip

Ansible do a when statement on an item in a loop


I'm trying to create a number of AWS Elastic IPs based on the number in a variable - up to here it's all good. BUT I need to check if this EIP already exists in a set of variables I have loaded from a file. If the EIP exists I want to skip its creation, for example:

- set_fact: "number_of_ips=3
- name: load the local config file
  include_vars: profiles/{{ ec2_tag_environment }}/file_with_variables

- name: allocate a new elastic IP for server {{ item }} if not exists already
  ec2_eip:
    profile: "{{ boto_profile }}"
    region: "{{ ec2_region }}"
    state: present
  register: reg_eip_server_{{ item }}
  when: server_eip_{{ item }} is not defined
  with_sequence: start=1 end={{ number_of_ips}}

(please don't mind the indention - it works but might be a copy/paste issue here) On the "when" line I get a warning and of course it fails if i try to use reg_eip_server_1.public_ip since it doesn't exists

Here are the questions:

  1. Is it possible to do?
  2. How can I take the public IP of the item and use it in the next step?
  3. How can I use the condition to skip an item when I'm using this kind of count?

Solution

  • I managed to figure it out. Using the items themselves, the warning is only a warning but it actually works so if the variable from the file do exists it will ignore the instance of the loop and move on. So: 1. Yes, possible. 2. take the public IP from the item of the results (using the results item number as an index). 3. the warning still works although the warning itself.