我正在尝试从AMI创建Windows Ec2实例,并以如下方式执行powershell命令:
data "aws_ami" "ec2-worker-initial-encrypted-ami" {
filter {
name = "tag:Name"
values = ["ec2-worker-initial-encrypted-ami"]
}
}
resource "aws_instance" "my-test-instance" {
ami = "${data.aws_ami.ec2-worker-initial-encrypted-ami.id}"
instance_type = "t2.micro"
tags {
Name = "my-test-instance"
}
provisioner "local-exec" {
command = "C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeInstance.ps1 -Schedule",
interpreter = ["PowerShell"]
}
}
而且我面临以下错误:
- aws_instance.my-test-instance: Error running command 'C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1 -Schedule': exit status 1. Output: The term 'C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:72
- C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1 <<<< -Schedule
- CategoryInfo : ObjectNotFound: (C:\ProgramData...izeInstance.ps1:String) [], CommandNotFoundException
- FullyQualifiedErrorId : CommandNotFoundException
最佳答案
您正在使用 local-exec
供应商,该供应商在运行Terraform的工作站上运行请求powershell代码:
The local-exec provisioner invokes a local executable after a resource is created. This invokes a process on the machine running Terraform, not on the resource.
听起来您想在结果实例上执行powershell脚本,在这种情况下,您需要使用
remote-exec
资源调配器,它将在目标资源上运行powershell:The remote-exec provisioner invokes a script on a remote resource after it is created. This can be used to run a configuration management tool, bootstrap into a cluster, etc.
您还需要包括connection详细信息,例如:
provisioner "remote-exec" {
command = "C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeInstance.ps1 -Schedule",
interpreter = ["PowerShell"]
connection {
type = "winrm"
user = "Administrator"
password = "${var.admin_password}"
}
}
这意味着该实例还必须准备好接受WinRM连接。
但是,还有其他选项可以完成此任务。例如使用userdata,which Terraform also supports。这可能类似于以下示例:
在Terraform中使用userdata文件的示例
名为
userdata.txt
的文件:<powershell>
C:\\ProgramData\\Amazon\\EC2-Windows\\Launch\\Scripts\\InitializeInstance.ps1 -Schedule
</powershell>
使用userdata文件启动实例:
resource "aws_instance" "my-test-instance" {
ami = "${data.aws_ami.ec2-worker-initial-encrypted-ami.id}"
instance_type = "t2.micro"
tags {
Name = "my-test-instance"
}
user_data = "${file(userdata.txt)}"
}
file interpolation将以字符串形式读取用户数据文件的内容,以传递给用户数据以启动实例。实例启动后,它应按预期运行脚本。
关于amazon-web-services - 如何通过Terraform执行PowerShell命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50604127/