Ansible 不加载 ~/.profile

标签 ansible

我问自己为什么 Ansible 在一台主机上执行 template 模块之前不获取 ~/.profile 文件?

远程主机~/.profile:

export ENV_VAR=/usr/users/toto

单个 Ansible 任务:

- template: src=file1.template dest={{ ansible_env.ENV_VAR }}/file1

Ansible 失败:

fatal: [distant-host] => One or more undefined variables: 'dict object' has no attribute 'ENV_VAR'

最佳答案

Ansible 不在交互式 shell 或登录 shell 中运行远程任务(命令、shell 等)。这与您通过 'ssh user@host "which python"' 远程执行命令相同 源 ~/.bashrc 不会经常工作,因为 ansible shell 不是交互式的,并且 ~/.bashrc 实现默认忽略非交互式 shell(检查其开头)。

我发现在 ssh 交互式登录后以用户身份执行命令的最佳解决方案是:

- hosts: all
  tasks:
    - name: source user profile file
      #become: yes
      #become_user: my_user  # in case you want to become different user (make sure acl package is installed)
      shell: bash -ilc 'which python' # example command which prints
      register: which_python
    - debug:
      var: which_python

bash: '-i' 表示交互式 shell,因此 .bashrc 不会被忽略 '-l' 表示登录 shell,它获取完整的用户配置文件(/etc/profile 和 ~/.bash_profile,或 ~/.profile - 有关更多详细信息,请参阅 bash 手册页)

我的示例说明:我的 ~/.bashrc 从该用户下安装的 anaconda 设置特定的 python。

关于Ansible 不加载 ~/.profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35988567/

相关文章:

regex - 正则表达式找不到任何匹配项来使用 ansible.builtin.replace 替换文本

docker - 是否在Kubernetes中为Docker Splunk做好了准备?

python - 使用 Python API 运行 Ansible playbook

ubuntu - 如何使用ansible设置FQDN?

python - 如何在循环中使用 with_dict 编写 Ansible 任务 (with_items)

linux - 无法导入 docker 或 docker-py - 没有名为 docker 的模块

Ansible:检查变量是否包含列表或字典

ansible - 如何用ansible相对角色复制文件?

ansible - Ansible 字符串中的新行

Ansible无限期暂停