1)创建目录
cd /etc/ansible/
mkdir roles/install_docker/{tasks,handlers,vars} -pv
mkdir roles/install_compose/{tasks,handlers,vars} -pv
2)安装docker的任务文件
# cat roles/install_docker/tasks/main.yml
- name: install depend
yum: name={{ item }} state=present
with_items:
- yum-utils
- device-mapper-persistent-data
- lvm2
- name: install ali epel
shell: yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
- name: install docker
yum: name=docker-ce state=present
- name: start docker
service: name=docker state=started enabled=true
- name: copy file
template: src=daemon.json dest=/etc/docker/daemon.json
tags: conf
notify:
- restart docker
3)当配置文件更新触发服务重启文件
# cat roles/install_docker/handlers/main.yml
- name: restart docker
service: name=docker state=restarted enabled=true
4)模板文件
# cat roles/install_docker/templates/daemon.json
{
"registry-mirrors": ["https://ui5lsypg.mirror.aliyuncs.com"]
}
5)安装docker-compose的任务文件
# cat roles/install_compose/tasks/main.yml
- name: install com
shell: sudo curl -L https://mirrors.aliyun.com/docker-toolbox/linux/compose/1.17.0/docker-compose-Linux-x86_64 > /usr/local/bin/docker-compose
- name: sudo chmod +x /usr/local/bin/docker-compose
shell: sudo chmod +x /usr/local/bin/docker-compose
6)主入口文件
# cat site.yml
---
- hosts: "{{ host }}"
gather_facts: false
remote_user: root
roles:
- { role: install_compose, tags: "compose"}
- install_docker
7)运行
ansible-playbook site.yml -e host=192.168.0.194 --syntax-check #检查语法
ansible-playbook site.yml -e host=192.168.1.194
说明:
roles:
- { role: install_compose, tags: "compose"}
- install_docker
ansible-playbook site.yml -e host=192.168.1.194 默认都会运行两个角色, install_compose 和install_docker
ansible-playbook site.yml -e host=192.168.1.194 --tags="compose" , 只会运行compose角色, 而不会运行install_docker 角色