LoginSignup
15
11

More than 1 year has passed since last update.

Ansible | Docker で Ansible の動作環境を作る

Last updated at Posted at 2017-06-30

Docker側の用意

Docker イメージの作成

この例では、次の条件でイメージを作る。

  • pythonが使える ( Ansble の実行環境ため )
  • sshで直接接続ができる
  • ssh ユーザー: root
  • ssh パスワード: screencast
Dockerfile
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

# FOR Ansible
RUN apt-get update && apt-get -y install python

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
$ docker build -t eg_sshd .

( Dockerize an SSH service | Docker Documentation を参考)

Dockerコンテナを走らせる

$ docker run -d -p 30000:22 --name test_sshd eg_sshd

Ansibleの実行

ファイル作成

手元にインベントリファイルを作成する。
( 接続先のIPはDockerの構築環境による )

inventory
[example]
127.0.0.1

[example:vars]
ansible_ssh_user=root
ansible_ssh_port=30000

( Ansible 2.0 以降では ansible_user などの短い書き方が推奨されているので注意 => Inventory — Ansible Documentation )

環境変数の設定

初回アクセス時の質問 ( known_inventory にフィンガープリントを記録する処理 ) を無効化しておく。

$ export ANSIBLE_HOST_KEY_CHECKING=False

コマンド実行

Dockerコンテナに適当なファイルを作成してみる。

$ ansible -i inventory example -m shell -a 'touch example.txt' --ask-pass
  • -i inventory
    • インベントリファイルの指定
  • -m shell
    • 「ansible の shell モジュールを実行する」という指定 (省略できる)
  • -a 'touch example.txt'
    • モジュールに渡す引数 ( この例の場合は、実行するコマンドの内容 )
  • --ask-pass
    • パスワードを手入力するためのフラグ

コマンドを実行するとパスワードを聞かれるので、設定したもの ( screencast ) を入力する。

確認

docker コンテナにファイルが作成されているのが分かる。

$ docker exec -it test_sshd /bin/bash
root@91625cd5dda0:/# ls ~/
example.txt

パスワードを聞かれないようにする場合

ホスト側に sshpass をインストールする

(Macの場合)

brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

( Installing SSHPass )

手元からコンテナにsshアクセスして FingerPrint を作っておく

ssh root@127.0.0.1 -p 30000

image.png

yes と答えて exit する。

インベントリファイルにパスワードを書く

たぶん非推奨。
( ちゃんとやる場合は鍵交換とかしよう )

inventory
[example]
127.0.0.1

[example:vars]
ansible_ssh_user=root
ansible_ssh_port=30000
+ ansible_ssh_pass=screencast

ansibleコマンドを実行する

ansible -i inventory example -m shell -a 'touch example.txt'

環境

  • ansible 1.9.6
  • Docker version 17.03.1-ce, build c6d412e
  • Mac OS Sierra 10.12.4

Docker hub

関連

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

15
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
11