Ansible Moleculeから稼働中サーバーを更新する


Moleculeから稼働中サーバーを更新するメリット

普通にansible-playbookコマンドから稼働中サーバーを更新するのではなく、Ansible Moleculeから稼働中サーバーを更新する場合、以下の様なメリットが考えられる

  • サーバーに対しても開発/テスト時と同じコマンド体系で反映が可能(シナリオを分ける前提)
    • サーバーに対しても開発/テスト時と同様にverifyを実施可能
    • サーバーに対しても開発/テスト時と同様に冪等性が確保されているかを検証可能
  • playbookの場所を考えなくても良い
    • molecule/default/converge.yml

ちなみにtest kitchenではproxyドライバーに相当

実装例

delegatedドライバーにより容易に実装可能
接続先情報のソースは、ここでは見通し良く、かつ連携を容易にする為に、molecule.ymlのplatforms下に置くことにする。

テンプレートの作成

roleごと

$ molecule init role ROLENAME --driver-name delegated

もしくはmolecule directory下のみ

$ molecule init scenario --driver-name delegated

によりテンプレートを作成

molecule
 └── default
     ├── INSTALL.rst
     ├── converge.yml
     ├── molecule.yml
     └── verify.yml

molecule.ymlの設定例

molecule/default/molecule.yml
---
dependency:
  name: galaxy
driver:
  name: delegated
platforms:

- name: host1
  address: xx.xx.xx.xx
  user: root
  port: 22
  identity_file: "~/.ssh/id_rsa"

- name: host2
  address: xx.xx.xx.xx
  user: root
  port: 22
  identity_file: "~/.ssh/id_rsa"

provisioner:
  name: ansible
verifier:
  name: ansible

create.ymlの例

molecule/default/create.yml
---
- name: Create
  hosts: localhost
  connection: local
  gather_facts: false
  no_log: "{{ molecule_no_log }}"
  tasks:

  - set_fact:
      instance_conf: "{{ instance_conf + [ { 
        'instance': item.name,
        'address': item.address,
        'user': item.user, 
        'port': item.port, 
        'identity_file': item.identity_file
        } ] }}"
    vars:
      instance_conf: []
    loop: "{{ molecule_yml.platforms }}"

  - name: Dump instance config
    copy:
      content: |
        # Molecule managed

        {{ instance_conf | to_json | from_json | to_yaml }}
      dest: "{{ molecule_instance_config }}"
  • 接続情報を設定
  • set_factにてname:をinstance:に置き換えている
    • 元データにinstance:も合わせて記載しておけば、set_fact無しで直接molecule_yml.platformsを書き込んでも良い
  • ちなみに"{{ molecule_instance_config }}"は、~/.cache/molecule/ロール名/シナリオ名/instance_config.yml
  • | to_json | from_json は昔の障害対応の名残?

これだけで稼働中サーバーに対して接続可能となる