LoginSignup
2
2

More than 5 years have passed since last update.

Ansibleで設定ファイルの行を書き換える

Posted at

すでにある環境に対して、Ansibleで構成変更するとき、lineinfile で行を置き換えるのではなく、既存の行の一部を変更したいことがある。

しかし、このようなときに、冪等性を確保するのは意外に難しい。正規表現では、最小一致や否定先読みアサーションを使ったとしても、うまく行を選択できないか、あるいは複数回実行すると、そのたびに変更されてしまったりする。

とりあえず、grepで書き換えるべきかどうかを判定して、必要なときだけ書き換えるようにしてみた。

- hosts: servers
  vars:
    httpd_conf: /etc/apache2/apache2.conf
  tasks:
    - name: grep %{Session}C
      command: grep '^LogFormat[[:space:]].*%{Session}C.*[[:space:]]combined' {{httpd_conf}}
      register: grep
      ignore_errors: True
      failed_when: False
      changed_when: False
    - name: change httpd.conf
      lineinfile:
        backup=yes
        backrefs=yes
        dest={{httpd_conf}}
        state=present
        regexp="^(LogFormat\s+\")(.*)(\"\s+combined)$"
        line="\1\2 \\\\\"%{Session}C\\\\\" \3"
      when: grep.rc == 1
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2