在Ansible中访问任务中的主机变量 [英] Accessing host variables in tasks in Ansible

查看:217
本文介绍了在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]中执行上述角色.我希望任务-名称:启动服务 [test:children] 中定义的任何主机组中运行.要检查是否已向 test 组添加了变量 clean_images = true 来执行条件检查

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

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

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'

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

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 个变量将永远不存在.但是,属于组的所有主机都将定义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中访问任务中的主机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆