can not source ~/.bashrc file with ansible

2019-02-21 19:01发布

问题:

I have a list of aliases in a file, .bash_aliases, which is being copied to remote servers with ansible playbook. The file is getting copied to the destination but the .bashrc (which in turns load the .bash_aliases) file is not getting loaded using the following ansible task.

I have tried giving the executable argument

  - name: source the .bashrc file
    shell: source ~/.bashrc
    args:
      executables: "/bin/bash"

Without argument

  - name: source the .bashrc file
    shell: source ~/.bashrc

With raw module

  - name: source the .bashrc file
    raw: source ~/.bashrc

With command module - name: source the .bashrc file command: source ~/.bashrc

Nothing works!!! Any help

回答1:

From reading your comments, you stated that you are trying to make permanate aliases and not for a particular session. Why not create those aliases inside of /etc/profile.d on the machines you need to have those particular aliases on instead of by user?

Also, from another post that popped up when I ran a google search on Ansible specifics as I am no Ansible expert... Not possible to source .bashrc with Ansible (thanks to @chucksmash for the link)

"Steve Midgley

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."



回答2:

If you expect the variables you set in one Bash instance to be visible in other Bash instances, or in the Ansible instance which ran this Bash script, there is no way to do that; this is inherent to the Unix process model.

What you can do is set a variable and then run whichever tool needs for this value to be set.

bash -c 'var="value" /path/to/other/tool'

This can be arbitrarily complex, though you're probably better off creating a separate external script if the task you need to perform could require anything more than the most trivial debugging.



标签: bash ansible