在Ansible中访问任务中的主机变量

时间:2018-12-11 06:29:57

标签: ansible ansible-inventory

我有一个主机组,该主机组具有如下所示的主机变量

[test:children]
test1
test2
test3

[test:vars]
clean_images=true

我的任务定义如下,

- name: clean docker images
  template:
    dest: "/etc/systemd/system/{{ item.name }}"
  with_items:
  - { name: "{{ service_name }}.service" }



- name: start service
  systemd:
    name: "{{ service_name }}.service"
    state: started
    enabled: yes
  when: hostvars['test'].clean_images is defined

这是一个简单的任务,其中我根据主机清理docker映像。我有一本剧本,可以在另一组主机组[test_services]中执行上述角色。我希望任务-名称:启动服务 [test:children] 中定义的任何主机组中运行。要检查是否已将变量 clean_images = true 添加到 test 组以执行条件检查

但是我上面包含的何时语句给我一个错误

fatal: [xx.xx.xx.xx]: FAILED! => {"msg": "The conditional check 'hostvars['test'].clean_images is defined' failed. The error was: error while evaluating conditional (hostvars['test'].clean_images is defined): \"hostvars['test']\" is undefined\n\nThe error appears to have been in 'main.yml'

我在使用何时建立此条件语句时遇到问题,任何帮助都会很棒。

1 个答案:

答案 0 :(得分:2)

when: hostvars['test'].clean_images is defined

应该只是:

when: clean_images is defined and clean_images

因为没有名为test的主机,因此test host vars将永远不存在。然而,属于组的所有主机都将定义test