6

Ansible v2.4.0.0 on RHEL 6.x

I see How to set linux environment variables with ansible, but it deals with setting a NEW environment variable. The solution does NOT work for me if I try to set my PATH variable. I do...

- name: Add /usr/other/bin to PATH dir to use the git binary there
  environment:
#    PATH: /usr/other/bin:{{ ansible_env.PATH }}
    PATH: /usr/other/bin:{{ lookup('env','PATH') }}

I've tried both ways, shown above, commenting out one vs. the other, and I get syntax errors in both cases. What am I missing?

Chris F
  • 14,337
  • 30
  • 94
  • 192

2 Answers2

18

This is the correct way to extend PATH variable for a single task:

- name: Execute task with extended PATH
  shell: echo $PATH
  environment:
    PATH: "/usr/other/bin:{{ ansible_env.PATH }}"

environment is not an action by itself, it's a keyword to modify actions' (shell in my example) environment.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
0

I don't know why, but Konstantin Suvorov solution doesn't work for me.

After some tests I used following Ansible part in combination with Vagrant (Ubuntu guest).

-name: Creating environment variable via file in /etc/profile.d
 args:
   chdir: /etc/profile.d
 shell: echo "export M2_HOME=/home/vagrant/maven" > env.sh

This works with PATH, too, by adding it into the quotes with ${PATH}.

hesch
  • 134
  • 4
  • I had the same problem but found the solution - make sure `gather_facts: true`. Konstantin's solution should work. – Dodgyrabbit Jan 22 '22 at 19:32