'GCP Impersonation not working with BQ command

I am trying to use impersonation while using BQ command but getting below error.

This is the command i am trying to run:

gcloud config set auth/impersonate_service_account sa-account  ;\
gcloud config list ; \
bq query --use_legacy_sql=false "SELECT * from prj-name.dataset-name.table-name ORDER BY Version" ;\

This is the error i am getting:

Your active configuration is: [default]
+ bq query --use_legacy_sql=false SELECT * from xxx-prj.dataset-name.table-name ORDER BY Version
ERROR: (bq) gcloud is configured to impersonate service account [XXXXXX.iam.gserviceaccount.com] but impersonation support is not available.

what change is needed here?



Solution 1:[1]

Here is how you can use service account impersonation with BigQuery API in gcloud CLI:

  1. Impersonate the relevant service account:

    gcloud config set auth/impersonate_service_account=SERVICE_ACCOUNT
    
  2. Run the following CURL command, specifying your PROJECT_ID and SQL_QUERY:

    curl --request POST \
    'https://bigquery.googleapis.com/bigquery/v2/projects/PROJECT_ID/queries' \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H 'Accept: application/json' \
      -H 'Content-Type: application/json' \
      -d '{"query":"SQL_QUERY"}' \
      --compressed
    

P.S. gcloud auth print-access-token will make it use the access token of the impersonated service account, which will allow you to run queries.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deniss T.