Regarding the issue of using ansible to execute the "source" command

I have three machines, and each of them has Helm installed. The installation path is /usr/local/bin.

I added the configuration for automatic completion of the helm command in the ~/.bashrc file.

grep helm ~/.bashrc 
source <(/usr/local/bin/helm completion bash)

Executing commands in the shell terminal takes effect.

source ~/.bashrc

However, it doesn’t work when executed using Ansible.

$ ansible all -m shell -a 'source ~/.bashrc'
k8s-node01 | CHANGED | rc=0 >>
/root/.bashrc: line 33: /usr/local/bin/helm: No such file or directory
k8s-node02 | CHANGED | rc=0 >>
/root/.bashrc: line 33: /usr/local/bin/helm: No such file or directory
k8s-master01 | CHANGED | rc=0 >>

How should this problem be solved?

What user is ansible using to connect?

Where is that users’ home directory?

Is there a .bashrc file there?

But I think the best question is, what problem are you trying to solve by having autocompletion available to ansible? Its not like you’d be tab-completing commands via ansible.

Ansible, by default uses /bin/sh, not bash, even if /bin/sh is implemented via bash it is normally in ‘posix compatibility mode’ and not all bash features will be available.

Also note that each task is run in isolation so source in one task, won’ t affect subsequent tasks.

Ohh, good catch there, I hadn’t considered that bit.

It is the root user. The home directory of the root user is /root , and there is the file /root/.bashrc. What I want to achieve is to execute source ~/.bashrc in the terminal alone, which can be done successfully. However, when using Ansible to execute this command, it does not work.

That is to say, it is impossible to achieve the same effect as executing source ~/.bashrc alone in the terminal through Ansible. Executing commands like ansible all -m shell -a 'source ~/.bashrc is not feasible.

Not impossible, you just need to make sure you execute bash, also this is just not very useful as the next task won’t reuse the same session nor shell.

On top of that, autocompletion of other shell utilities makes no sense in the case of ansible as it has no access to the remote shell when constructing tasks.

Then I’ll look for other methods. If this kind of writing is used, it will definitely not work. ansible all -m shell -a 'source ~/.bashrc'

again, you are not using bash:

 -a 'executable=/bin/bash cmd="source ~/.bashrc"'

even then, while it will execute, it will not do anything meaningful

Thank you for your reply. I think my idea was somewhat incorrect. After I executed the command ansible all -b -m lineinfile -a "path=~/.bashrc line='source <(helm completion bash)' state=present", it only needed to be manually executed in the terminal or re-login next time for it to take effect.