首页 > 解决方案 > 为什么我不能使用 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 中)

标签: linuxbashterminalansible

解决方案


如以下指南所示:

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

推荐阅读