Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extend windows path variable using ansible

Using win_environment, it is possible to add/remove environment variables to a windows host. But to modify variables that are already there, win_environment does not seem to be useful as u can't read old value to modify and update a variable. right?

like image 640
Kiarash Zamanifar Avatar asked Jan 08 '23 08:01

Kiarash Zamanifar


2 Answers

EDIT: Since Ansible 2.3, the win_path module does all the heavy lifting for you. Just give it a list of items that should be present in the path and it'll make sure they're present and in the relative order you specified.

(if you're still using an ancient version of Ansible, the following is still the way to go)

To get this to work sanely, you'll want to combine with a replace and search filter to only make the change if the value you want isn't in there. For instance (this is for Ansible 1.9):

  - raw: echo %PATH%
    register: path_out

  - win_environment: 
      name: path
      value: "{{ path_out.stdout | regex_replace('[\r\n]*', '') + ';C:\\\\newpath' }}"
      state: present
      level: machine
    when: not (path_out.stdout | search("(?i)c:\\\\newpath"))

This is a lot harder than it should be- I've got half a mind to hack up a win_path module for 2.0 to make it easier...

For 2.0, raw runs under Powershell, so you'd want Get-Item env:PATH instead.

like image 169
nitzmahone Avatar answered Jan 16 '23 02:01

nitzmahone


I just spent some hours fighting with Ansible, Jinja2, and JSON backslash hell and finally found a generic solution for this - ie, one that lets you add ANY directory to the system path, and won't add the same path twice. I adapted Devis' solution but made both the SETX command and the when: clause accept (the same) {{item}}, so it could be parameterized. Here's what I came up with.

Save this as extend-path.yml:

---
- name: Get current machine PATH.
  raw: $ENV:PATH
  register: path_out

- name: "Add {{ item }} to PATH."
  raw: SETX /M PATH "$ENV:PATH;{{ item }}"
  when: "not (path_out.stdout | urlencode | search( '{{ item | urlencode }}' ) )"
  changed_when: true

And then, for example, in your playbook.yml:

---
tasks:
  - name: Add tools to PATH.
    include: extend-path.yml
    with_items:
      - C:\bin
      - C:\Program Files (x86)\CMake\bin
      - C:\Program Files\git\cmd

(As you see, I actually lost the backslash war and decided to bypass it entirely by using urlencode.)

like image 31
Chris Hillery Avatar answered Jan 16 '23 00:01

Chris Hillery