linux - 为什么我不能使用 Ansible 捕获环境变量?
问题描述
我正在尝试获取并打印给定环境变量(ENV_VAR)的值:
$ cat ~/.bash_profile
ENV_VAR=Updated
ENV_VAR2=Updated
$ source ~/.bash_profile && echo $ENV_VAR
Updated
我可以通过终端成功检索它,但是通过使用下面的Ansible 剧本我得到一个错误:
# YAML
---
- hosts: all
vars:
env_var: "{{ lookup('env','ENV_VAR') }}"
tasks:
- name: Add/Update an environment variable to the remote user's shell
lineinfile:
dest: ~/.bash_profile
regexp: '^ENV_VAR='
line: "ENV_VAR=Updated2"
- name: Get the value of the environment variable we just added
shell: source ~/.bash_profile && echo $ENV_VAR
register: env_var_updated
- name: Print the value of the environment variable
debug:
msg: "var1: {{ env_var }} - var2 {{ env_var_updated.stdout }}"
执行:
$ ansible-playbook playbook.yml
PLAY [all] *********************************************************************************************************
TASK [Gathering Facts] *********************************************************************************************
ok: [192.168.0.222]
TASK [Add/Update an environment variable to the remote user's shell] ***********************************************
ok: [192.168.0.222]
TASK [Get the value of the environment variable we just added] *****************************************************
fatal: [192.168.0.222]: FAILED! => {"changed": true, "cmd": "source ~/.bash_profile && echo $ENV_VAR", "delta": "0:00:00.002337", "end": "2020-12-02 10:20:21.963968", "msg": "non-zero return code", "rc": 127, "start": "2020-12-02 10:20:21.961631", "stderr": "/bin/sh: 1: source: not found", "stderr_lines": ["/bin/sh: 1: source: not found"], "stdout": "", "stdout_lines": []}
PLAY RECAP *********************************************************************************************************
192.168.0.222 : ok=2 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
执行后的结果:
$ cat ~/.bash_profile
ENV_VAR=Updated2
ENV_VAR2=Updated
$ source ~/.bash_profile && echo $ENV_VAR
Updated2
我以同一用户身份登录(在终端窗口和 Ansible 的 SSH 中)
解决方案
如以下指南所示:
https://docs.ansible.com/ansible/2.5/modules/shell_module.html
Ansible shell 实际上在 /bin/sh 而不是 /bin/bash 中运行。您可以通过以下方式将 shell 指定为 /bin/bash:
- name: Get the value of the environment variable we just added
shell: source ~/.bash_profile && echo $ENV_VAR
register: env_var_updated
args:
executable: /bin/bash
推荐阅读
- node.js - 如何将 #each 中的车把中的下一个值放入下一行?
- python - 转换 pandas.DataFrame 中的元组列表
- spring-mvc - 带有两个表单和一个提交按钮的jsp文件
- r - 重命名与不同命名模式匹配的变量以一致方式表示时间的最佳方法?
- winapi - Win32 API 获取机器 UUID
- ios-simulator - Apple TV 模拟器 - Siri Remote 未出现
- javascript - 为什么这段代码返回未定义的值?
- html - 我的导航栏没有保持在顶部,它会一直滚动,如何让它保持在顶部
- flutter - Fluttter 在真机上运行和调试
- javascript - 为什么我的推送到数组函数返回为空?