在 Ansible playbook 中访问库存主机变量 [英] Accessing inventory host variable in Ansible playbook

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

问题描述

在 Ansible 2.1 中,我有一个角色被需要访问主机文件变量的剧本调用.关于如何访问它的任何想法?

In Ansible 2.1, I have a role being called by a playbook that needs access to a host file variable. Any thoughts on how to access it?

我正在尝试访问以下清单 host 文件的 test1 部分中的 ansible_ssh_host:

I am trying to access the ansible_ssh_host in the test1 section of the following inventory host file:

[test1]
test-1 ansible_ssh_host=abc.def.ghi.jkl ansible_ssh_port=1212

[test2]
test2-1 ansible_ssh_host=abc.def.ghi.mno ansible_ssh_port=1212

[test3]
test3-1 ansible_ssh_host=abc.def.ghi.pqr ansible_ssh_port=1212
test3-2 ansible_ssh_host=abc.def.ghi.stu ansible_ssh_port=1212

[all:children]
test1
test2
test3

我尝试通过以下方式访问角色:

I have tried accessing the role in the following fashions:

{{ hostvars.ansible_ssh_host }} 

{{ hostvars.test1.ansible_ssh_host }}

我收到此错误:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "'ansible.vars.hostvars.HostVars object' has no attribute 'ansible'"}

推荐答案

您在 hostvars 的正确轨道上.
这个魔法变量被使用访问有关其他主机的信息.

You are on the right track about hostvars.
This magic variable is used to access information about other hosts.

hostvars 是一个以库存主机名作为键的哈希.
要访问每个主机的字段,请使用 hostvars['test-1']hostvars['test2-1']

hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'], hostvars['test2-1'], etc.

ansible_ssh_host已弃用 支持 ansible_host 自 2.0 起.
所以你应该首先删除_ssh"从清单主机参数(即成为ansible_user"、ansible_host"和ansible_port"),然后在你的角色中调用它:

ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:

{{ hostvars['your_host_group'].ansible_host }}

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

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