Ansible 在剧本中使用条件根据IP地址执行

Ansible 在剧本中使用条件根据IP地址执行,ansible,ansible-inventory,ansible-facts,Ansible,Ansible Inventory,Ansible Facts,我必须在AWS中的40台计算机上更改windows计算机名。我尝试使用收集事实来设置一个条件,使其仅在ip匹配时执行。但出于某种原因,它没有把它捡起来。到目前为止,我对这个问题的解决方案(效率很低)是让每个ip都有一个单独的主机组。我知道必须有更好的方法来实现这一点,任何输入都将不胜感激 这就是我的工作原理 --- - hosts: windows_machine1 gather_facts: yes tasks: - name: Change the hostname

我必须在AWS中的40台计算机上更改windows计算机名。我尝试使用收集事实来设置一个条件,使其仅在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创建条件吗?

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

您不需要指定
ansible\u 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

您不能使用带有对象的列表作为列表项吗,例如:
host\u mapping:-{old:127.0.0.1,new:newName1}
等等?我尝试了您给出的第一个示例,结果失败。致命:[10.x.x.1]:失败!=>{“msg”:“条件检查'ansible\u default\u ipv4.address=='10.x.x.1'失败。错误为:计算条件时出错(ansible\u default\u ipv4.address=='10.x.x.1')。啊,对不起。我应该在发布之前检查一下。Ansible对原始字符串比较有点挑剔,要求将整个表达式用双引号括起来,而对于其他比较则没有。编辑并测试了我的答案。另外,只是为了确认,您在运行的代码中使用的是实际的IP地址,而不是“10.x.x.1”?