lineinfile モジュールについて
lineinfile モジュールを使用することで管理対象機器側のファイルについて以下のような操作ができます。
- 指定した内容の行を指定した位置に追加
- 指定した内容の行の削除
- 正規表現での行のマッチング
主なパラメータ
パラメータ | 必須 | 選択肢/デフォルト | 説明 |
path | ● | 操作対象ファイルのパスを指定 | |
line | state: present と組み合わせて使用する [挿入/置換]操作後の行内容 | ||
insertafter | ・EOF ← ・*regex* | state: present と組み合わせて使用する 検索対象行の正規表現を指定し、最後にヒットした行の後に行内容を挿入する EOF と指定すると最終行の意味になる | |
insertbefore | ・EOF ← ・*regex* | state: present と組み合わせて使用する 検索対象行の正規表現を指定し、最後にヒットした行の前に行内容を挿入する EOF と指定すると最終行の意味になる | |
firstmatch | ・no ← ・yes | insertafter/insertbefore で最初にヒットした行を対象とする場合は yes を指定 | |
regexp | [置換/削除]対象となる行の正規表現を指定 ・state: present ⇒ 置換 ・state: absent ⇒ 削除 ※複数行マッチする場合は最後にマッチした行が対象となる | ||
state | ・absent ・present ← | ・absent ⇒ 行削除 ・present ⇒ 行追加 | |
create | ・no ← ・yes | state: present と組み合わせて使用する path が存在しない場合、ファイルを作成する |
使用例
作業環境
- CentOS 8.0
- Python 3.7.7
- Ansible 2.9.6
行挿入
- /root/test.conf の「bbbb:」項目の後に 「cccc: 3」 を挿入する
■ /root/test.conf
aaaa: 1
bbbb: 2
dddd: 4
eeee: 5
ffff: 6
■ playbook.yml
- hosts: all
become: yes
tasks:
- name: lineinfile test
lineinfile:
path: /root/test.conf
line: 'cccc: 3'
insertafter: 'bbbb: .*'
■ Ansible 実行後の /root/test.conf
aaaa: 1
bbbb: 2
cccc: 3
dddd: 4
eeee: 5
ffff: 6
行置換
- /root/test.conf の「dddd:」項目の行を 「dddd: 40」 に置換する
■ /root/test.conf
aaaa: 1
bbbb: 2
dddd: 4
eeee: 5
ffff: 6
■ playbook.yml
- hosts: all
become: yes
tasks:
- name: lineinfile test
lineinfile:
path: /root/test.conf
line: 'dddd: 40'
regexp: 'dddd: .*'
■ Ansible 実行後の /root/test.conf
aaaa: 1
bbbb: 2
dddd: 40
eeee: 5
ffff: 6
行削除
- /root/test.conf の「dddd:」項目の行を削除する
■ /root/test.conf
aaaa: 1
bbbb: 2
dddd: 4
eeee: 5
ffff: 6
■ playbook.yml
- hosts: all
become: yes
tasks:
- name: lineinfile test
lineinfile:
path: /root/test.conf
regexp: 'dddd: .*'
state: absent
■ Ansible 実行後の /root/test.conf
aaaa: 1
bbbb: 2
eeee: 5
ffff: 6
行追加(最終行)
- /root/test.conf の最終行に「gggg: 7」を追加する
■ /root/test.conf
aaaa: 1
bbbb: 2
eeee: 5
ffff: 6
■ playbook.yml
- hosts: all
become: yes
tasks:
- name: lineinfile test
lineinfile:
path: /root/test.conf
line: 'gggg: 7'
insertafter: EOF
■ Ansible 実行後の /root/test.conf
aaaa: 1
bbbb: 2
eeee: 5
ffff: 6
gggg: 7
―――――――――――――