ansible - 如何在 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"}
这样做的正确方法是什么?
解决方案
只需使用变量。例如,给定库存
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 ...
推荐阅读
- node.js - Firefox 无法建立与 socket.io 的连接
- ruby-on-rails - Rails 凭据:编辑和未初始化的常量 Bundler (NameError)
- asp.net - ASP.NET OWIN Azure 广告登录在 iPhone (Safari) 浏览器上不起作用。在其他浏览器上很好
- angular - 无法绑定到“matMenuTriggerFor”,因为它不是“按钮”的已知属性
- javascript - 保证promise运行顺序,Word API JS
- php - How to avoid repeating similar sections of MySQL query code in PHP?
- javascript - How is this fat arrow operating in this code?
- spring-cloud - 带有 Eureka 的 Spring Cloud Gateway 得到 504(网关超时)
- powershell - 使用“Invoke-WebRequest”下载多个文件
- python - Trouble getting the position of an element while looping through a list (Python)