ali*_*der 36 ansible ansible-playbook ansible-2.x ansible-inventory
我正在使用ansible 2.1.我有以下清单主机文件和一个需要访问主机文件变量的播放器调用的角色.有关如何访问它的任何想法(目前收到错误):
主机文件
[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
Run Code Online (Sandbox Code Playgroud)
角色 我试图访问在以下时尚的作用:
{{ hostvars.ansible_ssh_host }}
Run Code Online (Sandbox Code Playgroud)
&&
{{ hostvars.test1.ansible_ssh_host }}
Run Code Online (Sandbox Code Playgroud)
我试图访问test1部分中的ansible_ssh_host.
错误
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'ansible.vars.hostvars.HostVars object' has no attribute 'ansible'"}
Run Code Online (Sandbox Code Playgroud)
Kon*_*rov 40
你正走在正确的轨道上hostvars.
此魔术变量用于访问有关其他主机的信息.
hostvars是库存主机名作为键的哈希.
要访问的每个主机,使用领域hostvars['test-1'],hostvars['test2-1']等等.
ansible_ssh_host被弃用有利于ansible_host自2.0.
所以你应该首先从库存主机参数中删除"_ssh"(即成为"ansible_user","ansible_host"和"ansible_port"),然后在你的角色中调用它:
{{ hostvars['your_host_group'].ansible_host }}
Run Code Online (Sandbox Code Playgroud)
Edu*_*omo 12
[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar
[host_group:vars]
custom_var=asdasdasd
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令访问主机组变量:
{{ hostvars['host_group'].custom_var }}
Run Code Online (Sandbox Code Playgroud)
如果您需要特定主机的特定值,您可以使用:
{{ hostvars[groups['host_group'][0]].node_name }}
Run Code Online (Sandbox Code Playgroud)
您应该能够直接使用变量名称
ansible_ssh_host
Run Code Online (Sandbox Code Playgroud)
或者你可以通过使用magic变量来完成hostvars,而不必逐字地指定主机 inventory_hostname
hostvars[inventory_hostname].ansible_ssh_host
Run Code Online (Sandbox Code Playgroud)
我也为此苦苦挣扎。我的具体设置是:您的host.ini(带有现代名称):
[test3]
test3-1 ansible_host=abc.def.ghi.pqr ansible_port=1212
test3-2 ansible_host=abc.def.ghi.stu ansible_port=1212
Run Code Online (Sandbox Code Playgroud)
加一个play fill_file.yml
---
- remote_user: ec2-user
hosts: test3
tasks:
- name: fill file
template:
src: file.j2
dest: filled_file.txt
Run Code Online (Sandbox Code Playgroud)
加一个模板 file.j2 ,比如
{% for host in groups['test3'] %}
{{ hostvars[host].ansible_host }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这对我有用,结果是
abc.def.ghi.pqr
abc.def.ghi.stu
Run Code Online (Sandbox Code Playgroud)
我必须承认这是ansible 2.7,而不是2.1。该模板是https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html中示例的变体。
接受的答案在我的设置中不起作用。有模板
{{ hostvars['test3'].ansible_host }}
Run Code Online (Sandbox Code Playgroud)
我的游戏失败,并显示 "AnsibleUndefinedVariable: \"hostvars['test3']\" is undefined" 。
备注:我尝试了一些变体,但失败了,偶尔出现“ansible.vars.hostvars.HostVars object has no element”;其中一些可能可以通过他们所说的来解释。在https://github.com/ansible/ansible/issues/13343#issuecomment-160992631
hostvars 模拟字典[...]。hostvars 也是延迟加载的
| 归档时间: |
|
| 查看次数: |
91307 次 |
| 最近记录: |