我问自己为什么 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/