问题描述
我有一个在不同主机上运行不同角色的剧本.是否可以将变量从在一台主机上运行的一个角色传递到在同一剧本运行中运行的另一台主机上的另一个角色?或任何解决方法?
I have a playbook that runs different roles on different hosts.Is it possible to pass a variable from one role running on one host to another role on another host running within the same playbook run? Or any workaround ?
playbook
host1
role1
here I get some variables: var1 var2 ...etc
host2
role2
here I need to use var1 var2 ... etc from the above host/role
role1 中设置变量 db
的任务如下所示:
The task in role1 that sets teh variable db
looks like this:
- shell: cd /ACE/conf && grep ^db.url local1.properties | awk -F/ '{print $4}' | awk -F? '{print $1}'
register: db
更新:在第一台主机上,值是动态的,就像一个总是更新的配置文件.在我使用 role1 将值存储在 host1 上的变量中之后,我移动到 host2,运行 role2 并使用 host1 存储的变量中的这些值执行操作.
UPDATE: On the first host the values are dynamic, it's like a configuration file that is always updated. After I store the values in variables on host1 with the role1 I then move to the host2, run the role2 and do stuff with those values from variables stored by host1.
我尝试使用主机变量:
{{ hostvars.LBL.db.stdout }}
{{ hostvars['LBL']['db'] }}
{{ hostvars['LBL']['db']['stdout'] }}
我得到错误:
in get_variables raise Exception("host not found: %s" % hostname) Exception: host not found: LBL
LBL 存在于主机中,因为我在其上运行第一个角色
LBL exists in hosts as on it I run the first role
我在一台主机上设置了一个变量,我希望该变量可用于另一台主机.所有这一切都在一个剧本中.可以吗?
I set a variable on one host and I want that variable to be available to the other host. All this within a single playbook. Can it be done ?
hostvars 不能像这样使用它:
hostvars is not working using it like this:
---
- name: test hostvars host1
hosts: LBL
tasks:
- command: "ls /bin"
register: ls_out
- name: test hostvars host2
hosts: LM
tasks:
- debug:
var: "{{ hostvars['LBL']['ls_out']['stdout'] }}"
错误:
fatal: [10.104.148.138] => host not found: LBL
/etc/ansible/hosts
/etc/ansible/hosts
[root@NS1 ansible]# cat /etc/ansible/hosts
[LBL]
10.104.148.136
[LM]
10.104.148.138
推荐答案
问题出在您的库存中.
这条消息:
fatal: [10.104.148.138] => host not found: LBL
是因为 LBL
是一个组而不是一个主机.LBL
组中有一个主机:10.104.148.136
is because LBL
is a group and not a host. Group LBL
has one host in it: 10.104.148.136
执行以下操作之一:
1.将您的库存 (/etc/ansible/hosts
) 更改为:
1. Change your inventory (/etc/ansible/hosts
) to:
LBL ansible_ssh_host=10.104.148.136
LM ansible_ssh_host=10.104.148.138
2.或者如果你真的知道你在做什么并且 LBL
是一个组并且你想保持这种方式然后访问变量:
2. or if you really know what you're doing and LBL
is a group and you wanna keep it that way then access the variable with:
{{ hostvars['10.104.148.136']['db']['stdout'] }}
再说一次,LBL 是一个组而不是一个主机.更多信息.
Again LBL is a group not a host. More info.
这篇关于将 Ansible 变量从一个角色(在一台主机上运行)传递到在同一剧本中的另一台主机上运行的另一个角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!