在Playbook中使用条件语句基于IP地址执行

时间:2019-01-17 16:09:25

标签: ansible ansible-inventory ansible-facts

我必须在AWS的40台计算机上更改Windows计算机名称。我尝试使用collect_facts设置仅在ip匹配时才执行的条件。但是由于某种原因,它无法接收。到目前为止,我对这个问题的解决方案(效率极低的问题是使每个ip上的单个主机组一个。我知道必须有一种更好的方法来处理此问题,任何输入都会受到赞赏。

这就是我的作品

---
- hosts: windows_machine1
  gather_facts: yes

  tasks:



    - name: Change the hostname to newname1
      win_hostname:
        name: newname1
      register: res

- hosts: windows_machine2
  tasks:

    - name: Change the hostname to newname2
      win_hostname:
        name: newname2
      register: res

    - name: Reboot
      win_reboot:
      when: res.reboot_required

我尝试了两种方法使条件条件都在运行时导致错误。

---
- hosts: windows_machine1
  gather_facts: yes

  tasks:



    - name: Change the hostname to newname1
      win_hostname:
        name: newname1
      register: res
      when: ansible_facts['ansible_all_ipv4_addresses'] == '10.x.x.x


    - name: Change the hostname to newname2
      win_hostname:
        name: newname2
      register: res
      when: ansible_facts['address'] == '10.x.x.x'

    - name: Reboot
      win_reboot:
      when: res.reboot_required

说条件检查失败将失败。因为我的条件不好。有人知道如何基于ip建立条件吗?

1 个答案:

答案 0 :(得分:1)

免责声明:我只在Linux主机上运行Ansible,所以我想Windows主机上可能会有所不同。

您无需指定ansible_facts,而是仅从特定的根事实开始。

在第一种情况下,您尝试获取的事实不会帮到您,因为它会返回系统上所有IP的列表。即使只有一个,它仍然会返回一个列表,您不能再简单地与它进行字符串比较。

这应该首先执行您想要的操作:

- name: Change the hostname to newname2
  win_hostname:
    name: newname2
  register: res
  when: "ansible_default_ipv4.address == '10.0.0.1'"

您是否打算复制此代码块,每个主机一个?如果是这样,请考虑设置一个变量以查找IP和新名称:

- hosts: all
  vars:
    ip_newname:
      10.0.0.1: newname1
      10.0.0.2: newname2
      10.0.0.3: newname3
  tasks:
    - name: Change the hostname
      win_hostname:
        name: "{{ ip_newname[ansible_default_ipv4.address] }}"
      register: res
      when: ansible_default_ipv4.address in ip_newname.keys()
    - name: Reboot
        win_reboot:
      when: res is defined and res.reboot_required