如何在 ansible 中的不同角色之间使用变量



我的剧本结构如下所示:

- hosts: all
name: all
roles:
- roles1
- roles2

tasksroles1,我定义了这样一个变量

---
# tasks for roles1
- name: Get the zookeeper image tag # rel3.0
run_once: true
shell: echo '{{item.split(":")[-1]}}' # Here can get the string rel3.0 normally
with_items: "{{ret.stdout.split('n')}}"
when: "'zookeeper' in item"
register: zk_tag

ret.stdout:

Loaded image: test/old/kafka:latest
Loaded image: test/new/mysql:v5.7
Loaded image: test/old/zookeeper:rel3.0

tasksroles2,我想使用zk_tag变量

- name: Test if the variable zk_tag can be used in roles2
debug: var={{ zk_tag.stdout }}

错误:

The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'

我想我遇到了以下两个问题:

  1. 向寄存器注册变量时,添加条件时,此变量不能在所有组中使用。如何解决这个问题?如何使此变量对所有组可用?

  2. 是我的标题,如何在 ansible 中的不同角色之间使用变量?

您很可能正在为新主机开始新的剧本。这意味着所有以前收集的变量都将丢失。

您可以做的是使用 add_host 模块将 var 传递给另一个主机。

- name: Pass variable from this play to the other host in the same play
add_host:
name: hostname2
var_in_play_2: "{{ var_in_play_1 }}"

---编辑---

有点不清楚。如果您希望剧中的每个主持人都可用,为什么首先要使用when语句? 您可能希望使用group_vars/all.yml文件来放置变量。

此外,使用add_host应该是我阅读的方式。你能在网站上发布你的剧本和剧本的结果吗,例如 pastebin?

如果由于when 条件而未定义 var,则应使用默认值强制在使用 var 时对其进行定义。当你使用它时,使用调试模块进行测试,而不是在 shell 中回显某些内容

- name: Debug my var
debug:
msg: "{{ docker_exists | default(false) }}"

最新更新