我将角色设置为事实
- 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 }}"
我正在获取未定义的变量。如何使其在全球范围内可见? 当然,如果我在同一主机上运行调试,它会完美地工作。
答案 0 :(得分:2)
如果您的目标只是从另一台主机上访问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