Search code examples
pythongoogle-cloud-sqlgoogle-alloydb

Error in connecting to AlloyDB database with IAM user


For Postgre Cloudsql, we have to use google cloud-sql-python-connector to connect to DB. When we establish a connection using IAM user, we don't have to pass any password if we pass a flag enable_iam_auth as true . I confirmed this by looking at source-code of this connector that password is optional (Line 58 here) However, for AlloyDB, we have to use alloydb-python-connector and when I am not passing any password for IAM user, it is resulting an error. This can be confirmed from source code where password is not optional (Line 50 here). I tried setting password as blank string or None but it didn't work.I also tried setting the flag enable_iam_auth but I got an error that it's an invalid argument.

The error is because alloy-db-connector has not specified any default value while poping password. Is there any other way we can use this connector with AlloyDB?


Solution

  • As mentioned on this Github issue

    This is because automatic IAM database authentication is not currently a supported feature of the AlloyDB Python Connector. It is currently being worked and will be released in the near future. There is an open feature request as a public tracking bug for this feature.

    However, you can actually configure/wire your own SQLAlchemy engine to connect using IAM authentication with some very minimal code.

    We have an example that uses this method with psycopg2 to connect directly without using the AlloyDB Python Connector.

    Additional steps to enable IAM database authentication on an AlloyDB instance can be found https://cloud.google.com/alloydb/docs/manage-iam-authn and make sure all steps have been followed in detail.

    TLDR steps;

    • [ ] Enabled IAM authentication on the AlloyDB instance via alloydb.iam_authentication flag
    • [ ] Granted the IAM Principal (user or service account) the Cloud AlloyDB Client and Cloud AlloyDB Database User roles
    • [ ] Create AlloyDB IAM database user on your AlloyDB cluster
    • [ ] Login as database admin user (ex. postgres user) and grant the new IAM database user the proper database privileges to the appropriate tables etc.