So From an ansible with host localhost I am trying to run ansible command directly inside a docker container (command can be anything from lineinfile to copy). The main reason I am trying to do this is so that I cam seamlessly use ansible task on docker (Docker exec is NOT an appropriate solution).
I am currently trying to achieve this using connection: community.docker.docker. I want to this on a task block and not at the playbook level hence why it looks like it does. Ideally I can the params in the template without creating an additional inventory.
Heads up the playbook is truncated but you can assume all missing vars are present. the issue is main. The part where I copying Let’s encrypt is important. The fact that I can start a container and docker_exec works makes me thing the error I get
fatal: [localhost -> instance-139.xxx.xxx.xxx]: FAILED! => {
"msg": "docker command not found in PATH"
}
is not supposed to happen.
Here is a truncated version of my ansible playbook
- name: Create an API instance
hosts: localhost
gather_facts: no
collections:
- linode.cloud
- community.docker
tasks:
- block:
- name: Linode IPS
debug:
msg: "{{ linode_ips }}"
- name: Update apt and install dependencies
apt:
update_cache: yes
name: "{{ item }}"
force_apt_get: yes
state: present
loop:
- apt-transport-https
- ca-certificates
- curl
- gzip
- software-properties-common
- name: Add Docker GPG key
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
state: present
- name: Add Docker repository
apt_repository:
repo: deb https://download.docker.com/linux/ubuntu focal stable
state: present
- name: Install Docker
apt:
name: docker-ce
state: present
force_apt_get: yes
update_cache: yes
- name: Start and enable Docker
systemd:
name: docker
state: started
enabled: yes
- debug:
msg: "Registry: docker.registry.aksantinet.com/{{ host_group }}"
- name: Pull the image from the registry
community.docker.docker_image:
name: "docker.registry.aksantinet.com/{{ host_group }}"
tag: latest
source: pull
- name: Run Docker container
community.docker.docker_container:
name: "{{ container_name }}"
image: "docker.registry.aksantinet.com/{{ host_group }}"
network_mode: host
state: started
capabilities:
- NET_ADMIN
devices:
- /dev/net/tun:/dev/net/tun
privileged: yes
become: yes
- name: Copy LetsEncrypt from ansible to Docker
become: yes
block:
- lineinfile:
path: "test"
line: "example"
create: yes
state: present
- ansible.builtin.copy:
src: /etc/letsencrypt/
dest: /etc/letsencrypt/
- shell: nginx
- shell: nginx
vars:
ansible_docker_host: "{{ container_name }}"
ansible_connection: docker
- name: Instance added
debug:
msg: "Addded instance at {{ linode_ip }}"
delegate_to: "instance-{{ linode_ip }}"
Main points are
- Want to run tasks inside the container docker
- I can execute other commands before so I am confused as to why it does work with connection: docker (same ssh: user)
- The delegate to is for the docker host