skip to Main Content

I have a terraform script

resource "google_compute_attached_disk" "default3" {
  disk     = google_compute_disk.default2.id
  instance = google_compute_instance.default.id
}

resource "google_compute_instance" "default" {
  name         = "test"
  machine_type = "custom-8-16384"
  zone         = "asia-south1-a"

  tags = ["foo", "bar"]

  boot_disk {
    initialize_params {
      image = "centos-cloud/centos-7"
    }
  }

  network_interface {
    network = "default"

    access_config {
      
    }
  }
    metadata_startup_script = <<-EOF
  echo "hello
  you" > /test.txt
  echo "help
  me" > /test2.txt
  EOF


  lifecycle {
    ignore_changes = [attached_disk]
  }
}

resource "google_compute_disk" "default2" {
  name  = "test-disk"
  type  = "pd-balanced"
  zone  = "asia-south1-a"
  image = "centos-7-v20210609"
  size =  100
}

Now I want to run metadata_startup_script, but it won`t execute. Resources are created but the script is not executed. How can I run this script?
Basically I have a big bash script. How can I run this script in GCP machine?

2

Answers


  1. If you have a large script to run, I recommend you to use startup-script-url to load the startup script from GCS instead of having it hardcoded in the terraform.

    resource "google_compute_instance" "default" {
      name         = "test"
      machine_type = "custom-8-16384"
      zone         = "asia-south1-a"
    
      metadata = {
        startup-script-url = "gs://<bucket>/path/to/file"
      }
     ...
     ...
    }
    

    Else, for your current issue, I also recommend to use the metadata

      metadata = {
        startup-script = <<-EOF
      echo "hello
      you" > /test.txt
      echo "help
      me" > /test2.txt
      EOF
      }
    
    Login or Signup to reply.
  2. You may find documentation on running startup scripts useful;

    Startup script can be ran using three methods:

    • local file
    • from metadata
    • cloud storage bucket

    Even ~50 line script can be run using all the methods (they can be up to 256 KB or more for GCS). If you can’t / don’t want to use local file nor put the script in the metadata while creating a new VM you can store it in a GCS bucket.

    If that doesn’t answer your needs then using ansible as guillaume blaquiere said is a very good choice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search