说明
宿主机需要安装Docker和Docker-compose
我们用三台机器
主机名分别为host1、host2和ansible
host1和host2安装python、openssh server
ansible安装openssh server、openssh client、ansible
步骤
按如下目录结构创建文件
.
├── alpine
│ └── Dockerfile
├── ansible
│ └── Dockerfile
└── docker-compose.yml
alpine/Dockerfile内容为
FROM alpine:3.10
RUN echo "http://mirrors.aliyun.com/alpine/latest-stable/main/" > /etc/apk/repositories && \
echo "http://mirrors.aliyun.com/alpine/latest-stable/community/" >> /etc/apk/repositories
RUN apk update && \
apk add --no-cache openssh-server tzdata python3 && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
sed -i "s/#PermitRootLogin.*/PermitRootLogin yes/g" /etc/ssh/sshd_config && \
ssh-keygen -t rsa -P "" -f /etc/ssh/ssh_host_rsa_key && \
ssh-keygen -t ecdsa -P "" -f /etc/ssh/ssh_host_ecdsa_key && \
ssh-keygen -t ed25519 -P "" -f /etc/ssh/ssh_host_ed25519_key && \
echo "root:root" | chpasswd
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
ansible/Dockerfile内容为
FROM alpine:3.10
RUN echo "http://mirrors.aliyun.com/alpine/latest-stable/main/" > /etc/apk/repositories && \
echo "http://mirrors.aliyun.com/alpine/latest-stable/community/" >> /etc/apk/repositories
RUN apk update && \
apk add --no-cache openssh-server tzdata ansible openssh && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
sed -i "s/#PermitRootLogin.*/PermitRootLogin yes/g" /etc/ssh/sshd_config && \
ssh-keygen -t rsa -P "" -f /etc/ssh/ssh_host_rsa_key && \
ssh-keygen -t ecdsa -P "" -f /etc/ssh/ssh_host_ecdsa_key && \
ssh-keygen -t ed25519 -P "" -f /etc/ssh/ssh_host_ed25519_key
RUN mkdir -p /etc/ansible && \
echo -e "[dev]\nhost1\nhost2" >/etc/ansible/hosts && \
ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
docker-compose.yml内容为
version: "2.4"
services:
host1:
build: alpine
host2:
build: alpine
ansible:
build: ansible
执行下面的命令构建镜像并启动服务:
docker-compose up -d
进入ansible容器
docker-compose exec ansible sh
执行下面命令:
ssh-copy-id host1
ssh-copy-id host2
会提示输入密码,密码是
root
使用
我们使用ping命令测试一下:
ansible dev -m ping
输出类似下面的信息:
host1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3.7"
},
"changed": false,
"ping": "pong"
}
host2 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3.7"
},
"changed": false,
"ping": "pong"
}
网友评论