shwetha
shwetha

Reputation: 376

Run a shell command inside a running Docker container using Ansible

I want to execute shell commands, for eg: a "wget" command inside a running docker container using Ansible. This is the playbook I am trying to execute

---

- name: Enter into a running container and run a command
  docker_container:
    name: centos_conatainer
    state: started
    image: centos
    command: wget https://downloadlink.com

This stops the container and also it is not downloading the file. Is this the right way to execute shell commands using docker_container module, or is there any other way to do this using Ansible?

Upvotes: 5

Views: 11367

Answers (4)

Cloudkollektiv
Cloudkollektiv

Reputation: 14669

Nowadays you can accomplish this with an Ansible community collection. To install this, please run:

ansible-galaxy collection install community.docker

If you successfully installed this collection, you can create the following task:

- name: Execute command inside a container
  community.docker.docker_container_exec:
    container: "{{ container_name }}"
    command: /bin/bash -c "echo Hello world"

This is equivalent to:

docker exec -i "{{ container_name }}" /bin/bash -c "echo Hello world"

Upvotes: 0

Michael
Michael

Reputation: 8663

You are looking for the Ansible equivalent of the docker exec command-line.

Command in ansible docker_container is the equivalent of the command option in the docker run command-line.

It doesn't appear that this new Ansible module has support for this. You'll just have to use the generic Ansible command.

Example:

- name: Enter into a running container and run a command
  command: docker exec centos_container wget https://downloadlink.com

Upvotes: 5

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68239

AFAIK there is no way you can do it with docker_container module – it is used to start a new container with the specified command.

I use this code to execute commands inside containers:

- name: Execute command inside a container
  shell: "docker exec {{ containerName }} {{ commandToRun }}"

Upvotes: 3

Mohamed Labouardy
Mohamed Labouardy

Reputation: 38

Entrypoint or CMD can do the job:

https://www.ctl.io/developers/blog/post/dockerfile-entrypoint-vs-cmd/

Upvotes: -3

Related Questions