Ansible:将主机 1 的角色中生成的变量传递给主机 2 的另一个角色

Ansible:将主机 1 的角色中生成的变量传递给主机 2 的另一个角色

我正在尝试使用在 host1 的角色中生成的变量,并在另一个角色中将其用于 host2。

这是使用的总体布局:

|   # Group variables
+-- group_vars
|   +-- all  # variables set on all hosts 

|   # Collection of playbooks divided by *role*
+-- roles
   - role-nfs.yml   # playbook for role `role-nfs`
|  - role-app.yml  # playbook for role `role-app`
|  - role-app      # directory containing stuff used by `role-app`
|  - role-nfs       # directory containing stuff used by `role-nfs`   
|
+-- site.yml
|   # This is the main playbook.

nfs为host1 生成变量:role-nfs/task/main.yml

- name: Export nfs_server_ip to a host-fact type variable
  set_fact:
    nfs_server_ip: "{{ ansible_default_ipv4.address }}"
    cacheable: True

然后在剧本app中被host2抓取:role-app.yml


- name: Deploy app
  tags:
    - app
  hosts: app
  roles:
    - role: role-app
      nfs: True
      nfs_ip: "{{hostvars['nfs_server_ip']}}"

并传递给role-app/task/main.yml。但调试信息告诉我我得到了一个空字符串:

- debug:
    msg: "This is nfs_ip: {{nfs_ip}} "

出去:

TASK [app : debug] *********************************************************************************
task path: /home/ubuntu/playbooks/roles/role-app/tasks/main.yml:26
ok: [app001] => {
"msg": "This is nfs_ip:  "
}

我不太清楚我做错了什么。有什么帮助吗?

编辑

因此我设法得到了我需要的东西,即nfs_ip通过这样的方式:

      group_name_nfs: "{{hostvars[inventory_hostname]['groups']['nfs-server'][0]}}"
      nfs_ip: "{{hostvars[inventory_hostname]['cluster']['nodes'][group_name_nfs]['ips'][0]}}"

可能有更好的方法可以做到这一点......

答案1

您可以尝试使用内存清单

- name: Add nfs_server_ip to in-memory inventory.
  add_host:
    hostname: nfs-server
    public_ip: {{ ansible_default_ipv4.address }}

然后使用类似下面的方法

- name: Deploy app
  tags:
    - app
  hosts: app
  roles:
    - role: role-app
      nfs: True
      nfs_ip: "{{ hostvars['nfs-server']['public_ip'] }}"

相关内容