Terraform 通过数据查找最新的 ami

时间:2021-01-12 15:19:58

标签: amazon-web-services terraform terraform-provider-aws terraform0.12+

我正在尝试实现某种机制,让某人可以填写一个变量,该变量定义是要部署 Amazon Linux 机器还是自创的打包机。但出于某种原因,它没有选择 AWS AMI 而它确实找到了我自己的。代码如下:

模块的Main.tf:

    data "aws_ami" "latest" {
  most_recent = true
  owners      = [var.owner]

  filter {
    name   = "name"
    values = [lookup(var.default_ami, var.ami)]
  }
}

resource "aws_instance" "test-ec2deployment" {
  ami                         = data.aws_ami.latest.id

变量.tf:

variable "default_ami" {
  type        = map
  description = "Choose windows 2016 or 2019"
  default = {
    "2016"  = "WIN2016-CUSTOM*"
    "2019"  = "WIN2019-CUSTOM*"
    "linux" = "ami-0fb02dcdd38048fb9"
  }
}

#Above are the options, here you need to make a decision.
variable "ami" {
  description = "You can either choose the 2019 or the 2016 image or the linux image."
  default     = "2019"
}

最后是调用模块的 main.tf:

module "aws_instance" {
  shared_credentials_file = ""
  source                  = ""
  env_name                = ""
  volume_size             = "60"
  ami                     = "linux"
}

就像我说的,当我进入 2019 或 2016 时,它确实找到了正确的图像。错误信息如下:

module.aws_instance.data.aws_ami.latest: Refreshing state...

Error: Your query returned no results. Please change your search criteria and try again.

有什么想法吗?

感谢您的帮助!

PS:我故意清空了一些字段。

2 个答案:

答案 0 :(得分:1)

AMI 名称和 AMI id 是两个不同的东西。您正在使用 AMI id (ami-0fb02dcdd38048fb9) 根据名称搜索 AMI。这显然不会起作用。您必须将 ami-0fb02dcdd38048fb9 替换为 AMI 名称。

您尚未指定如何命名 linux AMI,也许是 Linux2019-CUSTOM*?无论您使用什么名称,都必须使用该名称,而不是 AMI id。

答案 1 :(得分:0)

Marcin 的回答恰到好处。 AMI 名称和 AMI id 是两个不同的东西,您不能使用 AMI id 根据名称搜索 AMI。要使用 AMI id,您需要使用“image-id”过滤器。要获取可用于搜索 AMI 的完整过滤器列表,请选中 this

现在来解决您的问题。您可以同时使用“name”和“image-id”过滤器来获取所需的 AMI。如果您对它们中的任何一个都没有价值,请使用“*”。我是通过以下方式解决的 -

variable "ami" {
  description = "You can either choose the 2019 or the 2016 image or the linux image."
  default     = "2019"
}

variable "default_ami" {
  type = map(any)
  default = {
    "linux" = {
      name = "*"
      ami_id = "ami-0fb02dcdd38048fb9"
    },
    "2016" = {
      name = "WIN2016-CUSTOM*"
      ami_id = "*"
    },
    "2019" = {
      name = "WIN2019-CUSTOM*"
      ami_id = "*"
    }
  }
}

data "aws_ami" "latest" {
  most_recent = true
  owners      = [var.owner]

  filter {
    name   = "name"
    values = ["${var.default_ami[var.ami]["name"]}"]
  }
  filter {
    name   = "image-id"
    values = ["${var.default_ami[var.ami]["ami_id"]}"]
  }
}

resource "aws_instance" "test-ec2deployment" {
  ami = data.aws_ami.latest.id
  instance_type = var.instance_type
}
相关问题