DavidLinares
DavidLinares

Reputation: 61

[GCP]Error while trying to impersonate Service account and run auth print-access-token

I'm getting this error:

ERROR: (gcloud.auth.print-access-token) Failed to impersonate [Runtime-ServiceAccountName]. Make sure the account that's trying to impersonate it has access to the service account itself and the "roles/iam.serviceAccountTokenCreator" role.

I'm running this in ADO pipeline, using bash and Hashicorp Vault to login.

This are the gcloud commands:

Step to activate vault Service Account

echo
gcloud config set project $(project_id)
echo
gcloud auth activate-service-account $(vaultsbx_email) --key-file=D:/ref/gcp/gcpLogin.json --project=$(project_id)
echo

echo 'Set Service Account to Impersonate'
gcloud config set auth/impersonate_service_account $(iac_deployer)

Step to impersonate and grant Service Token Creator role to Runtime Service Account.

gcloud iam service-accounts add-iam-policy-binding $(iac_deployer) --member='serviceAccount:$(sa_rt)' --role='roles/iam.serviceAccountTokenCreator'
 

TOKEN=$(gcloud auth print-access-token --impersonate-service-account $(Runtime-ServiceAccountName)) 
 
echo ${TOKEN}

Result of the grant of the role:

Updated IAM policy for serviceAccount [vaultsbx_email].
bindings:
- members:
  - serviceAccount:ServiceAccountName
  - serviceAccount:Runtime-ServiceAccountName
  - serviceAccount:vaultsbx_email
  role: roles/iam.serviceAccountTokenCreator
etag: BwYY-t5I5rs=
version: 1

So, if you see the Runtime-ServiceAccountName has Service Account Token Creator role permission, it's above but then I got that error message. What's going on? Of course I tried different options, like to run the command:

gcloud iam service-accounts add-iam-policy-binding $(iac_deployer) --member='serviceAccount:$(Runtime-ServiceAccountName)' --role='roles/iam.serviceAccountTokenCreator'

with the others Service Accounts to grant Runtime-ServiceAccountName

The idea is to run AlloyDB Auth Proxy using the Token generated with this Runtime-ServiceAccountName.

Thanks!

Upvotes: 1

Views: 462

Answers (1)

x-zone-cat
x-zone-cat

Reputation: 550

You should add the permission on the project IAM level via following command:

gcloud projects add-iam-policy-binding <project-ID> \
--member='serviceAccount:[email protected]' \
--role='roles/iam.serviceAccountTokenCreator' \
--impersonate-service-account $(Runtime-ServiceAccountName)

then you can perform:

gcloud auth print-access-token --impersonate-service-account $(Runtime-ServiceAccountName

Try doing your commands manually to troubleshoot more

Upvotes: 1

Related Questions