Ansible循环JSON数组包含对象,并替换文件中JSON中找到的每个元素



我有这个JSON:

[{
"${foo1}": "somevalue1",
"${foo2}": "somevalue2"
}, {
"${zoo1}": "somevalue111",
"${zoo2}": "somevalue222"
}]

其中,我需要在ansible和JSON数组中的每个对象中循环每个键/对值我喜欢检查文件中是否存在密钥,并将其替换为值。例如:如果在文件中我有

key1=${foo1}

它将被取代

key1=somevalue1

我过去有一个硬编码的易感任务:

replace:
path: "/myfile.txt"
regexp: "{{ item.regexp }}"
replace: "{{ item.replace }}"
with_items:
- { regexp: '${foo1}', replace: "new_value" }

我喜欢将其转换为根据给定的JSON 动态搜索和替换

我捕获的JSON如下:(这是修剪YAML(

---
-
gather_facts: false
hosts: localhost
name: test
tasks:
- name: debug
debug:
msg: "{{ AAA| to_json }}"
- name: set fact
set_fact:
multi_parms: "{{ AAA| to_json }}"
- name: debug multi_parms
debug:
var: multi_parms 

将JSON文件读取到单个字典中,例如

- set_fact:
my_data: "{{ my_data|d({})|combine(item) }}"
loop: "{{ lookup('file', 'test.json') }}"

给出

my_data:
${foo1}: somevalue1
${foo2}: somevalue2
${zoo1}: somevalue111
${zoo2}: somevalue222

给定INI文件,例如

shell> cat conf.ini
key1=${foo1}
key2=${foo2}
key3=xyz

将配置解析到字典中,例如

- set_fact:
my_ini: "{{ dict(_keys|zip(_vals)) }}"
vars:
_lines: "{{ lookup('file', 'conf.ini').splitlines() }}"
_regex: '^(.*)=(.*)$'
_keys: "{{ _lines|map('regex_replace', _regex, '\1') }}"
_vals: "{{ _lines|map('regex_replace', _regex, '\2') }}"

给出

my_ini:
key1: ${foo1}
key2: ${foo2}
key3: xyz

然后使用模块ini_file替换数据,例如

- ini_file:
path: conf.ini
section:
option: "{{ item }}"
value: "{{ my_data[my_ini[item]] }}"
no_extra_spaces: true
loop: "{{ my_ini|list }}"
when: my_ini[item] in my_data

给出

shell> cat conf.ini
key1=somevalue1
key2=somevalue2
key3=xyz

Q:">如何在目标文件中进行搜索和替换">

A: 参见下面的"--diff";每次迭代的输出。

TASK [ini_file] ***************************************************
--- before: conf.ini (content)
+++ after: conf.ini (content)
@@ -1,3 +1,3 @@
-key1=${foo1}
+key1=somevalue1
key2=${foo2}
key3=xyz
changed: [localhost] => (item=key1)
--- before: conf.ini (content)
+++ after: conf.ini (content)
@@ -1,3 +1,3 @@
key1=${foo1}
-key2=${foo2}
+key2=somevalue2
key3=xyz
changed: [localhost] => (item=key2)
skipping: [localhost] => (item=key3)
这个代码在j2模板中
{% for  item in json_data %}
{% for k, v in item.items() %}

key{{loop.index}}  =  {{ v }}

{% endfor %}
{% endfor %} 

得到这个结果

key1  =  somevalue1
key2  =  somevalue2
key1  =  somevalue111
key2  =  somevalue222

这就是你想要的吗?

最新更新