LoginSignup
10
4

More than 5 years have passed since last update.

Ansibleでファイルの一部をコメントアウトする

Posted at

lineinfilebackrefs を使うのだがあまり記事がなかったので。

やりたいこと

/etc/sudoers
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

この「root」行をその後のパラメータも保持しつつコメントアウトしたい

/etc/sudoers
## Allow root to run any commands anywhere
#root    ALL=(ALL)       ALL  ← スペースの数とか保持してコメントアウト

確認環境

# ansible --version
ansible 2.6.4
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]

# cat /etc/redhat-release
CentOS release 6.10 (Final)

NGパターン

1. まるっとベタ定義

playbook.yml
---
- hosts: "web"
  tasks
    - name: "test"
      lineinfile:
        path: "/etc/sudoers"
        state: "present"
        regexp: "^root "
        line: "#root    ALL=(ALL)       ALL"

できるっちゃあ出来るんだけど、スペースの数とかベタ書き。
ちょっとモヤモヤする。

2. 変える部分だけ定義すりゃいいんじゃね

playbook.yml
---
- hosts: "web"
  tasks
    - name: "test"
      lineinfile:
        path: "/etc/sudoers"
        state: "present"
        regexp: "^root "
        line: "#root"

残念ながら「 lineinfile 」の名前のとおり、1行まるっと書換なのでNG.

/etc/sudoers
## Allow root to run any commands anywhere
#root   ← 後ろのパラメータ全部消えた

結論

perlの正規表現的に言えばこうしたい

$line =~ s/^(root.*)$/#$1/;

このグルーピング(丸かっこで囲って$1で参照)をしたい。
答えは lineinfilebackrefs: "yes" を付ける。

playbook.yml
---
- hosts: "web"
  tasks
    - name: "test"
      lineinfile:
        path: "/etc/sudoers"
        state: "present"
        backrefs: "yes"
        regexp: '^(root.*)$'
        line: '#\1'

backrefs をつけることで後から \1 などで参照できる。

ありがちなミスだと YAML では \ をスケープしないといけない。
上記では値をダブルクォート "" ではなく、シングル '' を使うことで対応している。

エビデンス

# grep -A 2 ^'## Allow root to' /etc/sudoers
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

# cat test.yml
---
- hosts: "web"
  tasks:

    - name: "test"
      lineinfile:
        path: "/etc/sudoers"
        state: "present"
        backrefs: "yes"
        regexp: '^(root.*)$'
        line: '#\1'

# ansible-playbook -i hosts -l web test.yml

PLAY [web] *********************************************

TASK [Gathering Facts] *********************************
ok: [192.168.200.230]

TASK [test] ********************************************
changed: [192.168.200.230]

PLAY RECAP *********************************************
192.168.200.230            : ok=2    changed=1    unreachable=0    failed=0

# grep -A 2 ^'## Allow root to' /etc/sudoers
## Allow root to run any commands anywhere
#root   ALL=(ALL)       ALL

:-)

10
4
2

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
10
4