LoginSignup
1
2

More than 1 year has passed since last update.

Ansible の handler を使ってみる

Last updated at Posted at 2018-07-03

handler とは

他の処理にフックして、処理を走らせることが出来る。
他の処理で changed のイベントが起こった時に、一度だけ、最後に handler 処理が走る。

タスク側では notify を設定し、 handler側では listen でそれを待ち受ける。

playbook の例

handler.yml
---
- hosts: localhost

  handlers:
    - debug:
        msg: i am the handler
      listen: hook to me
    - debug:
        msg: you are the handler
      listen: hook to you
    - debug:
        msg: he is the handler
      listen: hook to him

  tasks:
    - debug:
        msg: message
      changed_when: true
      notify: hook to me
    - debug: 
        msg: try to hook to me
      changed_when: true
      notify: hook to me  # hook twice but run handler once
    - debug:
        msg: try to hook to you
      changed_when: true
      notify: hook to you
    - debug:
        msg: try to hook to him
      changed_when: false # no changed no hook
      notify: hook to him

実行例

tasks が終わった後に、二種類の handler が実行されているのが分かる。
(playbookでは三回notifyしているが、同じ種類のhandlerが走るのは一回だけ。changed でない場合もhandler処理は走らない)

$ ansible-playbook handler.yml


PLAY [example] *****************************************************************

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

TASK [debug] *******************************************************************
changed: [localhost] => {
    "msg": "message"
}

TASK [debug] *******************************************************************
changed: [localhost] => {
    "msg": "try to hook to me"
}

TASK [debug] *******************************************************************
changed: [localhost] => {
    "msg": "try to hook to you"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "try to hook to him"
}

RUNNING HANDLER [debug] ********************************************************
ok: [localhost] => {
    "msg": "i am the handler"
}

RUNNING HANDLER [debug] ********************************************************
ok: [localhost] => {
    "msg": "you are the handler"
}

PLAY RECAP *********************************************************************
localhost                  : ok=7    changed=3    unreachable=0    failed=0   


環境

  • ansible 2.6.0

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
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
1
2