Ansible | template モジュール

Ansible の tamplate モジュールで実行時に変数が展開されることを確認した。

設定

テンプレートファイル sample.j2 に変数を展開してコピーする。

sample.j2

1
2
3
4
Hello, world
====
{{ sample_var }}
====

playbook.yml

1
2
3
4
5
6
7
8
9
- hosts: test-hosts
tasks:
- name: template copy sample file
become: true
template: src=./sample.j2
dest=/tmp/template.txt
owner=root
group=root
mode=0644

実行

1
2
3
4
5
6
7
8
9
10
11
12
13
$ ansible-playbook -i hosts playbook.yml -K
SUDO password:

PLAY [test-hosts] **************************************************************

TASK [setup] *******************************************************************
ok: [192.168.1.201]

TASK [template copy sample file] ***********************************************
changed: [192.168.1.201]

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

確認

``shell
$ cat /tmp/template.txt
Hello, world
====
hoge
====

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

冪等性を確認するために、再度実行する。

```shell
$ ansible-playbook -i hosts playbook.yml -K
SUDO password:

PLAY [test-hosts] **************************************************************

TASK [setup] *******************************************************************
ok: [192.168.1.201]

TASK [template copy sample file] ***********************************************
ok: [192.168.1.201]

PLAY RECAP *********************************************************************
192.168.1.201 : ok=2 changed=0 unreachable=0 failed=0

changed=0 なので、ファイルのコピーは行われていないので、冪等性が守られている。