Create first GCP resource with Terraform

pradeepbhadani

Pradeep Bhadani

Posted on January 9, 2020

Create first GCP resource with Terraform

Originally published at pbhadani.com


Welcome to my post and Happy New year!

Let's create our first GCP resource using Terraform in this post.
Alt Text

Photo by Markus Spiske on Unsplash

Goal

Create a Google Cloud Storage(GCS) Bucket using Terraform.

Prerequisites

This post assumes the following:

  1. We already have a GCP Project and a GCS Bucket (we will use this to store Terraform State file) created.
  2. Google Cloud SDK (gcloud) and Terraform is setup on your workstation. If you don't have, then refer to my previous blogs - Getting started with Terraform and Getting started with Google Cloud SDK.

Create a Google Cloud Storage(GCS) Bucket with Terraform

Step 1: Create a unix directory for the Terraform project.

  mkdir ~/terraform-gcs-example
  cd ~/terraform-gcs-example

Step 2: Create Terraform configuration file which defines GCS bucket and provider.

  vi bucket.tf

This file has following content

  # Specify the GCP Provider
  provider "google" {
    project = var.project_id
    region  = var.region
  }

  # Create a GCS Bucket
  resource "google_storage_bucket" "my_bucket" {
    name     = var.bucket_name
    location = var.region
  }

Step 3: Define Terraform variables.

  vi variables.tf

This file looks like:

  variable "project_id" {
    description = "Google Project ID."
    type        = string
  }

  variable "bucket_name" {
    description = "GCS Bucket name. Value should be unique ."
    type        = string
  }

  variable "region" {
    description = "Google Cloud region"
    type        = string
    default     = "europe-west2"
  }
**Note:** We are defining a `default` value for `region`. This means if a value is not supplied for this variable, Terraform will use `europe-west2` as its value.

Step 4: Create a tfvars file.

  vi terraform.tfvars
  project_id  = ""                   # Put your GCP Project ID.
  bucket_name = "my-bucket-48693"    # Put the desired GCS Bucket name.

Step 5: Set the remote state.

  vi backend.tf
  terraform {
    backend "gcs" {
      bucket = "my-tfstate-bucket"   # GCS bucket name to store terraform tfstate
      prefix = "first-app"           # Update to desired prefix name. Prefix name should be unique for each Terraform project having same remote state bucket.
      }
  }

Step 6: File structure looks like below

  cntekio:~ terraform-gcs-example$ tree
  .
  ├── backend.tf
  ├── bucket.tf
  ├── terraform.tfvars
  └── variables.tf

  0 directories, 4 files

Step 7: Now, initialize the terraform project.

  terraform init

Output

  Initializing the backend...

  Successfully configured the backend "gcs"! Terraform will automatically
  use this backend unless the backend configuration changes.

  Initializing provider plugins...
  - Checking for available provider plugins...
  - Downloading plugin for provider "google" (hashicorp/google) 3.3.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 = "~> 3.3"

  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.

Note: terraform init downloads all the required provider and plugins.

Step 8: Let's see the execution plan.

  terraform plan --out 1.plan

Output

  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_storage_bucket.my_bucket will be created
    + resource "google_storage_bucket" "my_bucket" {
        + bucket_policy_only = (known after apply)
        + force_destroy      = false
        + id                 = (known after apply)
        + location           = "EUROPE-WEST2"
        + name               = "my-bucket-48693"
        + project            = (known after apply)
        + self_link          = (known after apply)
        + storage_class      = "STANDARD"
        + url                = (known after apply)
      }

  Plan: 1 to add, 0 to change, 0 to destroy.

  ------------------------------------------------------------------------

  This plan was saved to: 1.plan

  To perform exactly these actions, run the following command to apply:
      terraform apply "1.plan"

Note: terraform plan output shows that this code is going to create one GCS bucket.
--out 1.plan flag tells terraform to save the plan in a file.

Step 9: The execution plan looks good, so let's move ahead and apply this plan.

  terraform apply 1.plan

Output

  google_storage_bucket.my_bucket: Creating...
  google_storage_bucket.my_bucket: Creation complete after 3s [id=my-bucket-48693]

  Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Step 10: Once we no longer need this infrastructure, we can cleanup to reduce costs.

  terraform destroy

Output

  google_storage_bucket.my_bucket: Refreshing state... [id=my-bucket-48693]

  An execution plan has been generated and is shown below.
  Resource actions are indicated with the following symbols:
    - destroy

  Terraform will perform the following actions:

    # google_storage_bucket.my_bucket will be destroyed
    - resource "google_storage_bucket" "my_bucket" {
        - bucket_policy_only = false -> null
        - force_destroy      = false -> null
        - id                 = "my-bucket-48693" -> null
        - labels             = {} -> null
        - location           = "EUROPE-WEST2" -> null
        - name               = "my-bucket-48693" -> null
        - project            = "my-project-id" -> null
        - requester_pays     = false -> null
        - self_link          = "https://www.googleapis.com/storage/v1/b/my-bucket-48693" -> null
        - storage_class      = "STANDARD" -> null
        - url                = "gs://my-bucket-48693" -> null
      }

  Plan: 0 to add, 0 to change, 1 to destroy.

  Do you really want to destroy all resources?
    Terraform will destroy all your managed infrastructure, as shown above.
    There is no undo. Only 'yes' will be accepted to confirm.

    Enter a value: yes

  google_storage_bucket.my_bucket: Destroying... [id=my-bucket-48693]
  google_storage_bucket.my_bucket: Destruction complete after 6s

  Destroy complete! Resources: 1 destroyed.

Hope this blog helps you get started with creating GCP resources using Terraform

If you have a feedback or questions, please reach out to me on LinkedIn or Twitter

💖 💪 🙅 🚩
pradeepbhadani
Pradeep Bhadani

Posted on January 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related