In ansible playbook I need to run docker-compose commands. How can I do it? I need to run command: docker-compose -f docker-compose.yml -f docker-compose.prod.yml up
2 Answers
You should copy your Docker Compose files and use docker_compose
module such as:
- name: copy Docker Compose files
copy:
src: files/{{ item }}
dest: /somewhere/yourproject/{{ item }}
loop:
- docker-compose.yml
- docker-compose.prod.yml
# use files parameter to use multiple docker-compose.yml files
- name: deploy Docker Compose stack
community.docker.docker_compose:
project_src: /somewhere/yourproject
files:
- docker-compose.yml
- docker-compose.prod.yml
-
Oh, I see that to use docker_compose I need to install a lot of dependencies. Thanks for your answer!– TatianaJun 18, 2020 at 15:31
-
-
1You mean old
community.general.docker_compose
? Just update to use recentcommunity.docker.docker_compose
Jun 8, 2022 at 8:30 -
You're maybe confusing Ansible Docker collection currently at version
3.3.1
(galaxy.ansible.com/community/…) and Docker Compose specs currently at3.8
(docs.docker.com/compose/compose-file/compose-versioning). Ansible Docker collection (packaging compose module) version is not correlated to Docker Compose itself, and is perfectly able to run latest Docker Compose specs and binaries as of time of writing this comment :) (just tested to make sure) Jan 19 at 10:32
At the end I decided to use to use shell module. I think @pierre-b answer is more correct but anyway:
- name: Run container
become: True
shell:
cmd: "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d"
chdir: /mydir/
-
3You should definitely avoid using shell when there is a module doing the job for you. Now you also have to manage idempotency (which is done automatically by the module). Jun 18, 2020 at 15:39
-
1Thanks, your answer is also valid but as @Zeitounator pointed it's better to use an Ansible module where possible and avoid using shell commands. Why did the module did not suit you? Jun 18, 2020 at 15:57
-
1Too many requirements for the module. But probably I will use it in next time, it looks cool.– TatianaJun 18, 2020 at 16:44
-
3"Definitely" - not at all. The module relies on docker-py which is unmaintained and outdated. Don't use modules that don't keep pace / have good community support unless you're ok with staying behind in compatibility and having to rewrite later. Ansible community will eventually figure it out though.– aehlkeJun 7, 2022 at 20:31
-
If I install docker-compose-plugin, or a docker-compose for my flavour of server, I do not see why I should not use this, as it is the simplest and gets the job done.– GogolSep 11, 2022 at 21:06