To find Ubuntu latest AMI, use the following code:
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
If you need to get the Amazon Linux 2 AMI use the following code:
data "aws_ami" "amazon-2" {
most_recent = true
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-ebs"]
}
owners = ["amazon"]
}
Then, in the aws_instance
you need to add the reference to it:
resource "aws_instance" "my-ec2" {
# get ubuntu AMI id
ami = data.aws_ami.ubuntu.id
}
Or, if you use Amazon Linux 2 AMI
resource "aws_instance" "my-ec2" {
# get Amazon Linux 2 AMI
ami = data.aws_ami.amazon-2.id
}