无法使用Ansible来源.bashrc
我可以ssh到远程主机,并做一个source /home/username/.bashrc – 一切工作正常。 但是,如果我这样做: 
 - name: source bashrc sudo: no action: command source /home/username/.bashrc 
我得到:
 failed: [hostname] => {"cmd": ["source", "/home/username/.bashrc"], "failed": true, "rc": 2} msg: [Errno 2] No such file or directory 
我不知道我在做什么错…
你有两个select来使用源代码。 一个是“shell:”命令和/ bin / sh(有效的默认值)。 “来源”被称为“。” 在/ bin / sh中。 所以你的命令是:
 - name: source bashrc sudo: no shell: . /home/username/.bashrc && [the actual command you want run] 
请注意,您必须在采购.bashrc b / c之后运行命令。每个ssh会话都是不同的 – 每个有效的命令都在单独的ssh事务中运行。
你的第二个select是强制Ansible shell使用bash,然后你可以使用“source”命令:
 - name: source bashrc sudo: no shell: source /home/username/.bashrc && [the actual command you want run] args: executable: /bin/bash 
最后,我会注意到,如果你使用的是Ubuntu或者类似的,你可能想要真正的源代码“/ etc / profile”,这样更完全地模拟了一个本地login。
 所以command只会运行可执行文件。  source本身不是可执行文件。  (这是一个build立在shell命令)你有什么理由为什么你想源代码一个完整的环境variables? 在Ansible中还有其他方法可以包含环境variables。 例如, environment指令: 
 - name: My Great Playbook hosts: all tasks: - name: Run my command sudo: no action: command /bin/pwd environment: HOME: /home/myhome 
 请记住,如果您使用shell Ansible模块,您的任务将运行: 
 - name: source bashrc sudo: no action: shell source /home/username/.bashrc 
但是,一旦Ansible步骤运行,shell实例/环境将会终止。
 我知道这个答案来得太晚,但我已经看到足够的代码,你可以使用sudo选项-i所以: 
 - name: source bashrc shell: sudo -iu {{ansible_user_id}} [the actual command you want run] 
如文件中所述
 The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution via the shell's -c option. If no command is specified, an interactive shell is executed. sudo attempts to change to that user's home directory before running the shell. It also initializes the environment to a minimal set of variables, similar to what is present when a user logs in. The Command environment section below documents in detail how the -i option affects the environment in which a command is run. 
 那么我尝试列出的答案,但这些没有为我工作,而通过rbenv安装ruby。 我不得不从/root/.bash_profile代码行下面/root/.bash_profile 
 PATH=$PATH:$HOME/bin:$HOME/.rbenv/bin:$HOME/.rbenv/plugins/ruby-build/bin export PATH eval "$(rbenv init -)" 
最后,我想出了这个
 - shell: sudo su - root -c 'rbenv install -v {{ ruby_version }}' 
可以使用任何命令。
 - shell: sudo su - root -c 'your command' 
我发现成为最好的解决scheme:
 - name: Source .bashrc shell: . .bashrc become: true 
您可以通过添加(默认:root)来更改用户:
 - name: Source .bashrc shell: . .bashrc become: true become-user: {your_remote_user} 
更多信息: Ansible成为
正确的做法应该是:
 - hosts: all tasks: - name: source bashrc file shell: "{{ item }}" with_items: - source ~/.bashrc - your other command 
  注意:这是testing在ansible 2.0.2版本