Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Using IAM to connect a SA account to a Postgres SQL instance from VM in Compute Engine

I'm trying to connect from Python from a Compute Engine VM to a Postgresql storage instance and I continue to get the following error even after making the recommended changes.  

"ClientResponseError(
aiohttp.client_exceptions.ClientResponseError: 403, message="Forbidden: Authenticated IAM principal does not seeem authorized to make API request. Verify 'Cloud SQL Admin API' is enabled within your GCP project and 'Cloud SQL Client' role has been granted to IAM principal."

My connection uses the following parameters:

# function to return the database connection object
def getconn():
conn = connector.connect(
'INSTANCE:LOCATION',
"pg8000",
user='sa-****',
db='postgres',
enable_iam_auth = True
)
return conn

Any suggestions for troubleshooting this issue?

Thanks,
Eric

4 4 2,283
4 REPLIES 4

Hi @tangedahl,

Welcome to the Google Cloud Community!

First, make sure that Cloud SQL Admin API is enabled. You may follow the steps in this documentation.

Next, check the service account associated with your VM have the necessary permission. Kindly follow the steps below:

  1. Head to Compute Engine in your Cloud Console
  2. Click on the VM name that you're running the Python script from.
  3. Under Details, scroll down to API and identity management.
  4. Take note of the service account indicated. Below is a sample screenshot.API.png
  5. Head to IAM, grant the service account associated to the VM with the "Cloud SQL Client" role.API_2.png
  6. Reattempt to run your Python Script.

I hope this helps. Thank you. 😃

I really appreciate that suggestion.. it got me going in the right
direction. I had the default service account running stead of the one I'd
created. One final item is to give the service account access to the
specific database in Postgresql and that enabled me to write to the DB...
thank you!

Hi @lawrencenelson

I've followed all the necessary steps mentioned above and from the docs as well but I'm still getting the similar error in one of my cases:

1) While using IAM (user): Working fine

2) While using IAM (service account)Cloud SQL IAM service account authentication failed for user "xxxxxxxxxx-compute@developer"

I'd really appreciate any suggestions for troubleshooting this issue?

Thanks,
Deepak

@lawrencenelson  @dev_deepak21 I am also dealing with this same issue.

I've verified that the service account associated with my cluster has the Cloud SQL Client Role, and I've verified that Cloud SQL Admin is enabled for my project. I only receive this error when running my server application and trying to connect to Cloud SQL/Postgres, from within GKE. I do not have this issue when running my server locally and connecting to Cloud SQL/Postgres.