Ansible:在 v2.3 中动态查找变量

Ansible: Lookup variables dynamically in v2.3

我有一组变量和一个任务如下。我的目的是根据用户选择的 URL 动态地进行健康检查。

vars:
  current_hostname: "{{ ansible_hostname }}"
  hc_url1: "https://blah1.com/healthcheck"
  hc_url2: "https://blah2.com/healthcheck"

tasks:
- name: Notification Msg For Healthcheck
  shell: "echo 'Performing healthcheck at the URL {{ lookup('vars', component) }} on host {{ current_hostname }}'"

运行 Ansible 2.3 中的剧本

ansible-playbook ansible_playbook.yml -i inventory -k -v --extra-vars "component=hc_url1"

错误

fatal: [hostname]: FAILED! => {"failed": true, "msg": "lookup plugin (vars) not found"}

我知道这是因为查找插件 "var" 是在 Ansible v2.5 中引入的。有没有办法在 Ansible 2.3 中做到这一点?我想得到{{component}}的值,然后是{{hc_url1}}

的值

PS - 由于组织限制,升级到 2.5 不是一个选项

或者,也许您可​​以使用字典来做到这一点。

例如,

vars:
  current_hostname: "{{ ansible_hostname }}"
  urls:
    hc_url1: "https://blah1.com/healthcheck"
    hc_url2: "https://blah2.com/healthcheck"

tasks:
- name: Notification Msg For Healthcheck
  shell: "echo 'Performing healthcheck at the URL {{ urls[component] }} on host {{ current_hostname }}'"

这样,用户提供的值 component 将作为字典中的关键字查找。