Ansible不会加载〜/ .profile

pie*_*ier 5 ansible

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

远程主机~/.profile

export ENV_VAR=/usr/users/toto
Run Code Online (Sandbox Code Playgroud)

一个简单的Ansible任务:

- template: src=file1.template dest={{ ansible_env.ENV_VAR }}/file1
Run Code Online (Sandbox Code Playgroud)

Ansible失败,原因:

fatal: [distant-host] => One or more undefined variables: 'dict object' has no attribute 'ENV_VAR'
Run Code Online (Sandbox Code Playgroud)

Jur*_*lak 8

Ansible 不在交互式或登录 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
Run Code Online (Sandbox Code Playgroud)

bash: '-i' 表示交互式 shell,因此 .bashrc 不会被忽略 '-l' 表示登录 shell,它提供完整的用户配置文件(/etc/profile 和 ~/.bash_profile,或 ~/.profile - 参见 bash 手册)页面了解更多详情)

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


iti*_*iic 6

在很多地方我都使用了以下结构:

- name: Task Name
  shell: ". /path/to/profile;command"
Run Code Online (Sandbox Code Playgroud)

  • “.”之间有空格 和“/path/to/profile”。这 ”。” 意思是“来源” (3认同)

udo*_*dan 5

Ansible不在远程主机上的交互式外壳中运行任务。迈克尔·德哈恩(Michael DeHaan)在github上已经回答了这个问题:

uber基本描述是Ansible的,实际上不是通过shell做事,它是在传输模块和执行它所传输的脚本,而不是使用登录shell。

即,为什么与手动运行相比,SSH远程命令获得的环境变量更少?

基本上,它不是一个连续的shell环境,也不是登录并键入命令和事物。

通过运行以下命令,您应该看到相同的结果(未定义的变量):

ssh <host> echo $ENV_VAR
Run Code Online (Sandbox Code Playgroud)