filedockeransiblecopy

ansible playbook copy file to docker container


I want copy a file to docker container using ansible playbook. How can i do that ?

- name: kapacitor conf
  template: src=/home/debian/roles/tick_install/files/kapacitor.conf  dest=/etc/kapacitor/kapaci
my docker container = tick_kapacitor

Solution

  • I assume you are using a plain Docker container without an orchestrated solution (such as Kubernetes or Swarm). If your container is already running, that will depend:

    Without volume mounted

    If you want to copy the file into an existing container which does not have a volume mounted where you want your file to be copied, I see no other way but running a docker cp command via shell or command, for example:

    - name: Copy file into existing container at /path/in/the/container/kapaci
      shell: docker cp /etc/kapacitor/kapaci tick_kapacitor:/path/in/the/container/kapaci
    

    With a volume mounted in the container

    If you already have a volume mounted from the machine into the container, you can copy the file directly at the machine mount point. For example, if the container has a volume mounted from /var/myapp/data to /path/in/the/container, you can use template to copy the file directly into the container with its mounted volume:

    name: kapacitor conf 
    template: 
      src: /home/debian/roles/tick_install/files/kapacitor.conf
      dest: /var/myapp/data/kapacitor.conf
      # will be available in container at /path/in/the/container
    

    Running a new container

    If you want to runner a new container, you can use the docker_container module or run a command (docker run, docker-compose up......) which will run your container and then copy the file into it using one of the previously mentionned solution.