Create first GCP resource with Terraform
Tags: terraform, devops, infrastructure, googlecloudplatform
Published: 2020-01-09 18:50:57

*Originally published at [pbhadani.com](https://pbhadani.com/posts/first-gcp-resource-with-terraform/)*
<br>
Welcome to my post and Happy New year!

Let's create our first GCP resource using Terraform in this post.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/cra9jscnmcqvn7s429wo.jpg)
<center><font size="1"> Photo by [Markus Spiske](https://unsplash.com/@markusspiske) on [Unsplash](https://unsplash.com)</font></center>

# 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](https://pbhadani.com/posts/getting-started-with-terraform/) and [Getting started with Google Cloud SDK](https://pbhadani.com/posts/getting-started-wth-google-cloud-sdk/).

# Create a Google Cloud Storage(GCS) Bucket with Terraform

**Step 1:** Create a unix directory for the Terraform project.
  ```bash
  mkdir ~/terraform-gcs-example
  cd ~/terraform-gcs-example
  ```

**Step 2:** Create Terraform configuration file which defines GCS bucket and provider.
  ```bash
  vi bucket.tf
  ```
  This file has following content
  ```hcl
  # 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.
  ```bash
  vi variables.tf
  ```
  This file looks like:
  ```hcl
  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.
  ```bash
  vi terraform.tfvars
  ```
  ```hcl
  project_id  = ""                   # Put your GCP Project ID.
  bucket_name = "my-bucket-48693"    # Put the desired GCS Bucket name.
  ```

**Step 5:** Set the remote state.
  ```bash
  vi backend.tf
  ```
  ```hcl
  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
  ```bash
  cntekio:~ terraform-gcs-example$ tree
  .
  ├── backend.tf
  ├── bucket.tf
  ├── terraform.tfvars
  └── variables.tf

  0 directories, 4 files
  ```

**Step 7:** Now, initialize the terraform project.
  ```bash
  terraform init
  ```
  **Output**
  ```bash
  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.
  ```bash
  terraform plan --out 1.plan
  ```
  **Output**
  ```bash
  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.
  ```bash
  terraform apply 1.plan
  ```
  **Output**
  ```bash
  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.
  ```bash
  terraform destroy
  ```
  **Output**
  ```bash
  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](https://linkedin.com/in/pradeepbhadani) or [Twitter](https://twitter.com/bhadanipradeep)