By Brian Fitzgerald
Introduction
Using Terraform, you can launch an AWS EC2 instance from any account and any region using a public AMI identified only by image name. Because you do not need to lookup the image id each time, your code can be simplified.
Approach
Red Hat account number
In the AWS console, notice that the Red Hat, Inc. account number is 309956199498.

AMI name
Find the Red Hat AMI image by name. In the console, navigate to EC2 Images AMIs. Filter on Owner: 309956199498, Architecture: 64-bit (x86), Virtualization type: HVM.
For example, “RHEL-7.9_HVM_GA-20200917-x86_64-0-Hourly2-GP2”. You could also search using the AWS command line:
$ aws ec2 describe-images --owners 309956199498 --filters "` cat filters.ami.json `" --region us-east-2
where filters.ami.json contains:
[
{
"Name": "architecture",
"Values": [
"x86_64"
]
},
{
"Name": "virtualization-type",
"Values": [
"hvm"
]
}
]
Terraform data source
Define a Terraform aws_ami data source.
ami-rhel.tf
data "aws_ami" "rhel" {
most_recent = true
owners = [
"309956199498"
]
filter {
name = "name"
values = [
"RHEL-7.9_HVM_GA-20200917-x86_64-0-Hourly2-GP2"
]
}
}
aws instance resource
Use the data source in your Terraform aws_instance resource
provider "aws" {
region = var.region
}
resource "aws_instance" "your-ec2-rsrc" {
ami = data.aws_ami.rhel.image_id
and so on . . .
Launch the ec2 instance
Run “terraform apply”. Terraform determines the AMI ID. For example, ami-0d2bf41df19c4aac7.
Conclusion
By using the Terraform AWS AMI data source, you can launch a public AMI from any account and region. The AMI ID is different for each account and region.

