7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ansible Advent Calendar 2020

Day 14

varsに潜む罠

Last updated at Posted at 2020-12-13

やりたいこと

my_dateに時刻を格納して一意のキーとして利用としたい。
だが!
以下のように my_dateの定義方法(varsset_fact)次第で挙動が異なっていたので、紹介したいと思います。
ちなみにvarsのみならず、group_vars、host_vars、vars_filesも同様な挙動を確認しています。
シーンによっては再帰的に利用できていいかもしれない。

vars_my_date.yml
- name: Test playbook
  hosts: localhost
  connection: local
  gather_facts: False
  vars:
    # 時間を取得
    my_date: "{{ lookup('pipe', 'date +%s') }}"
  tasks:
    - debug: msg="{{ my_date }}"
    - pause: seconds=5
    - debug: msg="{{ my_date }}"

1回目(1606815454)と2回目(1606815459)の実行結果でpauseの5秒があります。
つまり、代入したmy_dateを呼び出すたびにその値を再評価している動きになっています。

実行結果
TASK [debug] ********************************
Tuesday 01 December 2020  18:37:34 +0900 (0:00:00.120)       0:00:00.120 ****** 
ok: [localhost] => {
    "msg": "1606815454"
}

TASK [pause] ********************************
Tuesday 01 December 2020  18:37:34 +0900 (0:00:00.037)       0:00:00.157 ****** 
Pausing for 5 seconds
(ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort)
ok: [localhost]

TASK [debug] ********************************
Tuesday 01 December 2020  18:37:39 +0900 (0:00:05.013)       0:00:05.171 ****** 
ok: [localhost] => {
    "msg": "1606815459"
}

set_factで定義したらどうなるか?

set_fact_my_date.yml
- name: Test playbook
  hosts: localhost
  connection: local
  gather_facts: False
  tasks:
    - set_fact:
        my_date: "{{ lookup('pipe', 'date +%s') }}"

    - debug: msg="{{ my_date }}"
    - pause: seconds=5
    - debug: msg="{{ my_date }}"

1、2回目の実行結果は1606815486であり、変わっていないことがわかります。

実行結果

TASK [debug] ********************************
Tuesday 01 December 2020  18:38:07 +0900 (0:00:00.038)       0:00:00.160 ****** 
ok: [localhost] => {
    "msg": "1606815486"
}

TASK [pause] ********************************
Tuesday 01 December 2020  18:38:07 +0900 (0:00:00.028)       0:00:00.188 ****** 
Pausing for 5 seconds
(ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort)
ok: [localhost]

TASK [debug] ********************************
Tuesday 01 December 2020  18:38:12 +0900 (0:00:05.014)       0:00:05.203 ****** 
ok: [localhost] => {
    "msg": "1606815486"
}
7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?