gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:50:19 24 4
gpt4 key购买 nike

我正在尝试将路径部分替换或附加到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com