Search code examples
redisterraformgcloud

how to invoke gcloud commands using terraform


Since terraform does not have redis tls support yet, was planning to invoke gcloud command to create tls enabled redis through terraform. I am new to terraform, so was looking for some resource on web. but couldn't find much. Can some one please help with a working sample. any gcloud command invocation would work.

thanks


Solution

  • Terraform builds upon underlying REST APIs and does not use Cloud SDK (gcloud) directly. For this reason, it's not straightforward to invoke gcloud commands directly in the absence of a provider supporting the resource.

    I'm unfamiliar with Terraform but I expect (!?) that invoking shell commands directly (e.g. gcloud redis instances create ...) is discouraged. And, while it's likely also possible to call REST APIs directly, you'll then need to take care authenticating.

    That said, google-beta supports TLS.

    transit_encryption_mode = "SERVER_AUTHENTICATION"

    terraform {
      required_providers {
        google-beta = {
          source = "hashicorp/google-beta"
          version = "3.58.0"
        }
      }
    }
    
    variable "project" {}
    variable "region" {}
    variable "zone" {}
    variable "key" {}
    variable "instance" {}
    
    provider "google-beta" {
      credentials = file(var.key)
      project = var.project
      region  = var.region
      zone    = var.zone
    }
    
    resource "google_redis_instance" "cache" {
      provider = google-beta
      name = var.instance
      tier = "BASIC"
      memory_size_gb = 1
      location_id = var.zone
      transit_encryption_mode = "SERVER_AUTHENTICATION"
    }
    

    Then to confirm TLS-enabled:

    gcloud redis instances describe ${INSTANCE} \
    --region=${REGION} \
    --project=${PROJECT} \
    --format="value(transitEncryptionMode)"
    SERVER_AUTHENTICATION