gpt4 book ai didi

bash - 在 Terraform 中创建随机变量并将其传递给 GCE 启动脚本

转载 作者:行者123 更新时间:2023-12-03 22:03:08 24 4
gpt4 key购买 nike

我想运行一个 metadata_startup_script 使用 Terraform 创建 GCE 实例时。

该脚本应该创建一个用户并为该用户分配一个随 secret 码。

我知道我可以在 Terraform 中创建一个随机字符串,例如:

resource "random_string" "pass" {
length = 20
}

还有我的 startup.sh在某些时候会像:

echo myuser:${PSSWD} | chpasswd

我如何链接 random_string通过 metadata_startup_script 使用适当的脚本调用生成资源范围?

这是 google_compute_instance资源定义:
resource "google_compute_instance" "coreos-host" {
name = "my-vm"
machine_type = "n1-stantard-2"
zone = "us-central1-a"

boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
size = 20
type = "pd-standard"
}
}

network_interface {
network = "default"

access_config {
network_tier = "STANDARD"
}
}

metadata_startup_script = "${file("./startup.sh")}"

}

哪里 startup.sh包括以上行以非交互方式设置密码。

最佳答案

如果要将 Terraform 变量传递到模板化文件中,则需要使用模板。
在 Terraform <0.12 中,您需要使用 template_file data source像这样:

resource "random_string" "pass" {
length = 20
}

data "template_file" "init" {
template = "${file("./startup.sh")}"
vars = {
password = "${random_string.pass.result}"
}
}

resource "google_compute_instance" "coreos-host" {
name = "my-vm"
machine_type = "n1-stantard-2"
zone = "us-central1-a"

boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
size = 20
type = "pd-standard"
}
}

network_interface {
network = "default"

access_config {
network_tier = "STANDARD"
}
}

metadata_startup_script = "${data.template_file.startup_script.rendered}"
}
并更改您的 startup.sh脚本为:
echo myuser:${password} | chpasswd
请注意,模板使用 ${}用于对 Terraform 传递到脚本的变量进行插值。如果您需要使用 $脚本中的任何其他地方,那么你需要使用 $$ 来转义它获得文字 $在您渲染的脚本中。
在 Terraform 0.12+ 中有新的 templatefile function可以用来代替 template_file如果您愿意,可以使用数据源:
resource "random_string" "pass" {
length = 20
}

resource "google_compute_instance" "coreos-host" {
name = "my-vm"
machine_type = "n1-stantard-2"
zone = "us-central1-a"

boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
size = 20
type = "pd-standard"
}
}

network_interface {
network = "default"

access_config {
network_tier = "STANDARD"
}
}

metadata_startup_script = templatefile("./startup.sh", {password = random_string.pass.result})
}

顺便说一句,您还应该注意 random_string 上的警告。 :

This resource does use a cryptographic random number generator.

Historically this resource's intended usage has been ambiguous as the original example used it in a password. For backwards compatibility it will continue to exist. For unique ids please use random_id, for sensitive random values please use random_password.


因此,您应该改用 random_password resource :
resource "random_password" "password" {
length = 16
special = true
override_special = "_%@"
}

关于bash - 在 Terraform 中创建随机变量并将其传递给 GCE 启动脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58522142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com