user15224751
user15224751

Reputation:

Unable to run metadata_startup_script in Terraform

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?

Upvotes: 1

Views: 12789

Answers (2)

Wojtek_B
Wojtek_B

Reputation: 4443

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.

Upvotes: 0

guillaume blaquiere
guillaume blaquiere

Reputation: 76073

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
  }

Upvotes: 2

Related Questions