ansible docker - ghdrako/doc_snipets GitHub Wiki
Ansible Docker Modules
Ansible offers several modules to interact with Docker:
docker_container
: Manages Docker containers.docker_image
: Manages Docker images.docker_network
: Manages Docker networks.docker_volume
: Manages Docker volumes.
Pulling a Docker Image
---
- name: Pull NGINX image
hosts: target
tasks:
- name: Ensure NGINX image is present
docker_image:
name: nginx
source: pull
Creating Docker Container
---
- name: Run NGINX container
hosts: target
tasks:
- name: Ensure NGINX container is running
docker_container:
name: webserver
image: nginx
state: started
ports:
- "8080:80"
Managing Docker Networks
---
- name: Manage Docker Network
hosts: target
tasks:
- name: Create custom network
docker_network:
name: custom_network
state: present
- name: Add NGINX container to custom network
docker_container:
name: webserver
networks:
- name: custom_network
Managing Docker Volumes
---
- name: Manage Docker Volume
hosts: target
tasks:
- name: Create custom volume
docker_volume:
name: custom_volume
state: present
- name: Add custom volume to NGINX container
docker_container:
name: webserver
volumes:
- custom_volume:/usr/share/nginx/html
Install docker
1 ---
2 - name: install Docker
3 hosts: all
4 become: true
5 tasks:
6 - name: set mydistribution
7 ansible.builtin.set_fact:
8 mydistribution: "{{ 'rhel' if (ansible_distributi\
9 on == 'Red Hat Enterprise Linux') else (ansible_distribut\
10 ion | lower) }}"
11
12 - name: Add signing key
13 ansible.builtin.rpm_key:
14 key:"https://download.docker.com/linux/{{ mydist\
15 ribution }}/gpg"
16 state: present
17
18 - name: Add repository into repo.d list
19 ansible.builtin.yum_repository:
20 name: docker
21 description: docker repository
22 baseurl: "https://download.docker.com/linux/{{ my\
23 distribution }}/$releasever/$basearch/stable"
24 enabled: true
25 gpgcheck: true
26 gpgkey: "https://download.docker.com/linux/{{ myd\
27 istribution}}/gpg"
28
29 - name: Install Docker
30 ansible.builtin.yum:
31 name:
32 - docker-ce
33 - docker-ce-cli
34 - containerd.io
35 state: latest
36 update_cache: true
37
38 - name: Start Docker
39 ansible.builtin.service:
40 name: "docker"
41 enabled: true
42 state: started