Search code examples
centosansible

Ansible - How to add/modify PATH variable in CentOS?


I'm trying to add /usr/pgsql-10/bin to $PATH, since I want everybody who uses the machine, to be able to run the psql command.

Tried to follow this example:

- name: add {{extra_path}} to path
  lineinfile:
    dest: /etc/environment
    state: present
    backrefs: yes
    regexp: 'PATH=(["]*)((?!.*?{{extra_path}}).*?)(["]*)$'
    line: "PATH=\1\2:{{extra_path}}\3"

First of all, I don't quite understand how should I exactly modify this. Should I replace just the extra_path or the whole {{extra_path}} with my path (/usr/pgsql-10/bin).

I tried either way and I get different errors. To makes matters worse, my /etc/environment doesn't even contain PATH.


Solution

  • Declare additional path only

      vars:
        extra_path: /usr/pgsql-10/bin
    

    The tasks below are based on the idea from Response to updating PATH with ansible - system wide

    • If the file is at the controller test the local file
        - name: 'Add {{ extra_path }} if PATH does not exist'
          lineinfile:
            path: /etc/environment
            line: 'PATH="{{ extra_path }}"'
            insertafter: EOF
          when: lookup('file', '/etc/environment') is not search('^\s*PATH\s*=')
    
        - name: 'Add {{ extra_path }} to PATH'
          lineinfile:
            path: /etc/environment
            regexp: 'PATH=(["])((?!.*?{{ extra_path }}).*?)(["])$'
            line: 'PATH=\1\2:{{ extra_path }}\3'
            backrefs: yes
    
    • If the files are on the remote hosts fetch them first. To make the play idempotent don't report changes on fetching. Fit the destination to your needs
    
        - name: 'Fetch /etc/environment to {{ playbook_dir }}/environments'
          fetch:
            src: /etc/environment
            dest: "{{ playbook_dir }}/environments"
          changed_when: false
    
        - name: 'Add {{ extra_path }} if PATH does not exist'
          lineinfile:
            path: /etc/environment
            line: 'PATH="{{ extra_path }}"'
            insertafter: EOF
          when: lookup('file', path) is not search('^\s*PATH\s*=')
          vars:
            path: "{{ path_items|path_join }}"
            path_items:
              - "{{ playbook_dir }}"
              - environments
              - "{{ inventory_hostname }}"
              - etc/environment
    
        - name: 'Add {{ extra_path }} to PATH'
          lineinfile:
            path: /etc/environment
            regexp: 'PATH=(["])((?!.*?{{ extra_path }}).*?)(["])$'
            line: 'PATH=\1\2:{{ extra_path }}\3'
            backrefs: yes
    

    See Python regex.