中访问任务中的宿主变量

中访问任务中的宿主变量

本文介绍了在 Ansible 中访问任务中的宿主变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主机组,其中包含如下所示的主机变量

I have a host group which have host variables as shown below

[test:children]
test1
test2
test3

[test:vars]
clean_images=true

我在一个角色中定义了一个任务,如下所示

I have a tasks defined in a role as shown below

- 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] 中执行上述角色.我希望任务 - name: start service 在遇到 [test:children] 中定义的任何主机组时运行.检查我是否已将变量 clean_images=true 添加到 test 组以执行条件检查

This is a simple tasks, where I clean docker images depending on the host. I have a playbook which executes this above role in a different set of host group [test_services]. I want the task - name: start service to run if it come across any of the host groups defined in [test:children]. To check that I have added a variable clean_images=true to the test group to execute a condition check

但是我上面包含的 when 语句给了我一个错误

But the when statement I have included above gives me an error

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'

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

I have a problem in building up this conditional statement using when, any help would be great.

推荐答案

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

应该只是:

when: clean_images is defined and clean_images

因为没有名为 test 的主机,因此 host test 的变量永远不会存在.但是,属于test 组的所有主机都将定义clean_images

because there is no host named test, and thus hostvars of test will never exist. All hosts that belong to the test group will have clean_images defined, however

这篇关于在 Ansible 中访问任务中的宿主变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:37