How do you get latest AMI ID for AWS instance in Terraform script?
June 28, 2023 2023-06-28 17:22How do you get latest AMI ID for AWS instance in Terraform script?
This post could walk you through how to get latest Amazon Linux2 operating system when you create an EC2
instance by the Terraform. before you can launch an instance, we must choose an AMI from which to launch the instance.
Generally have to understand the following requirements you might have for the instances that you want to launch.
- The AWS Region [ we selected “us-west-2” ]
- The operating system [we selected “Amazon Linux2” ]
- The architecture: 32-bit (i386), 64-bit (x86_64), or 64-bit ARM (arm64) [we selected “x86_64” ]
- The root device type: Amazon EBS or instance store [we selected “EBS” ]
- The provider (for example, Amazon Web Services)
- Additional software (database)
In your Terraform configuration file (e.g., main.tf), define a data source using the aws_ami resource type:
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"]
}
}
I hope, added all the filter option which are mentioned on the above requirements.
resource "aws_instance" "ec2_instance" {
ami = data.aws_ami.base_ami.id
count = "1"
instance_type = "t3a.medium"
security_groups = [aws_security_group.myteam-web.id]
subnet_id = "${var.private-subnets}"
}
Remember to run terraform init and terraform apply to initialize and apply the changes respectively, add additional parameters with apply option if it’s required.
$ terraform init
$ terraform apply