Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliases on guest machine with Ansible

I want to add some aliases on a guest machine running through Vagrant. My provisioner is Ansible, and it would be great if I can add the aliases with a task on the playbook, I would prefer not having to modify my Vagrantfile.

I have tried both these in a role:
command: alias serve='pub serve --hostname=0.0.0.0'
shell: "alias serve='pub serve --hostname=0.0.0.0'"
but none of them has worked. The first raises an exception which I think comes from the ''. The second one simply doesn't add the alias.

like image 729
tomasyany Avatar asked Dec 05 '22 21:12

tomasyany


1 Answers

The shell option looks right but it will only create the alias for the session. Then when you connect to it after the provisioning then it won't exist. I'm also unsure if further plays in the playbook will be able to use it as they may use another SSH session.

To add it permanently you will need to add it to the relevant .bashrc or .bash_aliases (which is then sourced by .bashrc) depending on your Linux flavour/version.

To do this you could simply use:

shell: echo "alias serve='pub serve --hostname=0.0.0.0'" >> ~/.bash_aliases

But this would not be idempotent and rerunning the Ansible playbook or the Vagrant provisioning (which would rerun the Ansible playbook) would add duplicate lines each time.

Instead you should use the lineinfile module with something like:

- name: Add serve alias for foo user
  lineinfile:
    path=/home/foo/.bashrc
    line="alias serve='pub serve --hostname=0.0.0.0'"
    owner=foo
    regexp='^alias serve='pub serve --hostname=0.0.0.0'$'
    state=present
    insertafter=EOF
    create=True

The above play will add the alias line to the end of the foo user's .bashrc file (creating the file if it doesn't exist for some reason). When you rerun it, it attempts to match the regexp value (this might need tweaking with escaping parts) and if it matches it then it will replace it with the line value.

like image 153
ydaetskcoR Avatar answered Jan 18 '23 08:01

ydaetskcoR