1

使用 terraform 时,我正在努力从几个新的 ec2 实例中获取密码。一直在阅读一些帖子,并认为我有它但没有得到任何地方。

这是我的配置:

resource "aws_instance" "example" {
  ami = "ami-06f9d25508c9681c3"
  count         = "2"
  instance_type = "t2.small"
  key_name = "mykey"
  vpc_security_group_ids =["sg-98d190fc","sg-0399f246d12812edb"]
  get_password_data = "true"
}

output "public_ip" {
    value = "${aws_instance.example.*.public_ip}"
}

output "public_dns" {
    value = "${aws_instance.example.*.public_dns}"
}

output "Administrator_Password" {
    value = "${rsadecrypt(aws_instance.example.*.password_data, 
file("mykey.pem"))}"
}

设法清除所有语法错误,但现在运行时出现以下错误:

PS C:\tf> terraform apply
aws_instance.example[0]: Refreshing state... (ID: i-0e087e3610a8ff56d)
aws_instance.example[1]: Refreshing state... (ID: i-09557bc1e0cb09c67)

Error: Error refreshing state: 1 error(s) occurred:

* output.Administrator_Password: At column 3, line 1: rsadecrypt: argument 1 
should be type string, got type list in:

${rsadecrypt(aws_instance.example.*.password_data, file("mykey.pem"))}
4

1 回答 1

3

返回此错误的原因是每个 EC2 实例aws_instance.example.*.password_data的结果列表。password_data每一个都必须用 单独解密rsadecrypt

要在 Terraform v0.11 中执行此操作,需要使用null_resource作为解决方法来实现“for each”操作:

resource "aws_instance" "example" {
  count = 2

  ami                    = "ami-06f9d25508c9681c3"
  instance_type          = "t2.small"
  key_name               = "mykey"
  vpc_security_group_ids = ["sg-98d190fc","sg-0399f246d12812edb"]
  get_password_data      = true
}

resource "null_resource" "example" {
  count = 2

  triggers = {
    password = "${rsadecrypt(aws_instance.example.*.password_data[count.index], file("mykey.pem"))}"
  }
}

output "Administrator_Password" {
    value = "${null_resource.example.*.triggers.password}"
}

从 Terraform v0.12.0 开始,这可以使用新的for表达式结构来简化:

resource "aws_instance" "example" {
  count = 2

  ami                    = "ami-06f9d25508c9681c3"
  instance_type          = "t2.small"
  key_name               = "mykey"
  vpc_security_group_ids = ["sg-98d190fc","sg-0399f246d12812edb"]
  get_password_data      = true
}

output "Administrator_Password" {
  value = [
    for i in aws_instance.example : rsadecrypt(i.password_data, file("mykey.pem"))
  ]
}
于 2019-05-20T17:15:05.480 回答