Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

amazon web services - Terraform find latest ami via data

I'm trying to implement some sort of mechanism where someone can fill in a variable which defines if it's going to deploy an Amazon Linux machine or a self-created packer machine. But for some reason it's not picking up the AWS AMI while it does find my own. Here's the code:

Main.tf of the module:

    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

variables.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"
}

And finally the main.tf which calls on the module:

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

Like i said, it does find the correct image when i'm entering either 2019 or 2016. The error message is as follows:

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

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

Any idea's?

Thanks for the help!

PS: I've emptied some fields on purpose.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AMI name and AMI id are two different things. You are using AMI id (ami-0fb02dcdd38048fb9) to search AMI based on its name. This will not work obviously. You have to replace ami-0fb02dcdd38048fb9 with AMI name.

You haven't specified how you named your linux AMI, maybe Linux2019-CUSTOM*? Whatever the name you've used, you have to use that, not AMI id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...