【问题标题】:Unable to run metadata_startup_script in Terraform无法在 Terraform 中运行 metadata_startup_script
【发布时间】:2021-09-13 07:04:25
【问题描述】:

我有一个 terraform 脚本

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
}

现在我想运行 metadata_startup_script,但它不会执行。创建资源但不执行脚本。我怎样才能运行这个脚本? 基本上我有一个很大的 bash 脚本。如何在 GCP 机器上运行此脚本?

【问题讨论】:

    标签: google-cloud-platform terraform terraform-provider-gcp


    【解决方案1】:

    如果您要运行大型脚本,我建议您使用 startup-script-url 从 GCS 加载启动脚本,而不是将其硬编码到 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"
      }
     ...
     ...
    }
    

    否则,对于您当前的问题,我还建议使用元数据

      metadata = {
        startup-script = <<-EOF
      echo "hello
      you" > /test.txt
      echo "help
      me" > /test2.txt
      EOF
      }
    

    【讨论】:

    • 对不起,我脑子里很明显!!您必须在资源计算引擎实例中使用它。查看我的更新,如果更清楚,请告诉我!
    • 但我想运行本地脚本而不是 URL
    • 我也确实喜欢生成一个 ssh 密钥(使用 mobaxtrem 的公共和私有),然后使用像这样的元数据 metadata = { ssh-keys = "${rohan}:${file(C:/ user/rohan/desktop/public)}" } 以及连接参数配置器“remote-exec” { connection { host = google_compute_address.static.address type = "ssh" user = var.user timeout = "500s" private_key = file (C:/user/rohan/desktop/public.ppk) } 但使用它也无法执行脚本
    • 不用担心,您可以使用第二个代码示例,其中不使用文件,而是直接使用 medata 密钥对中的代码。我刚刚测试过,效果很好:)
    • 但我有一个大约 50 多行的大脚本,所以这不是最佳做法,所以你能告诉我如何通过 ssh 连接到我的 gcp 机器
    【解决方案2】:

    您可能会发现有关运行启动脚本的文档很有用;

    可以使用三种方法运行启动脚本:

    • 本地文件
    • 来自元数据
    • 云存储桶

    使用所有方法 (they can be up to 256 KB or more for GCS) 甚至可以运行 ~50 行脚本。如果您在创建新 VM 时不能/不想使用本地文件或将脚本放入元数据中,则可以将其存储在 GCS 存储桶中。

    如果这不能满足您的需求,那么使用 ansible as guillaume blaquiere said 是一个非常好的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-01
      • 2023-04-02
      • 2020-10-04
      • 2021-07-21
      • 2018-05-23
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多