Ansible, junja2和使用Ansible . build .replace在值周围设置单引号



我想确保在relation_regex定义的正则表达式周围有单引号(用ansible配置datadog postgres模块)。

这就是我的目标:

conf.yml:

instances:
-   dbname: dbname
host: localhost
password: password
port: 5432
username: datadog
relations:
- relation_regex: '.*'
relkind:
- r
- i
- S
- p

这是我与可见任务的地方:


- name: Properly configure any regexp expression in a configuration file
ansible.builtin.replace:
path: "/etc/datadog-agent/conf.d/{{ item }}.d/conf.yaml"
regexp: '(s+relation_regex:)s+(?:['']*([^'']*))'
replace: 'g<1> ''g<2>'''
with_items: "{{ datadog_checks|list }}"
notify: restart datadog-agent

然而,结果是这样的:


.. cut ..
-      - relation_regex: .*
+      - relation_regex: '.*
.. cut ..

Ansible不提供结束单引号(')。感觉像一个bug,但也许有什么问题,我的环顾regex有奇怪的后果?

版本:

ansible [core 2.11.1] 
python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0]
jinja version = 3.0.1
libyaml = True

您省略了下一个那一行的"不同"输出本来可以完全暴露问题:

-    - relation_regex: .*
+    - relation_regex: '.*
+'

表示您的"除'"需要更具体,说"除'EOL字符外的任何字符"&;

- name: Properly configure any regexp expression in a configuration file
ansible.builtin.replace:
path: "/etc/datadog-agent/conf.d/{{ item }}.d/conf.yaml"
regexp: '(s+relation_regex:)s+(?:['']*([^''rn]*))'
replace: 'g<1> ''g<2>'''
with_items: "{{ datadog_checks|list }}"
notify: restart datadog-agent

另外,虽然这不是您所要求的,但您使用包含单引号转义的单引号标量使事情变得比必要时更加困难,因为(目前)在那些需要引号的标量中没有yaml敏感的内容:

- name: Properly configure any regexp expression in a configuration file
ansible.builtin.replace:
path: "/etc/datadog-agent/conf.d/{{ item }}.d/conf.yaml"
regexp: (s+relation_regex:)s+(?:'*([^'rn]*))
replace: g<1> 'g<2>'
with_items: "{{ datadog_checks|list }}"
notify: restart datadog-agent

您还需要谨慎,因为根据编写的替换将无法协调现有的单引号项,如果您运行该任务两次,将导致幂等性失败

- name: Properly configure any regexp expression in a configuration file
ansible.builtin.replace:
path: "/etc/datadog-agent/conf.d/{{ item }}.d/conf.yaml"
regexp: (s+relation_regex:)s+(?:'*([^'rn]*)'*)
replace: g<1> 'g<2>'
with_items: "{{ datadog_checks|list }}"
notify: restart datadog-agent

给定文件

shell> cat conf.yaml
relation_regex: .*

任务
- ansible.builtin.replace:
path: conf.yaml
regexp: '(s+relation_regex:)s+''?(.*)''?'
replace: '1 ''2'''

给出(运行——check——diff选项)

--- before: conf.yaml
+++ after: conf.yaml
@@ -1 +1 @@
- relation_regex: .*
+ relation_regex: '.*'

最新更新