forked from vutoff/devops-programme
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplaybook.yml
More file actions
62 lines (54 loc) · 2.41 KB
/
playbook.yml
File metadata and controls
62 lines (54 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
---
- name: Build and run Python app container
hosts: localhost
connection: local
vars:
image_name: "cyrixrr/python-app"
image_tag: "v2"
listen_port: 8000 # Here we set our variables
host_port: "{{ listen_port }}" # New variable – this is the port we check and remove other containers from
collections:
- community.docker # Here we gave acces to Docker modules
tasks:
- name: Build the Docker image
community.docker.docker_image:
name: "{{ image_name }}"
tag: "{{ image_tag }}"
build:
path: "{{ playbook_dir }}"
source: build #This would like this in shell "docker build -t cyrixrr/python-app:v2 .
# ---------------- NEW BLOCK START ----------------
- name: Get Docker host info (list of all containers) # New – we gather container info so we can check used ports
community.docker.docker_host_info:
containers: true
register: host_info
- name: Remove ANY container using the host port # New – this removes any container that is using listen_port
community.docker.docker_container:
name: "{{ (item.Names is string) | ternary(item.Names, (item.Names | first | regex_replace('^/', ''))) }}"
state: absent
loop: "{{ host_info.containers | default([]) }}"
when: >
item.Ports is defined and
(
item.Ports
| selectattr('PublicPort','defined')
| selectattr('PublicPort','equalto', host_port | int)
| list | length
) > 0
# This loop checks every container, and if it is using 8000 on the host,
# we remove it. This makes the playbook idempotent and avoids port conflicts.
# ---------------- NEW BLOCK END ------------------
- name: Remove existing container if present
community.docker.docker_container:
name: python-app
state: absent #That will make it idempotent as we spoke in cource
- name: Run the Docker container
community.docker.docker_container:
name: python-app
image: "{{ image_name }}:{{ image_tag }}"
env:
PORT: "{{ listen_port | string }}"
published_ports:
- "{{ host_port }}:{{ listen_port }}" # Updated to use host_port so we can remove others first
state: started
restart_policy: unless-stopped #All this would like this in shell "docker run -d --name python-app -e PORT=8000 -p 8000:8000 cyrixrr/python-app:v2"