试图在terrraform启动的实例上设置Windows主机名



我正在尝试在我通过Terraform从AWS帐户启动的Windows实例上设置主机名。我可以借助主机设置主机名。ps1脚本。但是每次我启动一个新实例时,我都必须手动更改主机内硬编码的主机名。Ps1脚本文件。所以我想在变量的帮助下做到这一点,我可以在运行时指定或使用"Terraform应用"。这是我正在尝试的代码,但它没有发生。

我也想以后在linux平台上做同样的事情,为此我知道我可能不得不使用sh文件来完成,但我不知道确切的过程。

有人能帮我吗?下面是我的代码:

main.tf:

resource "aws_instance" "terra" {


ami = "ami-*****"
instance_type = "t3.xlarge"

tags = {
#Name = "terra-test-Pega8.7"
Name = var.hostname
Accesibility = "Public"

}
subnet_id = "subnet-0ba2da79c625a1513"
security_groups = ["sg-0d433ad46d13b2a0c"]
key_name = "windows-key"

user_data = file("host.ps1 ${var.hostname}")  # (here i tried only the hostname first which 
worked but i wanted to put the hostname in a 
variable later , so i tried this)

}

variable "hostname" {
type = string
description = "Sets a hostname of the created instance"
#default = "terratest"
} 

resource "aws_eip_association" "eip_assoc" {
instance_id   = aws_instance.terra.id
allocation_id = aws_eip.elasticip.id
}
resource "aws_eip" "elasticip" {
vpc = true
}

是主机。ps1文件:

param([String]$hname)
Rename-Computer -NewName $hname -Force -Restart

下面是之前工作的代码

Rename-Computer -NewName 'terratest' -Force -Restart

**实际上我是很新的,所以不太了解这些代码,所以如果有人可以指导,这将是非常有帮助的。提前谢谢你。

你试图传递参数的东西,正在加载一个文件为您的user_data将无法工作。如果希望将terraform变量传递到user_data中,可以尝试将引导脚本内联到terraform文件中:

resource "aws_instance" "terra" {
// Your stuff here
user_data = <<EOF
<powershell>
Rename-Computer -NewName ${var.hostname} -Force -Restart
</powershell>
EOF
}
更简洁的方法是使用template_file:
data "template_file" "user_datapowershell" {
template = <<EOF
<powershell>
Rename-Computer -NewName ${var.hostname} -Force -Restart
</powershell>
EOF
}
resource "aws_instance" "terra" {
// Your stuff here
user_data = data.template_file.user_datapowershell.rendered
}

最新更新