访问为其他主机注册的变量

问题描述 投票:0回答:1

情况是我在一个剧本中注册了一个变量,主要在host1(例如)中运行,并且为host2注册了IP

- name: Reading vdu-GUI IPs and storing them in variables
  hosts: host2
  remote_user: root
  tasks:
    - debug: var=ansible_all_ipv4_addresses
      register: host2_ip
    - debug: var=host2_ip

现在我正在尝试将密钥从host3交换到host2:

- name: Exchange Keys between servers
  hosts: host3
  remote_user: root
  tasks:
   - name: Check for presence of key
     stat:
       path: ~/.ssh/id_rsa.pub
     register: keyStat

- name: Create key on ControlServer if it does not exist already
  shell: "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N '' -q"
  when: keyStat.stat.exists != True

- name: Copy the file from master to the destination vms
  shell: "sshpass -p Passw0rd ssh-copy-id -i /root/.ssh/id_rsa -o 'StrictHostKeyChecking=no' root@{{ host2_ip }}"

这给了我未定义的变量错误:

TASK [Copy the file from master to the destination vms] task path: 
/tmp/ansible-execution-6RtsPw/playbook/ansible/test.yml:213
fatal: [8c0b69ef-dae2-4ebf-8b5a-2c522b677a31]: FAILED! => {
"failed": true,
"msg": "the field 'args' has an invalid value, which appears to include 
a variable that is undefined. The error was: 'host2_ip_addr' is 
undefined\n\nThe error appears to have been in '/tmp/ansible-execution- 
6RtsPw/playbook/ansible/test.yml': line 213, column 6, but may\nbe 
elsewhere in the file depending on the exact syntax problem.\n\nThe 
offending line appears to be:\n\n\n   - name: Copy the file from master 
to the destination vms\n     ^ here\n"
}
ansible
1个回答
0
投票

hostvars可以用来

访问另一个主机的变量,包括已收集的有关该主机的事实。您可以在剧本中的任何位置访问主机变量......

例如下面的剧本

- hosts: test_02
  gather_facts: yes
  tasks:
    - debug:
        var: ansible_all_ipv4_addresses

- hosts: test_03
  gather_facts: yes
  tasks:
    - debug:
        var: hostvars['test_02'].ansible_all_ipv4_addresses

给(删节):

PLAY [test_02]
TASK [debug]
ok: [test_02] => {
"ansible_all_ipv4_addresses": [
    "10.1.0.52"
    ]
}
PLAY [test_03]
TASK [debug]
ok: [test_03] => {
"hostvars['test_02'].ansible_all_ipv4_addresses": [
    "10.1.0.52"
    ]
 }
© www.soinside.com 2019 - 2024. All rights reserved.