docker-compose and changing config files

docker-compose and changing config files #

docker-compose (and docker swarm) has a concept of configs, which are sort of like mounting a single file as a volume. Especially handy is that you can specify the user that owns the config in the container. See also the Docker documentation.

You might use it in a config file like this:

version: "3.7"

services:
  dex:
    image: dexidp/dex
    volumes:
      - /etc/localtime:/etc/localtime:ro
    configs:
      - source: dex_config
        target: /config.yml
        uid: "1001"
        gid: "1001"
        mode: 0600
    command: ['dex', 'serve','/config.yml']

configs:
  dex_config:
    file: /tmp/config.yml

However, there is one stumbling block - a configuration cannot change. If the value in your config.yml files changes, Docker will refuse to deploy!

Instead, you can calculate the hash of the config file, and use that to name the config.

Calculate the hasn in your role:

- name: Install Dex config file
  template:
    src: dex.config.yml.j2
    dest: "/tmp/config.yml"
    owner: "1001"
    group: "1001"
    mode: "0600"

- name: Stat Dex config
  stat:
    path: "/tmp/config.yml"
  register: dex_config_stat_result

- name: Set Dex config hash
  set_fact:
    dex_config_hash: "{{ dex_config_stat_result.stat.checksum }}"

- name: Deploy the Docker stack
  docker_stack:
    state: present
    name: teststack
    prune: yes
    compose:
      - /path/to/compose-b.yml

And use that hash in your compose file:

version: "3.7"

services:
  dex:
    image: dexidp/dex
    volumes:
      - /etc/localtime:/etc/localtime:ro
    configs:
      - source: dex_config
        target: /config.yml
        uid: "1001"
        gid: "1001"
        mode: 0600
    command: ['dex', 'serve','/config.yml']

configs:
  dex_config:
    file: /tmp/config.yml
    name: dex_config_{{ dex_config_hash }}