hidemium's blog

日々学んだことをアウトプットする。

Ansibleのディレクトリ構成とロールの作成について

前回、AnsibleのVMwareモジュールについてインストールしてみましたが、利便性を高める方法について書いてみようと思います。小規模環境を想定して書いています。

構成

  • vCenter 7.0 U2
  • ESXi 7.0 Update 2
  • Ubuntu 20.04 (Ansible実行環境)

Ansibleのディレクトリ構成について

前回はシンプルに動作確認を行うために、インベントリファイルとplaybookのみの構成でした。AnsibleのSample directory layoutという構成をベースに作り替えていきたいと思います。

Sample Ansible setup — Ansible Documentation

Sample directory layoutは、以下のような構成となっています。

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1.yml             # here we assign variables to particular groups
   group2.yml
host_vars/
   hostname1.yml          # here we assign variables to particular systems
   hostname2.yml

library/                  # if any custom modules, put them here (optional)
module_utils/             # if any custom module_utils to support modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # main playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier
tasks/                    # task files included from playbooks
    webservers-extra.yml  # <-- avoids confusing playbook with task files

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
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

playbookとロールの作成

このSample directory layoutを一括で作成する公式ツールは見当たらなかったので、mkdirで作成していきます。

$ cd ~/ansible-vmware
$ mkdir {group_vars,host_vars,roles}

次に、inventoryを定義しておきます。仮想マシンhomelab_vm グループとして定義しておきます。

$ cd ~/ansible-vmware
$ vi hosts
---
[homelab_vm]
<VM name>

次に、playbookを定義しておきます。 homelab_vm グループのホストに対して、 guest_info というロールを実行するように定義します。

$ cd ~/ansible-vmware
$ vi pb_guest_info.yml
---
- hosts: homelab_vm
  gather_facts: false
  roles:
    - guest_info

次にロールを書いていきます。前回の仮想マシンの情報を取得する処理をベースにしていきます。

まず、rolesに guest_info というロールを作成します。ロールの作成はansible-galaxyコマンドを利用します。

$ cd ~/ansible-vmware
$ cd roles
$ ansible-galaxy init guest_info
$ tree -L 2
.
└── guest_info
    ├── defaults
    │   └── main.yml
    ├── files
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── main.yml
    ├── README.md
    ├── tasks
    │   └── main.yml
    ├── templates
    ├── tests
    │   ├── inventory
    │   └── test.yml
    └── vars
        └── main.yml

taskのmain.ymlを編集します。

$ cd guest_info
$ vi task/main.yml
---
- name: Gather info for VM
  community.vmware.vmware_guest_info:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    validate_certs: no
    datacenter: "{{ datacenter_name }}"
    name: "{{ inventory_hostname }}"
  delegate_to: localhost
  register: result

- debug: var=result

group_varsにvCenterの情報を記載していきます。Ansible Vaultのベストプラクティスに沿って、Vaultで暗号化された変数として vault_ を変数の頭につけます。

General tips — Ansible Documentation

$ cd ~/ansible-vmware/group_vars
$ mkdir all
$ cd all
$ vi main.yml 
vcenter_username: "{{ vault_vcenter_username }}"
vcenter_password: "{{ vault_vcenter_password }}
$ vi vault.yml
---
vault_vcenter_username: vCenter username
vault_vcenter_password: password
$ ansible-vault encrypt vault.yml
New Vault password: 
Confirm New Vault password: 
Encryption successful

Ansible Vaultのパスワードを毎回入力することが大変なため、 パスワードを記載したファイルを定義しておきます。

$ cd ~/ansible-vmware
$ vi .vault_password
password
$ vi ansible.cfg
[defaults]
vault_password_file = .vault_password

次に、taskの実行に必要な変数について homelab_vm グループの情報として取得できるように、group_vars配下にフォルダを作成して記載していきます。

$ cd ~/ansible-vmware/group_vars
$ mkdir homelab_vm
$ cd homelab_vm
$ vi main.yml
---
vcenter_hostname: vCenter Name
datacenter_name: Datacenter Name

最後に、playbookを実行できるか確認します。

$ ansible-playbook -i hosts pb_guest_info.yml
PLAY [homelab_vm] ************************************************************************************************************************************************************************

TASK [guest_info : Gather info for VM] ***************************************************************************************************************************************************
ok: [VM name -> localhost]

TASK [guest_info : debug] ****************************************************************************************************************************************************************
ok: [VM name] => {
    "result": {
        "changed": false,
        "failed": false,
        "instance": {
            "advanced_settings": {
                "ethernet0.pciSlotNumber": "192",
~ 中略 ~
            "vimref": "vim.VirtualMachine:vm-2028",
            "vnc": {}
        }
    }
}

PLAY RECAP *******************************************************************************************************************************************************************************
VM name                   : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

必要なファイルが増えましたが、全体構成として以下のようになりました。

$ tree -L 4
.
├── ansible.cfg
├── group_vars
│   ├── all
│   │   ├── main.yml
│   │   └── vault.yml
│   └── homelab_vm
│       └── main.yml
├── host_vars
├── hosts
├── pb_guest_info.yml
├── requirements.yml
├── roles
│   └── guest_info
│       ├── defaults
│       │   └── main.yml
│       ├── files
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── README.md
│       ├── tasks
│       │   └── main.yml
│       ├── templates
│       ├── tests
│       │   ├── inventory
│       │   └── test.yml
│       └── vars
│           └── main.yml
└── venv
    ├── bin
~ 中略 ~