Ansible -如何在CentOS中添加/修改PATH变量?

hts6caw3  于 2022-11-07  发布在  其他
关注(0)|答案(1)|浏览(170)

我尝试将/usr/pgsql-10/bin添加到$PATH,因为我希望使用该计算机的每个人都能够运行psql命令。
尝试以this为例:

- 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"

首先,我不太明白我应该如何修改它。我应该用我的路径(/usr/pgsql-10/bin)来替换extra_path还是整个{{extra_path}}
我尝试了两种方法,都得到了不同的错误。更糟糕的是,我的/etc/environment甚至不包含PATH

eit6fx6z

eit6fx6z1#

仅声明其他路径

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

下面的任务基于Response to updating PATH with ansible - system wide的想法

  • 如果文件在控制器上,则测试本地文件
- 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
  • 如果文件在远程主机上,请先获取它们。要使播放等幂,请不要报告获取时的更改。根据您的需要调整目标
- 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

请参阅Python正则表达式。

相关问题