Ayra
Ayra

Reputation: 348

Ansible won't interpret command as it should

- name: Execute commands in docker postgres container
  command: docker exec -i postgres bash -c 'psql -U postgres -c "create user gitlab with password '000000b';"'

this module is sending me an error around 000000b (syntaxe) but when i use the command :
psql -U postgres -c "create user gitlab with password '000000b';" on terminal it is working fine.

Why is Ansible interpreting my command otherwise ?

Upvotes: 0

Views: 68

Answers (1)

saj
saj

Reputation: 681

It fails because your command is too complex for ansibles command module (passing escaped sequences through 3 different commandline-interpreters and all ;). You could probably fix it with a lot of cleverly escaped sequences, but i would not recommend attempting that, primarily because it breaks idempotency, secondly because it's really unreadable and annoying to maintain and thirdly because you gonna age 2.34 times faster while doing so.

If all you want is use ansible to quickly and dirtily create a gitlab user, you could do something like this (still breaks idempotency, meaning you'd have to catch errors when running this more than once):

  • be sure to expose the containers postgres port to localhost:

    docker run -d --name postgres -p 5432:5432 postgres

  • change your playbook task to something like this:

    - command: psql -h localhost -U postgres -c "create user gitlab with password '000000b';"
      ignore_errors: yes
    

However, the proper way to do this - in my opinion - would be leveraging ansibles postgres_user module:

For this example, i ran a postgresql in a docker-container with above command.

playbook.yml:

---
- hosts: localhost
  tasks:
  - name: create gitlab user
    postgresql_user:
      login_host: localhost
      login_user: postgres
      name: gitlab
      password: '000000b'

This requires psycopg2 to be installed on the system, which should be available either from your distros repos or pypi. Also, you probably want to provide hashed passwords instead of having them in cleartext. The linked module documentation addresses that as well.

Upvotes: 1

Related Questions