如何使用 terraform 运行 gcp vm 中的 bash 脚本

how to run a bash script in gcp vm using terraform

各位干草, 我想 运行 gcp 机器中的一个脚本,为此我在文件

下创建了一个资源
  disk     = google_compute_disk.default2.id
  instance = google_compute_instance.default.id
} # aatach disk to vm

resource "google_compute_firewall" "firewall" {
  name    = "gritfy-firewall-externalssh"
  network = "default"
  allow {
    protocol = "tcp"
    ports    = ["22"]
  }
  source_ranges = ["0.0.0.0/0"] 
  target_tags   = ["externalssh"]
} # allow ssh

resource "google_compute_address" "static" {
  name = "vm-public-address"
  project = "fit-visitor-305606"
  region = "asia-south1"
  depends_on = [ google_compute_firewall.firewall ]
} # reserve ip

resource "google_compute_instance" "default" {
  name         = "new"
  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 { 
        nat_ip = google_compute_address.static.address     
    }
  }
  metadata = {
    ssh-keys = "${var.user}:${file(var.publickeypath)}"
  }
  lifecycle {
    ignore_changes = [attached_disk]
  }
    provisioner "file" {
    source      = "autoo.sh"
    destination = "/tmp/autoo.sh"
  }
provisioner "remote-exec" {
    connection {
      host        = google_compute_address.static.address
      type        = "ssh"
      user        = var.user
      timeout     = "500s"
      private_key = file(var.privatekeypath)
    }
    inline = [
      "sudo yum -y install epel-release",
      "sudo yum -y install nginx",
      "sudo nginx -v",
    ]
  }
} # Create VM

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

使用这个我可以创建 VM 和磁盘,也可以将 vm 附加到磁盘但不能 运行 我的脚本

错误日志是=

私钥部分工作正常,密钥已分配给 VM,我尝试连接它所连接的那个密钥,可能只有提供部分有问题 任何帮助或指导都会很有帮助...

如错误消息所述,您需要配置供应商的连接。此外,您还需要 运行 脚本的 remote-exec provisoner。

    provisioner "file" {
    source = "autoo.sh"
    destination = "/tmp/autoo.sh"
    connection {
        type = "ssh"
        user = var.user
        private_key = file(var.privatekeypath)
    }
  }
    provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/autoo.sh",
      "cd /tmp",
      "./autoo.sh"
    ]
    connection {
        type = "ssh"
        user = var.user
        private_key = file(var.privatekeypath)
    }

来源: