3

I am working to run a Postgres Docker container with Ansible playbook, but I'm having problems with passing the POSTGRES_USER and the POSTGRES_PASSWORD as env.

This is my playbook:

- name: Run Postgresql container
  hosts: db_farm
  gather_facts: no
  tasks:
    - name: Start docker service
      service:
        name: docker
        state: started

    - name: install pip dependencies
      pip:
        name: docker

- name: Create Postgres Container
      docker_container:
        name: hitch_postgres
        image: postgres:12
        state: started
        recreate: yes
        ports:
          - "5432:5432"
        volumes:
          - /home/hitch_postgres_data:/var/lib/postgresql/data
        env:
          POSTGRES_USER: "myuser"
          POSTGRES_PASSWORD: "myuser"

But when trying to connect to the server by first going into the container with docker exec -it hitch_postgres bash and running either psql -U myuser or psql -U postgresit shows this errors:

psql: error: FATAL:  role "myuser" does not exist
psql: error: FATAL:  role "postgres" does not exist  

I know Ansible has a module called postgresql_userbut when using it like this:

     postgresql_user:
       name: myuser
       password: myuser

It throws this error:

enter image description here

So, how to pass the environmental variables from Ansible that by using the Docker CLI would be as simple as adding -e POSTGRES_USER=123 -e POSTGRES_PASSWORD=123?

3
  • 2
    These variables only make sense when /home/hitch_postgres_data is empty. If there is a database, postgres won't make a new user and won't change the password. That is if you run this command with some another user before - it stays there and won't go unless you do something. Commented Feb 24, 2021 at 15:27
  • I just deleted the volume and run the playbook again and worked! Thank you very much. If you place it as an answer I would rate it and set as answer. Commented Feb 24, 2021 at 15:52
  • Does this answer your question? Docker exec - cannot call postgres with environment variables Commented Feb 24, 2021 at 19:18

1 Answer 1

0

POSTGRES_USER and POSTGRES_PASSWORD are only used to initialise a database. If you gave the container a persistent place to store the database (/home/hitch_postgres_data in the question) then after the first successful launch it will contain a database with the user and the password from the environment variables, which were present at that time. Consecutive launches with other environment variables will not trigger initialisation and thus, no user will be created and no password will be updated.

If you wish to learn more about the init process check out the readme and the entrypoint script.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.