LoginSignup
16
14

More than 5 years have passed since last update.

ansible のrole まとめ

Last updated at Posted at 2016-09-18

intro

ansible でファイルを使い回す方法に include がある。これは、 task, handler (task の一種), play1 を他のファイルから読み込める。

一方で、roles を使うことで一つのファイルでなく、タスクや変数・ハンドラごとのファイルをまとめて読み込める。

使い方

ディレクトリが以下のような構成だとする。

ansible.directory
main.yml
roles/
    common/
        files/
        templates/
        tasks/
        handlers/
        vars/
        defaults/
        meta/
main.yml
--
- hosts: webservers
  roles:
     - common

このとき、main.yml には以下が追加される.
* roles/common/tasks/main.yml のタスク
* roles/common/handlers/main.yml ハンドラ
* roles/common/var/main.yml の変数
* roles/common/default/main.yml の変数
* roles/common/meta/main.yml のrole dependencies 2
(これらのファイルでは、roles/common/files のファイルを、copy,script,template,include タスクで、相対パスも絶対パスもなく指定できる)

オプション

変数を設定したいとき

main.yml
---
- hosts: servers
  roles:
     - { role: some_role, dir: 'opt/a/', app_port: 500 }

ある条件を満たすときのみ role

main.yml
---
- hosts: servers
  roles:
     - { role: some_role, when: "ansible_os_family == 'RedHat'" }

タグの割り当て

main.yml
---
- hosts: servers
  roles:
     - { role: some_role, tags: ["bar", "baz"] }

注意点

タスクとの共用

すべての tasks:roles:の後に処理される。 それより前にタスクを処理したいなら、pre_tasks:を使うこと。

Role Dependencies

ロールの中から他のロールを読み込むために、meta/main.yml に依存関係を記述できる。

meta/main.yml
---
dependencies:
  - { role: common, some_parameter: 3 }
  - { role: apache, apache_port: 80 }
  - { role: '/path/to/common/roles/foo', x: 1 }

読み込まれたロールは読み込んでいるロールより先に実行される.
同じロールが以前に実行されていた場合はそのロールは実行されない. ただし meta/main.ymlallow_duplicates: yes を記述すれば、再度実行される.

ref


  1. あるホストグループに対する処理の流れを記述したもの(task などの列) 

  2. version 1.3 から 

16
14
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
16
14