如何设置在 Ansible 角色的所有主机上可见的事实

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

我正在为角色设定事实:

- name: Check if manager already configured
  shell: >
    docker info | perl -ne 'print "$1" if /Swarm: (\w+)/'
  register: swarm_status

- name: Init cluster
  shell: >-
    docker swarm init
    --advertise-addr "{{ ansible_default_ipv4.address }}"
  when: "'active' not in swarm_status.stdout_lines"

- name: Get worker token
  shell: docker swarm join-token -q worker
  register: worker_token_result

- set_fact:
    worker_token: "{{ worker_token_result.stdout  }}"

然后我想访问另一台主机上的worker_token。这是我的主要剧本,事实是在 swarm-master 角色中定义的

- hosts: swarm_cluster
  become: yes
  roles:
    - docker

- hosts: swarm_cluster:&manager
  become: yes
  roles:
    - swarm-master

- hosts: swarm_cluster:&node
  become: yes
  tasks:
    - debug:
        msg: "{{ worker_token }}"

我得到了未定义的变量。如何使其在全球范围内可见? 当然,如果我在同一主机上运行调试,它会完美地工作。

ansible
1个回答
3
投票

如果您的目标只是从另一台主机访问

worker_token
,您可以使用
hostvars
变量并迭代您定义变量的组,如下所示:

- hosts: swarm_cluster:&node
  tasks:
  - debug:
      msg: "{{ hostvars[item]['worker_token'] }}"
    with_items: "{{ groups['manager'] }}"

如果您的目标是全局定义变量,您可以添加一个步骤来在所有主机上定义变量,如下所示:

- hosts: all
  tasks:
  - set_fact:
      worker_token_global: "{{ hostvars[item]['worker_token'] }}"
    with_items: "{{ groups['manager'] }}"

- hosts: swarm_cluster:&node
  tasks:
  - debug:
      var: worker_token_global
© www.soinside.com 2019 - 2024. All rights reserved.