Skip to content

Commit

Permalink
Lab 6, added docker-compose (task 2)
Browse files Browse the repository at this point in the history
  • Loading branch information
kolayne committed Mar 9, 2024
1 parent 703cf9c commit 54ffb17
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 13 deletions.
45 changes: 32 additions & 13 deletions ansible/roles/web_app/tasks/main.yaml
Original file line number Diff line number Diff line change
@@ -1,23 +1,42 @@
---
- name: Pull image
community.docker.docker_image:
name: "{{ image_name }}"
source: "pull"
state: "present"
tag: "{{ image_tag }}"
- name: Create directory for compose
ansible.builtin.file:
path: "~/{{image_name|basename}}"
state: "directory"
register: compose_dir

- name: Stop old containers
community.docker.docker_compose_v2:
project_src: "{{ compose_dir.path }}"
state: stopped
# Compose file may not exist yet, thus ignoring errors
ignore_errors: true

- name: Render new docker-compose.yml
ansible.builtin.template:
src: docker-compose.yml.j2
dest: "{{ compose_dir.path }}/docker-compose.yml"
vars:
image_full: "{{image_name}}:{{image_tag}}"
expose_ports: "{{ publish_ports }}"
when: not wipe

- name: Manage container
# Note: runs both on normal run and on wipe
community.docker.docker_container:
name: "{{ container_name }}"
image: "{{image_name}}:{{image_tag}}"
state: "{{ wipe | ternary('absent', 'started') }}"
ports: "{{ publish_ports }}"
- name: Manage containers
# If wiping, remove containers, otherwise start them
community.docker.docker_compose_v2:
project_src: "{{ compose_dir.path }}"
state: "{{ wipe | ternary('absent', 'present') }}"
pull: always

- name: Wipe image
community.docker.docker_image:
name: "{{ image_name }}"
tag: "{{ image_tag }}"
state: "absent"
when: wipe

- name: Remove compose file from the filesystem
ansible.builtin.file:
path: "{{ compose_dir.path }}"
state: "absent"
when: wipe
9 changes: 9 additions & 0 deletions ansible/roles/web_app/templates/docker-compose.yml.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
services:
web_app:
image: {{ image_full }}
{% if expose_ports is iterable and expose_ports|length > 0 %}
ports:
{% for port_expr in expose_ports %}
- {{ port_expr }}
{% endfor %}
{% endif %}

0 comments on commit 54ffb17

Please sign in to comment.