docker
Ansible

Dockerコンテナにssh接続してAnsibleを試す

良い子はコンテナにssh接続なんてしてはいけないヨ。実験だからね。

コンテナを起動してsshサーバー入れる。rootパスワードも変えておく。

$ docker run --rm -i -t docker.io/centos:7.3.1611 /bin/bash
# yum install openssh-server
# useradd ymko
# passwd ymko
# passwd root

sshサーバーが起動しないのは暗号キーが生成されていないため

# /usr/sbin/sshd -D
Could not load host key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Could not load host key: /etc/ssh/ssh_host_ed25519_key
# ssh-keygen -A
# /usr/sbin/sshd -D

ssh-copy-idでsshが通るように公開鍵を登録
できないのはホストの.ssh/known_hostsに既に書かれているので削る

$ ssh-copy-id 172.17.0.2
/usr/bin/ssh-copy-id: ERROR: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR: @    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
ERROR: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR: IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
ERROR: Someone could be eavesdropping on you right now (man-in-the-middle attack)!
ERROR: It is also possible that a host key has just been changed.
ERROR: The fingerprint for the RSA key sent by the remote host is
ERROR: SHA256:
ERROR: Please contact your system administrator.
ERROR: Add correct host key in /home/ymko/.ssh/known_hosts to get rid of this message.
ERROR: Offending RSA key in /home/ymko/.ssh/known_hosts:6
ERROR: RSA host key for 172.17.0.2 has changed and you have requested strict checking.
ERROR: Host key verification failed.

接続OK。rootも通す。

$ ssh-copy-id 172.17.0.2
The authenticity of host '172.17.0.2 (172.17.0.2)' can't be established.
ECDSA key fingerprint is SHA256:
ECDSA key fingerprint is MD5:40:
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
ymko@172.17.0.2's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '172.17.0.2'"
and check to make sure that only the key(s) you wanted were added.

$ ssh 172.17.0.2
[ymko@fc8b90a03429 ~]$ logout
Connection to 172.17.0.2 closed.

$ ssh-copy-id root@172.17.0.2

ansibleをセットアップ

$ python36 -m venv venv
(venv) $ source venv/bin/activate
(venv) $ pip install ansible

hostファイルを作る

$ cat hosts
[container]
172.17.0.2

-u rootとすればrootで実行される

$ ansible -i hosts all -m ping
172.17.0.2 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
$ ansible  -i hosts all -a "id"
172.17.0.2 | SUCCESS | rc=0 >>
uid=1000(ymko) gid=1000(ymko) groups=1000(ymko)
$ ansible -u root -i hosts all -a "id"
172.17.0.2 | SUCCESS | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)

参考

Dockerで立てたコンテナにsshで接続する - $shibayu36->blog;
https://blog.shibayu36.org/entry/2013/12/07/233510
Ubuntu 16.04 LTS ServerでSSHのホストキーが自動生成されない - Qiita
https://qiita.com/xeres/items/6a32729916b07b37ea68
ansibleを使ってみる — そこはかとなく書くよん。
http://tdoc.info/blog/2013/04/20/ansible.html