🌠

Ansibleのロール(Role)を作る

2022/11/04に公開

Ansible推奨のディレクトリ構成が気に入らないので、俺々構成をメモしておく。

Ansible推奨のディレクトリ構成

AnsibleドキュメントのDirectory Layoutには以下の通り掲載されている。

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role

また別の例としては以下の通り。

roles/
    common/
    webtier/
    monitoring/
    fooapp/

上記のようにインストール先の種類でRoleを分けていると「JavaをインストールするTaskって、どこに入ってたっけ?」となる。

おすすめのディレクトリ構成

Directory Layout

こんな感じ。

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
    java/                 # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
    httpd/                 # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
	    
hosts-production           # inventory file for production servers
hosts-staging              # inventory file for staging environment

group_vars/
   group1.yml             # group_varsは何かの時に使った記憶/残しておく
   group2.yml
host_vars/
   ***                    # ホストの設定はほとんどインベントリに書くのでhost_varsは不要

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

site.yml からの参照

site.yml は呼び出すRoleを指定するのみ。

---
- name: ansible
  hosts: all
  connection: ssh
  gather_facts: false
  roles:
    - common
    - java
    - httpd

Roleに指定する細かい設定は変数化して、すべてインベントリのホスト毎の設定を参照する。


ansible galaxy に公開するとなるとディレクトリ構成はまた変わってくるので、それはまた別のお話。

Discussion