In Terraform, you can use the AWS CLI to retrieve the latest AMI ID with filter options. Lets see with an example, how you can achieve this:
1. Install and configure the AWS CLI on your local machine.
2. In your Terraform configuration file (e.g., main.tf), define a data source using the aws_ami resource type:
data "aws_ami" "base_ami" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
filter {
name = "architecture"
values = ["x86_64"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
3. In your Terraform code, reference the latest AMI ID using the data source defined above:
*architecture just added additionally
resource "aws_instance" "ec2_instance" {
ami = data.aws_ami.base_ami.id
count = "1"
subnet_id = "<your subnet>"
instance_type = "<instance type>"
key_name = "<private_key>"
}
Remember to run terraform init and terraform apply to initialize and apply the changes respectively.
Comments (0)