我有一个包含两个独立主机的剧本,一个是'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
知道该怎么做吗?还有别的办法吗?
发布于 2022-04-08 11:30:35
在第一个剧本中,您可以使用一个创建虚拟主机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'] }}"
两部戏必须放在你发行的同一本剧本里.
发布于 2022-04-08 13:17:22
不需要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在第一次播放中声明,并分配给主机本地主机。要在另一个主机中使用该变量,需要字典https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html#information-about-ansible-magic-variables。但是,问题是变量test_var没有被“实例化”。这意味着该变量没有包含在主机中。让我们来测试一下
- 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时,这个问题就会消失--额外的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
https://stackoverflow.com/questions/71795614
复制相似问题