使用 Terraform 在没有 "remote_exec" 的情况下安装 NGINX

Using Terraform to install NGINX without "remote_exec"

resource "digitalocean_droplet" "web-server" {
    image = "ubuntu-18-04-x64"
    name = "web-server"
    region = "nyc2"
    size = "s-1vcpu-1gb"
    ssh_keys = [
        var.ssh_fingerprint
    ]
    connection {
        host = digitalocean_droplet.web-server.ipv4_address
        user = "root"
        type = "ssh"
        private_key = file(var.pvt_key)
        timeout = "2m"
    }
    provisioner "remote-exec" {
        inline = [
            "export PATH=$PATH:/usr/bin",
            "sudo apt-get update",
            "sudo apt-get -y install nginx"
        ]
    }
}

目前,我正在使用上面的方法通过 Terraform 在 Digital Ocean droplet 上安装 NGINX,但是还有其他方法可以让 Terraform 管理它的状态吗?我希望能够管理升级、负载平衡等事情,这似乎是一种反模式?

您可以按照 https://www.terraform.io/docs/providers/do/r/droplet.html 中的说明使用 Droplet user_data。

创建一个模板,然后使用呈现的模板作为您的用户数据值

#!/usr/bin/env bash
set -x
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
export PATH="$PATH:/usr/bin"
sudo apt-get update
sudo apt-get -y install nginx

您的资源现在将如下所示:

data "template_file" "userdata" {
  template = "${file("${path.module}/userdata.sh")}"
}


 resource "digitalocean_droplet" "web-server" {
        image = "ubuntu-18-04-x64"
        name = "web-server"
        region = "nyc2"
        size = "s-1vcpu-1gb"
        user_data   "${data.template_file.userdata.rendered}"
        ssh_keys = [
            var.ssh_fingerprint
        ]
    }