首页 > 解决方案 > Ansible 在任务中创建可重用的动态环境变量

问题描述

是否可以在 Ansible 中的任务执行期间设置可重用的动态环境变量?像这样:

---
- name: grab secret from unexposed port 1234
  raw: SECRET=$(curl --silent http://127.0.0.1:1234/secret)
- name: use secret for something
  raw: echo $SECRET

标签: bashansible

解决方案


Ansible 正在为每个单独的命令执行一个子 shell。您不能从子shell 在父进程中设置变量。

不要使用raw. 如果您绝对必须使用raw,请尝试重新考虑。如果你仍然必须这样做,它仍然会创建一个子shell,并且不会做你想做的事。

您需要将值移动到 ansible 父进程。

- command: curl --silent http://127.0.0.1:1234/secret
  register: tmpvar

# pull just the bit you want - tmpvar has lots of extraneous stuff
- set_fact:
    SECRET: "{{ tmpvar.stdout }}"

- shell: |
    SECRET="{{ SECRET }}"
    echo $SECRET

推荐阅读