ksaitoの日記

日々試したことの覚え書き

ansibleのdocker connection plugin

移転しました。

自動的にリダイレクトします。

ansibleのdocker connection plugを使ってみました。

環境

ansibleとdockerのバージョンは、下記の通りです。

$ ansible --version
ansible 2.0.1.0
  config file = /home/vagrant/.ansible.cfg
  configured module search path = Default w/o overrides
(0)21:07:12 vagrant@vivid64$ 
(0)21:07:12 vagrant@vivid64$ docker version
Client:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   a34a1d5
 Built:        Fri Nov 20 13:16:54 UTC 2015
 OS/Arch:      linux/amd64

Server:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   a34a1d5
 Built:        Fri Nov 20 13:16:54 UTC 2015
 OS/Arch:      linux/amd64
$ 

最初は、手動でコンテナを起動します。 コンテナ作成時に--nameオプションで名前を指定します。ansibleは、この名前でコンテナを識別します。

$ docker run --name target -td ubuntu:14.04 bash
909d3137c6d28f02ed261bba2974dc2ed1d50a7313a2843a6da2cec09ab8f61b
(0)20:54:49 vagrant@vivid64$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
909d3137c6d2        ubuntu:14.04        "bash"              3 seconds ago       Up 3 seconds                            target
$

docker connection pluginは、python必須なのでコンテナにpythonをインストールします。

$ docker exec target "apt-get install -y python"

疎通確認

ansibleコマンドで疎通を確認します。

-c dockerを指定することで通常sshで接続するところをdocker execでコマンドを実行します。

$ ansible -i "target," target -c docker -a hostname
target | SUCCESS | rc=0 >>
909d3137c6d2

$ 

playbookの準備

下記のようなplaybookを準備します。

$ cat sample.yml 
---
- name: start up docker container
  hosts: localhost
  tasks:
    - add_host: name=target

- name: configure container
  hosts: target
  connection: docker
  tasks:
    - command: id
      register: id_result
    - debug: var=id_result.stdout
      when: id_result | success
$ 

実行

$ ansible-playbook -i "localhost," sample.yml 

PLAY [start up docker container] ***********************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [add_host] ****************************************************************
changed: [localhost]

PLAY [configure container] *****************************************************

TASK [setup] *******************************************************************
ok: [target]

TASK [command] *****************************************************************
changed: [target]

TASK [debug] *******************************************************************
ok: [target] => {
    "id_result.stdout": "uid=0(root) gid=0(root) groups=0(root)"
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0   
target                     : ok=3    changed=1    unreachable=0    failed=0   

$