问题描述
我有一个 ansible 任务,将 2 行写入 journald.conf,但是再次运行时它不执行幂等性。
我看到以下问题对我不起作用:
- Ansible lineinfile duplicates line
- Idempotency in ansible playbook
- https://github.com/ansible/ansible/issues/4531
我的正则表达式似乎没问题,您可以在我的任务下方看到:
- name: set cpu affinity settings in systemd
lineinfile:
dest: /etc/systemd/journald.conf
line: "{{ item.key }}={{ item.value }}"
regexp: "^#?{{ item.value }}"
state: present
with_dict:
RateLimitIntervalSec: 0
RateLimitBurst: 0
tags: journald
notify: restart journald
预期的行为应该是:保留注释行并在文件末尾添加新的注释行以及列表中的项目,除非未注释的行已经存在。
[Journal]
#Storage=auto
#Compress=yes
#Seal=yes
#SplitMode=uid
#SyncIntervalSec=5m
#RateLimitIntervalSec=30s
#RateLimitBurst=1000
#SystemMaxUse=
#SystemKeepFree=
#SystemMaxFileSize=
#SystemMaxFiles=100
#RuntimeMaxUse=
#RuntimeKeepFree=
#RuntimeMaxFileSize=
#RuntimeMaxFiles=100
#MaxRetentionSec=
#MaxFileSec=1month
#ForwardToSyslog=yes
#ForwardToKMsg=no
#ForwardToConsole=no
#ForwardToWall=yes
#TTYPath=/dev/console
#MaxLevelStore=debug
#MaxLevelSyslog=debug
#MaxLevelKMsg=notice
#MaxLevelConsole=info
#MaxLevelWall=emerg
#LineMax=48K
RateLimitIntervalSec=0
RateLimitBurst=0
RateLimitIntervalSec=0
RateLimitBurst=0
RateLimitIntervalSec=0
RateLimitBurst=0
RateLimitIntervalSec=0
RateLimitBurst=0
我尝试使用上述文章中建议的参数 backrefs: yes
,但它每次都执行幂等性,即使没有任何未注释的行也是如此。
大家有什么建议吗?
我使用的是 ansible 2.9.0
解决方法
我建议另一种方法 - 使用 ini_file 模块,因为 journald.conf
中的设置是 INI 样式 key=value
(还有一个部分)。这将简化所需的任务并具有幂等性。
示例:
- name: set cpu affinity settings in systemd
ini_file:
path: /etc/systemd/journald.conf
section: Journal
option: "{{ item.key }}"
value: "{{ item.value }}"
no_extra_spaces: yes
with_dict:
RateLimitIntervalSec: 0
RateLimitBurst: 0
注意:如果您想在更改之前参考设置,请将 backup: yes
添加到任务中。