首页 > 解决方案 > 如何在 Ansible 中动态使用自定义事实来评估条件语句

问题描述

我正在尝试评估情况

hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']

host_variableexternal_ip上设置。我已经设置了自定义事实并尝试评估这种情况ipify_ip

when: hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']

我也尝试过这个选项,但在那里也失败了

when: hostvars[inventory_hostname].external_ip == {{ ipify_ip }}

这是完整的剧本文件

- name: Get public ip for the host
  ipify_facts:
   api_url: https://api.ipify.org/
   timeout: 20
  tags: always

- name: Set fact
  set_fact:
   ipify_ip: "{{ ipify_public_ip }}"
  tags: always

- name: ipify_ip External IP
  debug:
   var: ipify_ip
  tags: always

- name: is extrnal_ip in hostvars is same with ipify_ip
  debug:
   var=hostvars[inventory_hostname].external_ip
  when: hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']
  tags: always

错误

fatal: [localhost]: FAILED! => {"msg": "The conditional check 'hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']' failed. The error was: error while evaluating conditional (hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']): 'dict object' has no attribute 'ipify_ip'\n\nThe error appears to be in '/home/anish/playbook/prereqs.yml': line 29, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: extrnal_ip on hostvars\n ^ here\n"}

这样做的正确方法是什么?

标签: ansible

解决方案


只需使用变量。例如,给定库存

shell> cat hosts
host01 external_ip=1.2.3.4

和剧本

shell> cat playbook.yml
- hosts: host01
  tasks:
    - set_fact:
        ipify_ip: 1.2.3.4
    - debug:
        var: ipify_ip
    - debug:
        var: external_ip
    - debug:
        msg: "{{ external_ip }} is equal to {{ ipify_ip }}"
      when:  external_ip == ipify_ip

shell> ansible-playbook -i hosts playbook.yml

PLAY [host01] *******************************

TASK [set_fact] *****************************
ok: [host01]

TASK [debug] ********************************
ok: [host01] =>
  ipify_ip: 1.2.3.4

TASK [debug] ********************************
ok: [host01] =>
  external_ip: 1.2.3.4

TASK [debug] ********************************
ok: [host01] =>
  msg: 1.2.3.4 is equal to 1.2.3.4

PLAY RECAP **********************************
host01: ok=4 changed=0 unreachable=0 failed=0 ...

推荐阅读