Embracing the Messiness in Search of Epic Solutions

GCP + Terraform: Running Terraform Commands with a Service Account

Posted

in

, ,

PROBLEM

When running these commands…

gcloud auth login
gcloud auth application-default login

… it allows terraform apply to provision the infrastructure using your credential.

However, sometimes there’s a need to run Terraform using a service account.

SOLUTION

First, identify the service account you want to use… for example: [email protected].

Then, create and download the private key for the service account.

Command:

gcloud iam service-accounts keys create --iam-account [email protected]  key.json

Output:

created key [xxxxxxxx] of type [json] as [key.json] for [[email protected]]

With this service account’s private key, we can now authorize its access to GCP.

Command:

gcloud auth activate-service-account --key-file key.json

Output:

Activated service account credentials for: [[email protected]]

You can verify whether the right account is being used or not.

Command:

gcloud auth list

Output:

                      Credentialed Accounts
ACTIVE  ACCOUNT
*       [email protected]
        [email protected]

To set the active account, run:
    $ gcloud config set account `ACCOUNT`

In this case, the * marks the active account being used.

Now, you can run terraform apply to provision the infrastructure using the selected service account.

Comments

Leave a Reply