0

I have the following situation: I have a remote server that runs docker with a Postgres container. The Postgres instance is only reachable through a docker network, not directly from the remote server.

I am trying to create an ansible role that makes sure all the required databases and users exist in the Postgres instance. For this I am trying to make Ansible first connect to the remote server, then connect to the Postgres docker container, and from there use the community.postgresql.postgresql_* modules to create the databases and users. However, I am stuck trying to get Ansible to do the nested connection. I currently have the following ansible-playbook:

# playbook.yml
- name: Postgres
  hosts: dockerservers
  roles:
    - name: postgres
      tags: [postgres, never]

# roles/postgres/tasks/main.yml
- name: Connect to database docker container
  add_host:
    name: "postgres"
    ansible_connection: docker
  changed_when: false

- name: Inside postgres docker container
  delegate_to: "postgres"
  block:
    - name: Debug
      community.postgresql.postgresql_info:

Docker tries to use the local docker cli (which is not installed) to connect to the remote docker daemon. Is there a way to somehow hop from the remote server to the docker container, instead of trying to directly connect to it?

1 Answer 1

1

I have found a hacky workaround for my problem. I replicated the behavior of the community.postgresql.* modules that I want to use in a bash script and execute it using the community.docker.docker_container module.

- name: Ensure databases and users exist
  register: "pg_ensure_db"
  changed_when: "not 'created' in pg_ensure_db.container.Output"
  community.docker.docker_container:
    name: postgresql-ensure-db
    image: "{{postgres_image}}"
    cleanup: true
    detach: false
    networks:
      - name: "db"
    command_handling: correct
    command: ["bash", "-c", "{{lookup('template', 'postgres-ensure-db.j2.sh')}}" ]

While this is not directly an answer to my question, and certainly less maintainable than if it was done natively using Ansible, I thought I would share it anyway until I find a better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.