簡體   English   中英

如何使用 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)
    }

來源: https : //stackoverflow.com/a/36668395/5454632

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM