Ansible“lineinfile”:添加新行(使用PATH =)或追加到现有行(使用PATH =)
问题描述:
我试图在Linux机器上的/ etc/environment中的路径定义中替换或追加路径部分。Ansible“lineinfile”:添加新行(使用PATH =)或追加到现有行(使用PATH =)
这是我有:
//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 =”存在的行时,我希望它添加一个新的行。但事实并非如此。
我的期望是错误的还是谎言的问题?
答
您正在使用backrefs: true
标志,该标志防止lineinfile在该行不存在时更改该文件。从文档:
与state = present一起使用。如果设置,则行可以包含反向引用(位置和名称均为 ),如果正则表达式匹配,则该引用将被填充。 该标志稍微改变了模块的操作;在 之前插入并且insertafter将被忽略,并且如果正则表达式不匹配 文件中的任何位置,则该文件将保持不变。如果正则表达式 确实匹配,则最后的匹配行将被扩展的 行参数替换。
既然你需要创建行,如果不存在的话,你应该使用:
- 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
答
同样的想法如下:https://stackoverflow.com/a/40890850/7231194或在这里:https://stackoverflow.com/a/40891927/7231194
步骤是:
- 尝试替换该行。
- 如果替换mod改变它。很酷,一切都结束了!
- 如果更换国防部不改变,添加行
例
# Vars
- name: Set parameters
set_fact:
my_path: "/usr/bin:/usr/sbin"
my_extra_path: "/usr/extra/path"
# Tasks
- name: Try to replace the line if it exists
replace:
dest : /dir/file
replace : 'PATH={{ my_extra_path }}'
regexp : '^PATH=.*'
backup : yes
register : tryToReplace
# If the line not is here, I add it
- name: Add line
lineinfile:
state : present
dest : /dir/file
line : '{{ my_extra_path }}'
regexp : ''
insertafter: EOF
when: tryToReplace.changed == false
没有,去掉'backrefs:TRUE'不起作用。如果您重新运行合理的角色并且它不会添加到现有路径,而是替换它,它会创建重复项。为了能够添加到路径中,我需要'backrefs:true'。在'line =' – Dominik
末尾查看'\ 3'如果条件不存在,则更新我的答案以有条件地创建该行,但否则使用backrefs更新该行。 Backrefs目前与创建不存在的行不兼容,因此您需要多个任务。 – smiller171