容器技术:Ansible管理Docker(六)
17. Ansible批量容器管理
17.1 环境准备
ansible管理docker集群,需要使用比较新的版本ansible + python3环境。
主机 | 说明 | IP | 软件 |
---|---|---|---|
devops | 管理端 | 10.0.0.71 | python3,docker-compose,ansible,pip3安装setuptools_rust、docker模块 |
docker01 | 被管理端 | 10.0.0.81 | python3,docker-ce,pip3安装docker、docker-compose模块 |
docker02 | 被管理端 | 10.0.0.82 | python3,docker-ce,pip3安装docker、docker-compose模块 |
管理机
- 安装python3、python3-pip、rust
- pip3安装setuptools_rust、docker、ansible、docker-compose模块
yum install -y python3 python3-pip rust
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install setuptools_rust docker ansible docker-compose
pip3 list | egrep 'docker|ansible'
#要有以下模块
ansible 4.10.0
ansible-core 2.11.12
docker 5.0.3
docker-compose 1.29.2
dockerpty 0.4.1
被管理机
- 安装python3、python3-pip、dcoker-ce
- pip3安装docker、docker-compose模块
如果你之前安装过 docker,请先删掉
yum remove docker docker-ce docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine docker*
安装一些依赖
yum install -y yum-utils device-mapper-persistent-data lvm2
也可以安装一下代码补全插件:yum install -y bash-completion bash-completion-extras
下载 repo 文件,并把软件仓库地址替换为镜像站
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sed -i 's+https://download.docker.com+https://mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo
安装docker-ce
yum install docker-ce
配置镜像加速,编辑配置文件
[root@docker01 ~]# cat /etc/docker/daemon.json
{
"registry-mirrors": [
"https://mirror.ccs.tencentyun.com"
]
}
启动docker并设置开机自启
systemctl enable docker
systemctl start docker
yum install -y python3 python3-pip
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install docker docker-compose
pip3 list | egrep 'docker|ansible'
#要有以下模块
docker 5.0.3
docker-compose 1.29.2
dockerpty 0.4.1
17.2 配置密钥认证
生成密钥文件并拷贝到被控端
ssh-keygen
ssh-copy-id -i /root/.ssh/id_rsa.pub 10.0.0.81
ssh-copy-id -i /root/.ssh/id_rsa.pub 10.0.0.82
编写ansible主机清单
[root@devops ~]# mkdir /ans-docker
[root@devops ~]# cat /ans-docker/hosts
[dk]
10.0.0.81
10.0.0.82
测试是否能通过ansible批量管理,没有问题!
17.3 批量管理Docker前最后的配置优化
Ansible环境变量 | |
---|---|
ANSIBLE_PYTHON_INTERPRETER | ansible会默认调用的python解释器,默认python2,指定python3。 |
ANSIBLE_INVENTORY | ansible主机清单默认是/etc/ansible/hosts,修改为当前目录下的hosts文件。 |
[root@devops ~]# cat >> /etc/profile << EOF
> export ANSIBLE_PYTHON_INTERPRETER=/usr/bin/python3
> export ANSIBLE_INVENTORY=./hosts
> EOF
[root@devops ~]# source /etc/profile
就不需要指定hosts文件啦,默认会读取命令执行的当前目录下的hosts!
17.4 Ansible管理Docker
17.4.1 参数
待补充
17.4.2 批量拉取镜像到各主机
例如拉取 nginx:1.22.0-alpine
ansible dk -m docker_image -a 'name="nginx:1.22.0-alpine" source=pull'
作者:YinJay
Email:szgetshell@163.com