Luv33preet
Luv33preet

Reputation: 1867

Ansible: Attach role to user in postgres

I am already having a role in Postgres namely readonly. It has readonly access on all the tables in all the databases.

I want to attach this role to a user so that he/she also gets the readonly access on all tables in one command. How can I perform the following command using ansible's postgresql_user module?

mydb=> grant readonly to dev_username;

EDIT: adding more details

This is what I have tried,

- name: Postgres
  postgresql_user:
    login_host: xx.xx.com
    login_password: mypassword
    login_user: myuser
    db: mydb
    name: dev_username
    password: mypassword
    priv: "readonly"
    expires: infinity
    state: present

It is giving me this error,

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: __main__.InvalidPrivsError: Invalid privs specified for database: READONLY
fatal: [127.0.0.1]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/h1/w57gk9nx0xl8j6xb_cqv3wb00000gn/T/ansible_2ema8gl3/ansible_module_postgresql_user.py\", line 855, in <module>\n    main()\n  File \"/var/folders/h1/w57gk9nx0xl8j6xb_cqv3wb00000gn/T/ansible_2ema8gl3/ansible_module_postgresql_user.py\", line 746, in main\n    privs = parse_privs(module.params[\"priv\"], db)\n  File \"/var/folders/h1/w57gk9nx0xl8j6xb_cqv3wb00000gn/T/ansible_2ema8gl3/ansible_module_postgresql_user.py\", line 686, in parse_privs\n    (type_, ' '.join(priv_set.difference(VALID_PRIVS[type_]))))\n__main__.InvalidPrivsError: Invalid privs specified for database: READONLY\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

I also tried with role_attr_flags: readonly, but again it failed. Its clearly written in the official docs that there are only some values allowed in role_attr_flags and priv, I knew it wouldn't work but I did it just for the sake of it.

Is this even possible with ansible?

Upvotes: 2

Views: 2488

Answers (2)

Pratik
Pratik

Reputation: 1

You need to add become_user: postgres at the end.

## Create Postgresql db user
- name: Create postgresql database user on UBUNTU
  postgresql_user:
    name: "{{db_user}}"
    password: "{{db_passwd}}"
    state: present
  become_user: postgres

Upvotes: -1

Zeitounator
Zeitounator

Reputation: 44760

Recap of postgresql terminology: a user is a role, a group is a role. The first has login privileges, the second usually not.

postgresql_user ansible module does not allow you to assign an existing role to a user.

You will need to first create the user and then attach the other role with postgresql_membership

Upvotes: 6

Related Questions