首页 > 解决方案 > Ansible 对循环中的项目执行 when 语句

问题描述

我正在尝试根据变量中的数字创建许多 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}}

(请不要介意缩进 - 它有效,但可能是复制/粘贴问题)在“何时”行我收到警告,如果我尝试使用它当然会失败,reg_eip_server_1.public_ip因为它不存在

以下是问题

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

标签: amazon-ec2ansibleeip

解决方案


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


推荐阅读