首页 > 解决方案 > Ansible lineinfile 不执行幂等性

问题描述

我有一个将 2 行写入 journald.conf 的 ansible 任务,但是在再次运行时它不会执行幂等性。

我已经看到以下对我不起作用的问题:

我的正则表达式似乎没问题,你可以在下面看到我的任务:

- 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

预期的行为应该是:保留注释行并在文件末尾添加新的行以及列表中的项目,除非未注释的行已经存在。

我的文件 journald.conf 文件是这样的:

[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

标签: ansibleidempotent

解决方案


我建议另一种方法 - 使用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到任务中。


推荐阅读