how to get the ec2 ami id using the ec2 name in terraform

Viewed 17
data "aws_instance" "ec2_blue" {
  instance_tags = {
    Name = "dev-blue"
  }
}
ami_siebel_server = "${data.aws_instance.ec2_blue.ami == "" ? data.aws_ami.ami_siebel_server.id : data.aws_instance.ec2_blue.ami}"

i was trying to get the ami id from the ec2 if the ec2 already created with the name"dev2-blue" . if the ec2 is not created with the name "dev-blue" then i was trying to fetch the latest ami. I can only give the ec2 name which is unique. But i was getting the below error : Error: Your query returned no results. Please change your search criteria and try again.

on infrastructure.tf line 117, in data "aws_instance" "ec2_blue": 117: data "aws_instance" "ec2_blue" {

There is already an ec2 is created with this name "dev2-blue" but still that was showing above error can someone help me how to resolve this.

1 Answers
data "aws_instance" "ec2_blue" {
  filter {
    name   = "tag:Name"
    values = ["dev-blue"]
  }
}

# get ami id
data.aws_instance.ec2_blue.ami

This should do the trick for you.

Related