/IaC-gcp-example

this is an IaC example of deploying resources on GCP with terraform

Primary LanguageHCLApache License 2.0Apache-2.0

IaC-gcp-example

this is an IaC example of deploying resources on GCP with terraform

Install google cloud sdk (python cli) on MacOSX

brew install --cask google-cloud-sdk

Reference:

Authenticating GCP project in Terraform

Init the project for gcp cli to use

gcloud init

Create an Application Default Credential (ADC) for terraform to sue

gcloud auth application-default login

(Optional) remove the ADC:

gcloud auth application-default revoke

Reference:

Config CLI

List the active gcp account name:

gcloud auth list

List the active gcp projects with associated gcp account:

gcloud projects list --filter='lifecycleState:ACTIVE'

List the project ID:

gcloud config list project

List the current cli project's active config

gcloud config configurations list

Create service account

PROJECT_ID=$(gcloud config list --format 'value(core.project)')
SERVICE_ACCOUNT_NAME=<sa-name>
echo ${SERVICE_ACCOUNT_NAME}
gcloud iam service-accounts create ${SERVICE_ACCOUNT_NAME} \
  --description="service account to access gcp project from remote terraform" \
  --display-name=${SERVICE_ACCOUNT_NAME}
ROLE=roles/aiplatform.admin
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
    --member="serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role=${ROLE}
ROLE=roles/editor
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
    --member="serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role=${ROLE}
ROLE=roles/storage.admin
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
    --member="serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role=${ROLE}

Create a service account key file and save it to your remote workstation

makedir -p ~/.gcp/
KEY_FILE=~/.gcp/sa-private-key.json
gcloud iam service-accounts keys create ${KEY_FILE} \
--iam-account=${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com

Notice:

  • You are using user authentication at this point
  • after the service-acccounts key generation, you can remove the user authentication.

Adding the env variable in your shell

# google credentials
# location of the service account key file
export GOOGLE_CREDENTIALS="~/.gcp/sa-private-key.json"

init terraform

# init terraform state
terraform init
# plan the change shall be made to your cloud resources
terraform plan
# executed planed changes defined by HCL 
terraform apply

(Optional) upgrade the provider version

terraform init --upgrade

Apply terraform

terraform will take the variables from either terraform.tfvars or .auto.tfvars

Otherwise, we need to define the .tfvars file during the terraform apply.

terraform apply -var-file="const.tfvars"

Visualize your terraform plan

terraform graph -type=plan | dot -Tpng -o graph.png

Learning Source

Resources

GCP pricing