我正在尝试使用Ansible和lineinfile + insertbefore将json条目添加到特定位置的文件中。 这是原始文件的模拟:
const var =
{
"values": [
{
"entry1":500,
"entry2": "test001",
"entry3": true
},
{
"entry1":3,
"entry2": "test002",
"entry3": false
}
]
};
ansible脚本是这样的:
- name: script description 1
lineinfile:
dest: /destinationPATH/file.xpto
insertbefore: "]"
line: "\t\t,\t\t{\n\t\t\t'entry1':0,\n\t\t\t'entry2': 'ansible entry',\n\t\t\t'entry3': true\n\t\t}\n"
state: present
backup: yes
在第一次尝试时,它可以正常工作,并添加了预期的条目!
const var =
{
"values": [
{
"entry1": 500,
"entry2": "test001",
"entry3": true
},
{
"entry1": 3,
"entry2": "test002",
"entry3": false
}
,
{
"entry1": 0,
"entry2": "ansible entry",
"entry3": true
}
]
};
问题是,如果我运行两次,...它将再次添加该条目...
const var =
{
"values": [
{
"entry1": 500,
"entry2": "test001",
"entry3": true
},
{
"entry1": 3,
"entry2": "test002",
"entry3": false
}
,
{
"entry1": 0,
"entry2": "ansible entry",
"entry3": true
}
,
{
"entry1": 0,
"entry2": "ansible entry",
"entry3": true
}
]
};
尝试过
- name: script description 2
become: yes
become_method: sudo
lineinfile:
dest: /destinationPATH/file.xpto
insertbefore: "]"
line: "\t\t,\t\t{\n\t\t\t'entry1':0,\n\t\t\t'entry2': 'ansible entry',\n\t\t\t'entry3': true\n\t\t}\n"
backup: yes
check_mode: yes
现在文件甚至都没有更改... 我有什么办法可以评估文件中是否存在该行,如果正确,然后ansible将其添加?
答案 0 :(得分:1)
我将问题分解为两个任务。
我假设您的ansible entry
是唯一的字符串,您可以在文件中搜索。
所以首先,我将检查条目是否完全存在于文件中,就像这样:
- name: Check if the file contains the entry
shell: cat /destinationPATH/file.xpto | grep "ansible entry"
become: yes
become_method: sudo
failed_when: false
register: grep_result
grep_result
是一个词典,除其他内容外,还包含shell命令的返回代码,即0
以外的其他情况,以防失败,这意味着该条目不存在。 >
failed_when: false
做到这一点,以使播放不会因此中断。
然后您可以使用when
使任务取决于结果,如下所示:
- name: script description 2
become: yes
become_method: sudo
lineinfile:
dest: /destinationPATH/file.xpto
insertbefore: "]"
line: "\t\t,\t\t{\n\t\t\t'entry1':0,\n\t\t\t'entry2': 'ansible entry',\n\t\t\t'entry3': true\n\t\t}\n"
backup: yes
when: grep_result.rc > 0