I configured nginx on diffrent docker using ansible. Now I want to change different index.html using Jinja2.
I configured nginx using localhost. But now how can I use template Jinja2 and transfer it on container using ansible.
---
- hosts: localhost
vars:
server_name: "server"
connection: local
become: yes
tasks:
- package:
name: docker
state: present
- service:
name: docker
state: restarted
- command: docker run -it --name ngixserver21 -d -p 8090:80 nginx
#how I can transfer html_template.j2 on container - ngixserver21
- name: Run a simple command (command)
community.docker.docker_container_exec:
container: ngixserver21
template:
src: "html_template.j2"
desc: "/usr/share/nginx/html/index.html"
notify: Restart Nginx
2
Answers
I actually support what’s been said in the comments. It’s a little bit of anti-pattern.
I used something like this in the past. I’m sure you get the gist.
This assumes of course that you have bash(sh should work too) and base64. If your template does not have single quotes, you may not need base64.
Important preliminary note: I urge you to read the comments from DavidMaze and β.εηοιτ.βε above regarding good practice to understand why you don’t want to go through ansible in your specific case and you should not modify a running container.
Meanwhile, since there are other use cases (like testing ansible roles inside a docker container), I’ll still answer the overall question hopping that all the above warnings were enough for you to use that information very wisely.
To start with, if you want to deploy and run your image with ansible, it should be done using the relevant
docker_container
module rather than callingshell
.Once this is done, ansible has a
docker
connection plugin that will let you interact with containers on your host 1. The idea is to have an entry in your inventory for the relevant container using the correctly configured connection. You can then use a normal play host loop with usual ansible tasks to reach your remote target container 2.In my example below, I deploy an image and add it to the in-memory inventory in the same playbook using the
add_host
module. Those two actions can be done totally independently and there are several options to add your containers to an inventory among which thedocker_containers
dynamic inventory plugin.I used the following
test.j2
template for this testThis the demo
playbook.yml
:Which gives:
1
docker
plugin uses the docker cli to run commands. If you prefer to use the api directly, you can do the same thing with thedocker-api
plugin2 Note that your target container will need to satisfy to ansible managed nodes requirements and have python installed