Skip to content

Instantly share code, notes, and snippets.

@realBjornRoden
Last active September 27, 2019 13:43
Show Gist options
  • Save realBjornRoden/3c5d8e9c95511867e924860d8715e9bb to your computer and use it in GitHub Desktop.
Save realBjornRoden/3c5d8e9c95511867e924860d8715e9bb to your computer and use it in GitHub Desktop.

Infrastructure as Code (IaC) with Terraform HCL for GCP

The purpose of infrastructure as code (IaC) is to create and execute code to define, create, modify, and delete computing, storage and networking infrastructure, with consistency.

  • Basics with Terraform HCL
    $ terraform init
    $ terraform plan
    $ terraform apply
    

GCP (Google Cloud Platform)

  • Getting started with Terraform on Google Cloud Platform

  • Create and download service account keys JSON file from Console create, manage, or CLI:

    $ gcloud auth login
    
    $ gcloud projects list
    PROJECT_ID          NAME                PROJECT_NUMBER
    project-01-default  project-01-default  523124300007
    
    $ gcloud iam service-accounts create terraform-svc --display-name "Terraform Service Account"
    Created service account [terraform-svc].
    
    $ gcloud iam service-accounts list --filter "terraform-svc"
    NAME                       EMAIL                                                           DISABLED
    Terraform Service Account  terraform-svc@project-01-default.iam.gserviceaccount.com        False
    
    $ gcloud iam service-accounts keys create ./terraform-svc.json --iam-account terraform-svc@project-01-default.iam.gserviceaccount.com
    created key [deadbeeff1fa3b6c4f6ca6647f7b615ffa554391] of type [json] as [./terraform-svc.json] for [terraform-svc@project-01-default.iam.gserviceaccount.com]
    
    $ gcloud iam roles create terraform_svc --project project-01-default --file terraform-roles.yaml 
    Created role [terraform_svc].
    description: Terraform Service Role for GCP Compute
    etag: deadbeef
    includedPermissions:
    - compute.disks.create
    - compute.instances.create
    - compute.instances.delete
    - compute.instances.setMetadata
    - compute.subnetworks.use
    - compute.subnetworks.useExternalIp
    name: projects/project-01-default/roles/terraform_svc
    stage: ALPHA
    title: Terraform
    
    $ gcloud projects add-iam-policy-binding project-01-default --role projects/project-01-default/roles/terraform_svc --member serviceAccount:terraform-svc@project-01-default.iam.gserviceaccount.com
    Updated IAM policy for project [project-01-default].
    bindings:
    - members:
      - serviceAccount:terraform-svc@project-01-default.iam.gserviceaccount.com
      role: projects/project-01-default/roles/terraform_svc
    - members:
      - serviceAccount:service-523124360557@compute-system.iam.gserviceaccount.com
      role: roles/compute.serviceAgent
    - members:
    - serviceAccount:523124360557-compute@developer.gserviceaccount.com
      - serviceAccount:523124360557@cloudservices.gserviceaccount.com
      role: roles/editor
    - members:
      - serviceAccount:terraform@project-01-default.iam.gserviceaccount.com
      - user:realbjornroden@gmail.com
      role: roles/owner
    etag: deadbeef
    version: 1
    
  • main.tf

    provider "google" {
     credentials = "${file("terraform-svc.json")}"
     project = "project-01-default"
     region = "us-east1"
    }
    
    resource "google_compute_instance" "vm-solo-01" {
     provider = "google"
     zone = "us-east1-b"
     name = "vm-solo-01"
     machine_type = "f1-micro"
     boot_disk {
     	initialize_params {
     		image = "debian-cloud/debian-9"
     	}
     }
     network_interface {
     	network = "default"
     	access_config {
     		// for external IP
     	}
     }
    }
    
  1. Run terraform init

    $ terraform init
    
    Initializing the backend...
    
    Initializing provider plugins...
    - Checking for available provider plugins...
    - Downloading plugin for provider "google" (hashicorp/google) 2.16.0...
    
    The following providers do not have any version constraints in configuration,
    so the latest version was installed.
    
    To prevent automatic upgrades to new major versions that may contain breaking
    changes, it is recommended to add version = "..." constraints to the
    corresponding provider blocks in configuration, with the constraint strings
    suggested below.
    
    * provider.google: version = "~> 2.16"
    
    Terraform has been successfully initialized!
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
    
  2. Run terraform plan

    $ terraform plan
    Refreshing Terraform state in-memory prior to plan...
    The refreshed state will be used to calculate this plan, but will not be
    persisted to local or remote state storage.
    
    
    ------------------------------------------------------------------------
    
    An execution plan has been generated and is shown below.
    Resource actions are indicated with the following symbols:
      + create
    
    Terraform will perform the following actions:
    
      # google_compute_instance.vm-solo-01 will be created
      ...
    
    Plan: 1 to add, 0 to change, 0 to destroy.
    
    ------------------------------------------------------------------------
    
    Note: You didn't specify an "-out" parameter to save this plan, so Terraform
    can't guarantee that exactly these actions will be performed if
    "terraform apply" is subsequently run.
    
    
  3. Run terraform apply to create the VM

    $ terraform apply -auto-approve
    google_compute_instance.vm-solo-01: Creating...
    google_compute_instance.vm-solo-01: Still creating... [10s elapsed]
    google_compute_instance.vm-solo-01: Creation complete after 14s [id=vm-solo-01]
    
    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
    
  4. Run gcloud compute instances list

    $ gcloud compute instances list
    NAME        ZONE        MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
    vm-solo-01  us-east1-b  f1-micro                   10.142.0.2   35.243.203.155  RUNNING
    
  5. Run gcloud iam roles update to add the permission compute.instances.get

    $ gcloud iam roles update terraform_svc --project project-01-default --file terraform-roles.yaml 
    The specified role does not contain an "etag" field identifying a 
    specific version to replace. Updating a role without an "etag" can 
    overwrite concurrent role changes.
    
    Replace existing role (Y/n)?  Y
    
    description: Terraform Service Role for GCP Compute
    etag: deadbeef
    includedPermissions:
    - compute.disks.create
    - compute.instances.create
    - compute.instances.delete
    - compute.instances.get
    - compute.instances.setMetadata
    - compute.subnetworks.use
    - compute.subnetworks.useExternalIp
    name: projects/project-01-default/roles/terraform_svc
    stage: ALPHA
    title: Terraform
    
  6. Run terraform destroy to delete the VM

    $ terraform destroy -auto-approve
    google_compute_instance.vm-solo-01: Refreshing state... [id=vm-solo-01]
    google_compute_instance.vm-solo-01: Destroying... [id=vm-solo-01]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 10s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 20s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 30s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 40s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 50s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 1m0s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 1m10s elapsed]
    google_compute_instance.vm-solo-01: Still destroying... [id=vm-solo-01, 1m20s elapsed]
    google_compute_instance.vm-solo-01: Destruction complete after 1m22s
    
    Destroy complete! Resources: 1 destroyed.
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment