regex - "lineinfile": add new line (with PATH=) or append to existing line (with PATH=)

标签 regex ansible

我正在尝试将路径部分替换或附加到 linux 机器上的/etc/environment 中的路径定义。

这是我所拥有的:

//all.yml
my_path: "/usr/bin:/usr/sbin"
my_extra_path: "/usr/extra/path"

在我的角色文件中:

//updatePath.yml
- name: update /etc/environment
  lineinfile:
    dest=/etc/environment
    state=present
    backrefs=yes
    regexp='PATH=({{ my_path }}:?)?({{ my_extra_path }}:?)?(.*)'
    line='PATH={{ my_extra_path }}:{{ my_extra_path }}:\3'

现在,当我运行该角色时,它可以很好地更新现有的 PATH 行,但不会在该行内创建重复项,甚至不会创建重复行。到目前为止一切顺利。

当没有包含“PATH=”的行时,我希望它添加一个新行。但事实并非如此。

是我的预期有误还是问题出在哪里?

最佳答案

您正在使用 backrefs: true 标志,如果该行尚不存在,它会阻止 lineinfile 更改文件。来自文档:

Used with state=present. If set, line can contain backreferences (both positional and named) that will get populated if the regexp matches. This flag changes the operation of the module slightly; insertbefore and insertafter will be ignored, and if the regexp doesn't match anywhere in the file, the file will be left unchanged. If the regexp does match, the last matching line will be replaced by the expanded line parameter.

如果该行不存在则需要创建该行,因此您应该使用:

- name: Check whether /etc/environment contains PATH
  command: grep -Fxq "PATH=" /etc/environment
  register: checkpath
  ignore_errors: True
  changed_when: False

//updatePath.yml
- name: Add path to /etc/environment
  lineinfile:
    dest=/etc/environment
    state=present
    regexp='^PATH='
    line='PATH={{ my_extra_path }}'
  when: not checkpath.rc == 0

- name: update /etc/environment
  lineinfile:
    dest=/etc/environment
    state=present
    backrefs=yes
    regexp='PATH=({{ my_path }}:?)?({{ my_extra_path }}:?)?(.*)'
    line='PATH={{ my_extra_path }}:{{ my_extra_path }}:\3'
  when: checkpath.rc == 0

关于regex - "lineinfile": add new line (with PATH=) or append to existing line (with PATH=),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834862/

相关文章:

ansible - 使用 ansible playbook 进行 Logrotate

ansible - 如何读取其他主机的变量? (不是事实)

shell - Ansible 命令模块显示 '|' 是非法字符

regex - 使用 bash 删除字符串的一部分

docker - Ansible: 'item' 未定义

c# - 如何从双引号中删除换行符?

javascript - 正则表达式 : 0. 50 到 100.00

python - Ansible gce 模块 : create instance with customize disk size

javascript - JavaScript 中的正则表达式

regex - 从识别命令解析图像大小