Ansible 在循环中对项目执行 when 语句

Ansible do a when statement on an item in a loop

我正在尝试根据变量中的数字创建多个 AWS 弹性 IP - 到目前为止一切正常。但是我需要检查这个 EIP 是否已经存在于我从文件加载的一组变量中。如果 EIP 存在我想跳过它的创建, 例如:

- 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}}

(请不要介意缩进 - 它有效,但这里可能是 copy/paste 问题) 在 "when" 行我收到警告,当然如果我尝试使用 reg_eip_server_1.public_ip 它会失败,因为它不存在

这里是问题:

  1. 可以吗?
  2. 如何获取项目的 public IP 并在下一步中使用它?
  3. 当我使用这种计数时,如何使用条件来跳过项目?

我设法弄明白了。 使用项目本身,警告只是一个警告,但它确实有效,所以如果文件中的变量确实存在,它将忽略循环实例并继续前进。 所以: 1. 是的,可能。 2. 从结果项中取出public IP(以结果项编号为索引)。 3. 尽管警告本身警告仍然有效。