Ansible任务间复用环境变量:如何正确注册脚本输出的BAZ变量?
问题:如何在Ansible中正确注册bash脚本导出的BAZ变量?
我在Ansible剧本中运行若干任务,其中一个任务执行bash脚本并注册其输出,但实际注册的是curl命令的输出而非脚本里导出的BAZ变量。尝试过用单独任务读取BAZ,但每个任务是独立shell,无法访问之前的变量。
相关代码如下:
playbook.yml
- name: Compare FOO to BAZ shell: . script.sh register: output - name: Print the generated output debug: msg: "The output is {{ output }}" - include: Run if BAZ is true when: output.stdout == "true"
script.sh
#!/bin/bash FOO=$(curl example.com/file.txt) BAR=$(cat file2.txt) if [ $FOO == $BAR ]; then export BAZ=true else export BAZ=false fi
解决方案
方法一:修改脚本,直接输出BAZ的值
Ansible的shell模块注册的是脚本的标准输出内容,所以让脚本最后直接打印BAZ的值,就能被register捕获。
修改后的script.sh:
#!/bin/bash FOO=$(curl example.com/file.txt) BAR=$(cat file2.txt) # 注意给变量加引号,避免空值或含空格的内容导致语法错误 if [ "$FOO" == "$BAR" ]; then BAZ=true else BAZ=false fi # 关键:最后输出BAZ的值 echo $BAZ
然后修改playbook中的任务(不需要再source脚本,直接运行即可):
- name: Run script and get BAZ value shell: ./script.sh register: baz_output - name: Print BAZ value debug: msg: "BAZ is {{ baz_output.stdout }}" - include: Run if BAZ is true when: baz_output.stdout == "true"
方法二:在同一个shell任务中完成脚本执行+变量输出
如果不想修改原脚本,可以把source脚本和输出BAZ的命令放在同一个shell任务里——同一个任务会在同一个shell进程中执行,所以能访问到脚本导出的变量:
- name: Get BAZ value from script shell: . ./script.sh && echo $BAZ register: baz_output - name: Print BAZ value debug: msg: "BAZ is {{ baz_output.stdout }}" - include: Run if BAZ is true when: baz_output.stdout == "true"
方法三:把逻辑迁移到Ansible中(推荐)
没必要依赖外部bash脚本,直接用Ansible的模块实现相同逻辑,更易维护且符合Ansible的最佳实践:
- name: Fetch FOO from remote URL uri: url: http://example.com/file.txt return_content: yes register: foo_result - name: Read BAR from local file slurp: path: ./file2.txt register: bar_result - set_fact: # slurp返回的内容是base64编码,需要解码并去除首尾空白 bar_content: "{{ bar_result.content | b64decode | trim }}" foo_content: "{{ foo_result.content | trim }}" - name: Set BAZ variable based on comparison set_fact: baz: "{{ 'true' if foo_content == bar_content else 'false' }}" - name: Print BAZ value debug: msg: "BAZ is {{ baz }}" - include: Run if BAZ is true when: baz == "true"
内容的提问来源于stack exchange,提问作者rippie
相关产品推荐
相关产品推荐

