Append to .bashrc using Ansible
You can append to .bashrc
using the Ansible blockinfile
module.
Since Ansible is intended to be idempotent, by default it will add # BEGIN
and # END
comments around the block. This enables Ansible to detect whether the block has already been added, and so avoids making the change if the block already matches.
Following is a simple example of appending some code to .bashrc
that shows our current Git branch in bash.
The code for appending §
This is the code we want to append to .bashrc
:1
Nothing particularly special here. Just make sure the bashrc_extra.sh
file has unix line endings (LF
), not Windows (CR LF
), else when you run the playbook each line will have ^M
at the end when viewed in less
.
Playbook task §
We add this task to our playbook:
It does the following:
- Uses
ansible_env.HOME
to look up theHOME
environment variable, which gives us the path to the home directory on the target machine. - The
block
usesansible.builtin.file
to read the contents ofbashrc_extra.sh
from the local machine.
We have this structure on our local machine:
Structure §
A quick aside…
You might prefer to put the bashrc_extra.sh
in a config
directory, especially as the project grows.
To do so, just specify 'config/bashrc_extra.sh'
in the block
:2
Running the playbook §
That’s it, now we can run the playbook.
After running the playbook, this is what ~/.bashrc
on the target machine contains:
And if you run the playbook again, the task will make no changes, because the block is already applied.
Taken from here. Thanks danielalvarenga and abdobouna. ↩︎
Made with this fun tool. ↩︎