LoginSignup
4
2

More than 5 years have passed since last update.

Ansibleでループ中の変数に応じてhandlerを切り替える

Posted at

はじめに

Ansibleで、あるミドルウェアをプロビジョニングするとき、関連する設定ファイルが複数ある場合、with_items等を使ってtemplateモジュールやcopyモジュールで対応すると思います。
その際、notifyでサービスのリロードや再起動などを制御するのが通常のやり方です。

しかし、ミドルウェアによっては、設定ファイルごとに別のhandlerを呼びたいことがあります。

例えばapacheと連携するZabbixなどです。
/etc/zabbix_server.confの更新時にはzabbix-serverを、/etc/httpd/conf.d/zabbix.confの更新時にはapacheをリロードしたいでしょう。

ところが、with_items等で使う変数itemの内容は、notifyで呼ぶhandlers内のタスクでは参照できません。

  notify:
    - reload apache
    - reload middleware

このように複数のhandlerを指定することは可能ですが、この場合、本来middleware本体のみリロードすべきところをapacheまでリロードされてしまいます。

前置きが長くなりましたが、今回はループ処理中の変数の値によって、handlerを切り替える方法をご紹介します。

やること

ループ中の変数にis_apache: Trueが定義されている時はapacheをリロードするhandlerを呼び、それ以外はmiddlewareをリロードするhandlerを呼ぶ

sample

ディレクトリ構成

ディレクトリ構成
site.yml
hosts/inventory_file
host_vars/targethost.yml
roles/
|--middleware/
|  |--tasks/
|  |  |--main.yml
|  |--handlers/
|  |  |--main.yml

Role

notifyの中で変数を評価し、呼ぶhandlerを切り替えます。

roles/middleware/tasks/main.yml
- name: put some middleware config files
  template:
    src: "{{ item.template }}"
    dest: "{{ item.path }}"
    owner: "{{ item.owner | default('root') }}"
    group: "{{ item.group | default('root') }}"
    mode: "{{ item.mode | default('0644') }}"
  with_items: "{{ my_vars.middleware.config_file }}"
  notify: >-
    {%- if item.is_apache == True -%}
    ["reload apache"]
    {%- else -%}
    ["reload middleware"]
    {%- endif -%}

vars

apacheを再起動したい設定ファイルについてはis_apache: Trueを定義しておきます。

host_vars/targethost.yml
---
my_vars:
  middleware:
    config_file:
      - template: middleware.conf.j2
        owner: middleware_user
        group: middleware_group
        mode: '0644'
        path: /path/to/middleware.conf
      - template: middleware_apache.conf.j2
        owner: apache
        group: apache
        mode: '0644'
        path: /path/to/middleware_apache.conf
        is_apache: True

handler

handlerは普通に2つ定義しておきます。

roles/middleware/handlers/main.yml
---
- name: reload apache
  service:
    name: httpd
    state: reloaded
  when: not ansible_check_mode

- name: reload middleware
  service:
    name: middleware
    state: reloaded
  when: not ansible_check_mode

まとめ

これで他と連携するミドルウェアについてもスマートにRoleが定義できると思います。

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