Ansible:如何遍历键/值对在多个文件中进行字符串替换

时间:2019-01-11 08:52:19

标签: ansible yaml

我有多个配置文件,其中包含要替换为特定于环境的值的标记。我的文件如下:

confId1:@DESTPATH1@:@USER1@:@PASSWORD1@
confId2:@DESTPATH2@:@USER2@:@PASSWORD2@

要使用的值在目标服务器上的标记文件(yaml)中。

DEV.yml:
---
DESTPATH1: /my/dest/path1
DESTPATH2: /my/dest/path2
USER1: mydevuser1
USER2: mydevuser2
PASSWORD1: 123456
PASSWORD2: 654321

我有一本能将配置文件部署到所选目标的剧本。首先,我用slurp读取远程标记文件:

- name: slurp tag file
  slurp:
    src: "/path/to/tag/DEV.yml"
  register: slurped

我可以轻松访问一个已知的密钥以显示其值:

- debug:
    msg: "slurped: {{ (slurped.content|b64decode|from_yaml).DESTPATH1 }}"

然后可以将标签@ DESTPATH1 @替换为其值:

- name: replace tags
  replace:
    dest: "/path/to/my/conf/file1.conf"
    regexp: "@DESTPATH1@"
    replace: "{{ (slurped.content|b64decode|from_yaml).DESTPATH1 }}"

现在让我们考虑: -我不知道标记文件中的哪些键,因此我必须遍历它们。 -存在多个必须替换标签的配置文件。这些与ansible查找模块一起列出

- name: find conf files
  find:
    paths: "/path/to/my/conf"
    patterns: "*.conf"
  register: confFiles

如何通过一项艰巨的任务实现这一目标?看起来像:

- Iterate over the keys found in the tag file.
- For each key, iterate over the conf files and replace @key@ with the corresponding value

1 个答案:

答案 0 :(得分:2)

我回答自己,看来我只需要在这里自己寻求解决方案即可:)

首先,我更改了标记文件的语法:

---
tags:
  - tkey: DESTPATH1
    tvalue: /my/dest/path1
  - tkey: DESTPATH2
    tvalue: /my/dest/path2
  - tkey: USER1
    tvalue: mydevuser1
  - tkey: USER2
    tvalue: mydevuser2
  - tkey: PASSWORD1
    tvalue: 123456
  - tkey: PASSWORD2
    tvalue: 654321

然后执行我想要的任务:

- name: replace tag.key with tag.value
  replace:
    dest: "{{item[1].path}}"
    regexp: "@{{item[0].tkey}}@"
    replace: "{{item[0].tvalue}}"
  with_nested:
    - "{{(slurped.content|b64decode|from_yaml).tags}}"
    - "{{confFiles.files}}"