Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not possible to source .bashrc with Ansible

Tags:

ansible

I can ssh to the remote host and do a source /home/username/.bashrc - everything works fine. However if I do:

- name: source bashrc   sudo: no   action: command source /home/username/.bashrc 

I get:

failed: [hostname] => {"cmd": ["source", "/home/username/.bashrc"], "failed": true, "rc": 2} msg: [Errno 2] No such file or directory 

I have no idea what I'm doing wrong...

like image 264
pldimitrov Avatar asked Mar 07 '14 17:03

pldimitrov


People also ask

What source .bashrc does?

bashrc file is a script, and by sourcing it, you execute the commands placed in that file. The commands define aliases in your case, but there can be virtually any commands placed in that file. you could also use exec bash to replace the current bash process with a new.

What is the difference between Shell and command in Ansible?

Both modules execute commands on target nodes but in a sensible different way. The command modules execute commands on the target machine without using the target shell, it simply executes the command. The target shell is for example the popular bash , zsh , or sh .


2 Answers

You have two options to use source with ansible. One is with the "shell:" command and /bin/sh (the ansible default). "source" is called "." in /bin/sh. So your command would be:

- name: source bashrc   sudo: no      shell: . /home/username/.bashrc && [the actual command you want run] 

Note you have to run a command after sourcing .bashrc b/c each ssh session is distinct - every ansible command runs in a separate ssh transaction.

Your second option is to force Ansible shell to use bash and then you can use the "source" command:

- name: source bashrc   sudo: no      shell: source /home/username/.bashrc && [the actual command you want run]   args:      executable: /bin/bash 

Finally, I'll note that you may want to actually source "/etc/profile" if you're on Ubuntu or similar, which more completely simulates a local login.

like image 100
Steve Midgley Avatar answered Sep 22 '22 17:09

Steve Midgley


So command will only run executables. source per se is not an executable. (It's a builtin shell command). Is there any reason why you want to source a full environment variable?

There are other ways to include environment variables in Ansible. For example, the environment directive:

- name: My Great Playbook   hosts: all   tasks:     - name: Run my command       sudo: no       action: command <your-command>       environment:           HOME: /home/myhome 

Another way is to use the shell Ansible module:

- name: source bashrc   sudo: no   action: shell source /home/username/.bashrc && <your-command> 

or

- name: source bashrc   sudo: no      shell: source /home/username/.bashrc && <your-command> 

In these cases, the shell instance/environment will terminate once the Ansible step is run.

like image 40
Rico Avatar answered Sep 21 '22 17:09

Rico