Ansible-从一个主机获取一些变量值,并在另一个主机中使用它们



我有一个包含两个独立主机的剧本,一个是"localhost",另一个是‘xyz’。

- hosts: localhost
connection: local
gather_facts: False
vars_prompt: 
- name: "value" 
prompt: "Enter your value" 
private: yes
roles:
- a
###
- name: Define xyz
hosts: xyz
roles:
- a
- b

当我们运行上面的剧本时,然后在"localhost"var_promot中从用户那里获取值,然后,我想在shell命令中的"xyz"主机角色中使用这些值。

目前,在"a"角色内部,我有这种类型的代码,但它给了我一个错误。

- name: echo
shell: " echo {{ value | urlencode }}"
register: sout

你知道怎么做吗?

不需要vars_prompt角色来重现问题。请改用简单的vars任务。例如

- hosts: localhost
vars:
test_var: foo
tasks:
- debug:
var: test_var
- hosts: xyz
vars:
test_var: "{{ hostvars.localhost.test_var }}"
tasks:
- debug:
var: test_var

给出(仅调试输出(

ok: [localhost] => 
test_var: foo
ok: [xyz] => 
test_var: VARIABLE IS NOT DEFINED!

变量test_var在第一次播放中声明,并分配给主机localhost。要在另一个主机中使用该变量,需要字典hostvars。但是,问题是变量test_var不是";实例化";。这意味着该变量未包含在hostvars中。让我们测试一下

- hosts: localhost
vars:
test_var: foo
tasks:
- debug:
var: test_var
- debug:
var: hostvars.localhost.test_var
- hosts: xyz
gather_facts: false
tasks:
- debug:
var: hostvars.localhost.test_var

给出(仅调试输出(

ok: [localhost] => 
test_var: foo
ok: [localhost] => 
hostvars.localhost.test_var: VARIABLE IS NOT DEFINED!
ok: [xyz] => 
hostvars.localhost.test_var: VARIABLE IS NOT DEFINED!

-e,--extra vars使用时,问题将消失

shell> ansible-playbook playbook.yml -e test_var=bar

给出(仅调试输出(

ok: [localhost] => 
test_var: bar
ok: [localhost] => 
hostvars.localhost.test_var: bar
ok: [xyz] => 
hostvars.localhost.test_var: bar

为了解决其他变量源的问题;实例化";第一个剧本中的变量。使用set_fact

- hosts: localhost
vars:
test_var: foo
tasks:
- debug:
var: test_var
- debug:
var: hostvars.localhost.test_var
- set_fact:
test_var: "{{ test_var }}"
- debug:
var: hostvars.localhost.test_var
- hosts: xyz
vars:
test_var: "{{ hostvars.localhost.test_var }}"
tasks:
- debug:
var: test_var

给出(仅调试输出(

ok: [localhost] => 
test_var: foo
ok: [localhost] => 
hostvars.localhost.test_var: VARIABLE IS NOT DEFINED!
ok: [localhost] => 
hostvars.localhost.test_var: foo
ok: [xyz] => 
test_var: foo

测试其他来源,例如

shell> cat host_vars/localhost 
test_var: foo
- hosts: localhost
tasks:
- debug:
var: test_var
- set_fact:
test_var: "{{ test_var }}"
- hosts: xyz
vars:
test_var: "{{ hostvars.localhost.test_var }}"
tasks:
- debug:
var: test_var

给出(仅调试输出(

ok: [localhost] => 
test_var: foo
ok: [xyz] => 
test_var: foo

在第一个剧本中,您可以使用一个创建虚拟主机variable_holder的任务,并使用一个共享的var:(使用模块add_host(

- name: add variables to dummy host
add_host:
name: "variable_holder"
shared_variable:  "{{ value }}"

在第二场比赛中,你只记得var共享的

- name: Define xyz
hosts: xyz
vars:
value: "{{ hostvars['variable_holder']['shared_variable'] }}"

这两个剧本必须在你推出的剧本中。。。。

相关内容

最新更新