Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables from Ansible playbook to docker_compose task

How can I pass registered output from a playbook to docker_compose task? In the playbook, I first create a temporary directory, and register the result:

- name: Create temporary deployment directory
  tempfile:
    state: directory
     prefix: test.
  register: tempdir

Later in the playbook, I have a docker_compose task like this:

- name: Create and start services
  docker_compose:
    project_name: test
    project_src: "{{ tempdir.path }}"

This works so far that the compose file is run and the containers started. However, in the compose file itself, I need to reference the tempdir in the volumes section, to mount it into the container.

I tried this in the compose file, which obviously doesn't work:

volumes:
  - /var/run/docker.sock:/var/run/docker.sock
  - "{{ tempdir.path }}/certs/acme.json:/acme.json"

This isn't limited to passing the tempdir, as I might need other variables passed to the compose file too. E.g. from the inventory file.

NB. I'm fairly new to Ansible, so forgive me if I confuse any terms.

like image 279
TomG Avatar asked Dec 19 '25 12:12

TomG


1 Answers

You can create a docker-compose template file and use template module from ansible, to copy and replace the variables inside to your destination.

Something similar to this:

 - name: set docker-compose
   template:
      src: docker-compose.yml.j2
      dest: "{{ your_compose_path }}"

And inside your docker-compose.yml.j2 you use your registered variable:

 volumes:
   - /var/run/docker.sock:/var/run/docker.sock
   - "{{ tempdir.path }}/certs/acme.json:/acme.json"
like image 175
sadok-f Avatar answered Dec 22 '25 15:12

sadok-f



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!