我尝试通过Ansible将路径添加到文本文件中用逗号分隔的路径列表中。
我的文本文件具有(或没有)属性paths
,该属性包含路径列表。即path = path1,path2,path3
我想确保列表中存在路径(pathX),无论其位置如何,如果没有,则将其添加到末尾(如果没有行,则创建新的行路径= pathX)
我尝试使用正则表达式负前瞻的lineinfile模块失败
lineinfile:
path: /myfile
state: present
regexp: '^(paths =([\s,]+(?!pathX)[\w=\/\-\."]+)*)([\s,]*[\w=\/\-\."]+)*$'
line: '\1\3, pathX'
backrefs: yes
不存在路径时,我要插入paths = pathX
当paths = path1
时,我想拥有paths = path1, pathX
当paths = path1, pathX
时,我想拥有paths = path1, pathX
当paths = pathX, path1
时,我想拥有paths = pathX, path1
(或path1, pathX
之类的东西)
答案 0 :(得分:0)
有点粗糙,但是可以用:
---
- name: Fix line
hosts: localhost
connection: local
tasks:
- name: get line from file
command: grep '^paths = ' file
register: grep
failed_when: false
- name: Add line if not present
lineinfile:
path: file
state: present
line: "paths = pathX"
when: grep.rc != 0
- name: Ensure pathX is in line
lineinfile:
path: file
regexp: '^paths = path1'
state: present
line: "paths = path1, pathX"
when: "'paths = path1' in grep.stdout"
- name: Ensure path1 is in line
lineinfile:
path: file
regexp: '^paths = pathX'
state: present
line: "paths = pathX, path1"
when: "'paths = pathX' in grep.stdout"
您不必在单个任务中做任何事情。