Home > Blockchain >  Switching gcloud accounts for Terraform and Kubernetes
Switching gcloud accounts for Terraform and Kubernetes

Time:10-03

I have two emails associated with two separate gcloud projects.

I can easily switch the projects with:

$ gcloud auth list
  Credentialed Accounts
ACTIVE  ACCOUNT
        first@project1
*       second@project2

$ gcloud config set account first@project1

I can then see, that gcloud did change the active account. I can also do this with:

$ gcloud config configurations list
...
$ gcloud config configurations set project1

And I can see the active configuration changes.

However it does not seem to have any effect for kubectl and terraform commands as they still use the previous configuration.

What am i doing wrong? How should I switch between the projects? It seems it has something to do with application-default account, but that looks it cannot be easily switched without relogin?

CodePudding user response:

Kubectl and terraform have own config or we can say context

for kubectl you need to change the cluster config using

kubectl config get-contexts

kubectl config use-context <cluster-name>

Or else each time you have set the context of Kubernetes cluster using Gcloud and it will get auto changed for kubectl

gcloud container clusters get-credentials cluster-name which takes the --project also.

Read more at : https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl

For changing project in terraform there are different ways

  • Using different serviceaccount keys JSON
  • Changing project config inside terraform provider
  • Setting up environment variable GOOGLE_APPLICATION_CREDENTIALS

setting project inside the Provider

provider "google" {
  project     = "my-project-id"
  region      = "us-central1"
  zone        = "us-central1-c"
}

https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference

Best approach to use : https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#credentials-1

As you are writing IAC so all config in code.

List of all possible methods for authentication terraform:

https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#authentication

CodePudding user response:

SDK provides the following command, this helps in applying credentials to all API calls that make use of the Application Default Credentials client library.

Terraform is one of the classic applications that have this dependency.

gcloud auth application-default login

Here is the documentation for the above command.

  • Related