mmag

ハマったことメモなど

dockerコンテナにansibleを適用する

ディレクトリ構成

Best Practicesのこの辺りを参考に。

.
├── Dockerfile
├── docker-compose.yml
├── hosts
├── requirements.txt
├── roles
│   └── common
│       ├── tasks
│       │   └── main.yml
│       └── templates
│           └── we_are_the.txt.j2
├── site.yml
└── web.yml

Dockerコンテナ

# docker-compose.yml

web:
  build: .
  privileged: true
  command: /sbin/init
  container_name: web
# Dockerfile

FROM ubuntu:xenial

RUN apt-get update
RUN apt-get install -y python  # ansibleの適用先にpythonが必要らしい

ここでdocker-compose up -dするとwebコンテナが立ち上がる。

$ docker-compose up -d
...
$ docker-compose ps
Name    Command     State   Ports
---------------------------------
web    /sbin/init   Up

ansible

requirements.txtは以下。pip install -r requirements.txtで必要なものをインストール。もしかしたら余計なものが入ってるかも。ちなみにpythonのバージョンは2.7.12。

ansible==2.1.0.0
docker-compose==1.7.1
docker-py==1.8.1

エントリポイントなymlは個別のplaybookを読んでるだけ。

# site.yml

---
- include: web.yml

個別のplaybookでroleをいくつか読む。今回は1個。

# web.yml

---
- hosts: web
  connection: docker
  roles:
    - common
  vars:
    - we_are_the: world

commonでやるのは、適当なファイルを1つ送り込むことだけ。

# roles/common/tasks/main.yml

---
- name: put example file
  template: src=templates/we_are_the.txt.j2 dest=/etc/we_are_the.txt

テンプレートではweb.ymlで設定した変数を使ってる。

{# roles/common/templates/we_are_the.txt.j2 #}

{{ we_are_the }}

あとはinventryにコンテナ名を列挙しする。

[container]
web

適用。

$ ansible-playbook -i hosts site.yml

適用結果。

$ docker exec -it web /bin/bash
root@ab4fcb3eb1b7:/# cat /etc/we_are_the.txt
world

所感

pythonもansibleも初心者だけどなんとかなりそう。規模が大きくなっても、触るのはほぼyamlだけっぽいのでpython力はそれほど問われないはず。どれだけyamlがカオスになっていくのかは未知数。

itamaeを触った後なので変な感じがしたのだろうけど、こんな認識で合ってるのかな?

  • itamaeではroleとcookbookが1対多
  • ansibleではplaybookとroleが1対多

あと、web.ymlconnection: dockerが入り込んできていて、開発環境はdocker、本番環境にはsshで、とか分けたい場合なんかはちょっと工夫が必要そう。 こちらのQiitaを読むと何かわかるのかも。