我问自己为什么Ansible在一个主机上执行~/.profile
模块之前没有提供template
文件?
遥远的主人~/.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'
答案 0 :(得分:4)
Ansible未在远程主机上的交互式shell中运行任务。 Michael DeHaan不久前回答了这个问题{/ 3}}:
基于uber的基本描述并不是真的通过shell做事,它传输模块并执行它传输的脚本,而不是使用登录shell。
即。 on github
它基本上不是一个连续的shell环境,也不是登录并输入命令和东西。
你应该通过运行这个来看到相同的结果(未定义的变量):
ssh <host> echo $ENV_VAR
答案 1 :(得分:1)
当ansible将私有程序升级为sudo时,它不会调用sudo用户的登录shell
我们需要对调用sudo的方式进行更改,例如使用-i和-H标志调用它
&#34; sudo_flags = -H&#34;在你的ansible.cfg文件中
答案 2 :(得分:1)
我在很多地方使用了以下结构:
- name: Task Name
shell: "./path/to/profile;command"
答案 3 :(得分:0)
如果您可以以root用户身份运行,则可以使用runuser。
- shell: runuser -l '{{ install_user }}' -c "{{ cmd }}"
这有效地在一个全新的登录shell中以 install_user 的形式运行命令,就好像您使用了su - *install_user*
(它加载了配置文件,尽管它可能是.bash_profile
而不是.profile
...)然后执行*cmd*
。
我尝试不以root身份运行所有内容,以便您可以像其他人一样运行它,但是...
答案 4 :(得分:0)
Ansible不在交互式或登录Shell中运行远程任务(命令,Shell等)。就像当您通过'ssh user @ host“ that 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。
答案 5 :(得分:0)
如果您可以修改目标主机的配置,并且不想更改您的Yaml代码。您可以尝试以下操作:
将变量ENV_VAR=/usr/users/toto
添加到/etc/environment
文件中,而不是~/.profile
。