No environment variables are set after sourcing. Vagrant provisioning with Ansible and shell

240 views Asked by At

I append both /etc/bash.bashrc and $HOME/.bashrc with variables by using Ansible.

After Ansible finished, the two files look like the following.

In /etc/bash.bashrc:

...
export VAR1="some text comes here"
...

In $HOME/.bashrc:

...
export VAR2="other text comes here"
...

So, Ansible does its job perfectly.

The shell script in Vagrantfile, that runs after Ansible finishes:

$init = <<-SCRIPT
whoami
echo $HOME
cat /etc/bash.bashrc
cat $HOME/.bashrc
source /etc/bash.bashrc
source $HOME/.bashrc
echo "VAR1 :: $VAR1"
echo "VAR2 :: $VAR2"
SCRIPT

config.vm.provision :init, type: :shell, inline: $init, privileged: false

Even though the two variables are set in the two files and then both files are sourced the output is:

vagrant
/home/vagrant
---> /etc/bash.bashrc contains the export
---> $HOME/.bashrc contains the export as well
VAR1 ::
VAR2 ::

As we see the two variables are not set and provides empty string.

I tried it with $HOME/.profile, but the same result.

Do you have any idea how to proceed?

1

There are 1 answers

0
techraf On BEST ANSWER

It's not enough that /etc/bash.bashrc and source $HOME/.bashrc contain the variable assignment. The variable assignment must actually have a chance to be executed.

If you look at the source of both scripts (examples below from Debian), they contain lines which break the execution when invoked in a non-interactive shell:

  • /etc/bash.bashrc

    # If not running interactively, don't do anything
    [ -z "$PS1" ] && return
    
  • $HOME/.bashrc

    # If not running interactively, don't do anything
    case $- in
        *i*) ;;
          *) return;;
    esac
    

So even though you explicitly source those files, if you insert the lines export VAR1="some text comes here" or export VAR2="other text comes here" after those conditions, they will never be executed as the provisioning script runs as non-interactive shell.

You don't actually show how you insert the variable assignment lines, but you say you "append" them. If you use Ansible's lineinfile module, you can add the insertbefore parameter to ensure these lines are placed before the script exits.