Search code examples
google-cloud-platformterraformgoogle-compute-enginekubectl

installing kubectl in GCP compute engine using terraform


Need to add multiple commands in metadata_startup_script in terraform script to launch compute engine instance in GCP

Following is my code

  metadata_startup_script = "curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" ; chmod +x kubectl ; sudo cp kubectl /usr/local/bin"

terraform plan shows below error

   Error: Missing newline after argument

  on main.tf line 58, in resource "google_compute_instance" "default":
  58: metadata_startup_script = "curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" ; chmod +x kubectl ; sudo cp kubectl /usr/local/bin"

  An argument definition must end with a newline.

Any suggestions to resolve this ? The task is to install kubectl once a compute engine is launched using below commands

   curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" 
   chmod +x kubectl 
   sudo cp kubectl /usr/local/bin"

Solution

  • You have 2 solution

    1. Escape the double quote "
      metadata_startup_script = "curl -LO \"https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl\" ; chmod +x kubectl ; sudo cp kubectl /usr/local/bin"
    
    1. Write your script in multiline inside the TF file
    metadata_startup_script = <<SCRIPT
       curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" 
       chmod +x kubectl 
       sudo cp kubectl /usr/local/bin
    SCRIPT