首页 > 解决方案 > Ansible:如何迭代几个键/值以在多个文件中进行字符串替换

问题描述

我有多个配置文件,其中包含我想用特定于环境的值替换的标签。我的文件看起来像:

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

我有一个将配置文件部署到选定目标的 ansible 剧本。首先,我使用 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 find 模块一起列出

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

如何通过 ansible 任务来实现这一点?它看起来像:

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

标签: ansibleyaml

解决方案


我自己回答,看来我只需要在这里问自己才能找到解决方案:)

首先我改变了标签文件的语法:

---
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}}"

推荐阅读