ansible 部署 docker

准备工作

创建roles目录

# mkdir -pv  /data/apps/ansible/roles/docker/{files,tasks,handlers,templates,vars}

hosts

[ubuntu]
172.16.18.31 ansible_ssh_port=22  ansible_ssh_user=ubuntu hostname=app-01

测试连通性

# ansible ubuntu -m ping
172.16.18.247 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    }, 
    "changed": false, 
    "ping": "pong"
}

创建角色相关文件

tasks/main.yml

- include: group.yml
- include: copy.yml
- include: conf.yml
- include: service.yml

tasks/group.yml

- name: create docker group
  group: 
    name: docker
    state: present
    gid: 998

tasks/copy.yml

- name: copy docker to remote ubuntu22.04
  copy: 
    src: docker/
    dest: /usr/bin/
    mode: u+x
- name: copy docker-compose to remote ubuntu22.04
  copy: 
    src: docker-compose
    dest: /usr/local/sbin/
    mode: u+x

tasks/conf.yml

- name: Create a directory if it does not exist
  ansible.builtin.file:
    path: /etc/docker
    state: directory
- name: docker daemon.json
  copy: 
    src: daemon.json 
    dest: /etc/docker/daemon.json

tasks/service.yml

- name: service containerd.service script
  copy: 
    src: containerd.service 
    dest: /lib/systemd/system/containerd.service
- name: service docker script
  copy: 
    src: docker.service  
    dest: /lib/systemd/system/docker.service
- name: service docker.socket
  copy: 
    src: docker.socket 
    dest: /lib/systemd/system/docker.socket
- name: start containerd.service
  systemd: 
    name: containerd.service
    state: started 
    enabled: yes
- name: start docker.socket
  systemd: 
    name: docker.socket
    state: started 
    enabled: yes
- name: start docker service
  systemd: 
    name: docker.service 
    state: started 
    enabled: yes

查看相关文件

# tree /data/apps/ansible/roles/docker/
/data/apps/ansible/roles/docker/
├── files
│   ├── containerd.service
│   ├── daemon.json
│   ├── docker
│   │   ├── containerd
│   │   ├── containerd-shim-runc-v2
│   │   ├── ctr
│   │   ├── docker
│   │   ├── dockerd
│   │   ├── docker-init
│   │   ├── docker-proxy
│   │   └── runc
│   ├── docker-23.0.2.tgz
│   ├── docker-compose
│   ├── docker.service
│   └── docker.socket
├── handlers
├── tasks
│   ├── conf.yml
│   ├── copy.yml
│   ├── group.yml
│   ├── main.yml
│   └── service.yml
├── templates
└── vars

6 directories, 19 files

playbook调用角色

docker_roles.yml

- hosts: ubuntu
  remote_user: ubuntu
  become: yes
  roles:
   - role: docker

运行playbook

# ansible-playbook docker_roles.yml
posted @ 2023-04-03 16:00  小吉猫  阅读(152)  评论(0编辑  收藏  举报