A step-by-step guide for AWS EC2 provisioning using Terraform: Automating aws ec2 ubuntu AMIs using terraform aws_ami data source — Part 8

Joel Wembo
6 min readJun 22, 2024

--

Part — 8 This blog post provides a detailed, step-by-step guide to provisioning an Ubuntu EC2 instance on AWS using Terraform, an open-source Infrastructure as Code (IaC) tool. The tutorial focuses on using Amazon Machine Images (AMI) to ensure that the EC2 instance is configured with the latest Ubuntu operating system.

A step-by-step guide for AWS EC2 provisioning using Terraform: Automating aws ec2 ubuntu AMIs using terraform aws_ami data source — Part 8

To enhance readability, this handbook is divided into chapters and split into parts. The first, part, “A step-by-step guide for AWS EC2 provisioning using Terraform: HA, ALB, VPC, and Route53 — Part 1”, and the second part “A step-by-step guide for AWS EC2 provisioning using Terraform: HA, CloudFront, WAF, and SSL Certificate — Part 2”, and “A step-by-step guide for AWS EC2 provisioning using Terraform: Cloud Cost Optimization, AWS EC2 Spot Instances — Part 3”, was covered in a separate article to keep the reading time manageable and ensure focused content. The next part or chapter will be published in the next post, upcoming in a few days, “A step-by-step guide for AWS EC2 provisioning using Terraform: VPC peering, VPN, Site-to-site Connection, tunnels ( multi-Cloud ) — Part 12“ and so much more !!

Deploying cloud infrastructure efficiently and consistently is crucial in today’s fast-paced IT environments. This article provides a detailed, step-by-step guide to provisioning an Ubuntu EC2 instance on AWS using Terraform, an open-source Infrastructure as Code (IaC) tool.

The tutorial focuses on using Amazon Machine Images (AMI) to ensure that the EC2 instance is configured with the latest Ubuntu operating system. By leveraging Terraform’s scripting capabilities, users can automate the creation of EC2 instances, manage security groups, and maintain infrastructure as code. This approach not only simplifies deployments but also ensures that instances are launched with a standardized, up-to-date AMI, enhancing reliability and security.

Terraform Solution : List of AMI specific to ubuntu 20.04 LTS AWS

Visit https://cloud-images.ubuntu.com/locator/ec2/

Amazon EC2 AMI Locator
# Terraform provision AWS EC2 instance with S3 State Management


# Fetch the latest Ubuntu AMI
data "aws_ami" "ubuntu" {
most_recent = true
# owners = ["059978233428"] # Canonical's AWS account ID
owners = ["amazon"]


filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}

filter {
name = "virtualization-type"
values = ["hvm"]
}
}
# AWS EC2 Instance A
resource "aws_instance" "prodxcloud-lab-1" {
# ami = var.instance_ami # ami id from variable.tf
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
# subnet_id = var.instance_subnet_id # Custom using subnet id using variable.tf
subnet_id = element(aws_subnet.public_subnets.*.id, 1) # dynamic via terraform vpc.tf
associate_public_ip_address = var.publicip
key_name = var.instance_keyName

# Remote Provisioner execution using bash scipt file
# Establishes connection to be used by all

provisioner "file" {
source = "user_data.sh"
destination = "/tmp/user_data.sh"

# SSH Connection via terraform
connection {
type = "ssh"
user = "ubuntu"
host = self.public_ip
private_key = file("${path.module}/prodxcloud-ec2-keypair-1.pem")
}

}

# Remote Provisioner for User-Data inline commands
provisioner "remote-exec" {
# inline = [
# "sudo apt-get update",
# "sudo apt-get install -y nginx",
# "sudo systemctl start nginx",
# "sudo systemctl enable nginx",
# "sudo chmod -R 777 /var/www/html",
# "sudo echo “User Data Installed by Terraform $(hostname -f)” >> /var/www/html/index.html"
# ]
# generic remote provisioners (i.e. file/remote-exec) with file
inline = [
"chmod +x /tmp/user_data.sh",
"/tmp/user_data.sh",
]
# SSH connection via terraform
connection {
type = "ssh"
user = "ubuntu"
host = self.public_ip
private_key = file("${path.module}/prodxcloud-ec2-keypair-1.pem")

}
}
# remote exec end here

# Attaching security group
vpc_security_group_ids = [
aws_security_group.prodxcloud-SG.id
]
root_block_device {
delete_on_termination = false
volume_size = 50
volume_type = "gp2"
}
tags = {
Name = "prodxcloud-lab-1"
Environment = "DEV"
OS = "UBUNTU"
Managed = "PRODXCLOUD"
}

depends_on = [aws_security_group.prodxcloud-SG, aws_vpc.prodxcloud-vpc, aws_subnet.public_subnets]

//end
}

Data Source for AMI:

  • The data "aws_ami" "ubuntu" block fetches information about the latest Ubuntu AMI.
  • most_recent = true ensures that the most recent AMI is selected.
  • owners = ["xxxxxxxxxx"] specifies the owner of the AMI, which is Canonical (the organization behind Ubuntu).
  • The filter blocks define criteria to filter the AMIs:
  • The first filter selects AMIs with names that match the specified pattern (Ubuntu 20.04).
  • The second filter ensures the AMI uses hardware virtual machine (HVM) virtualization.
terraform init
terraform plan
terraform apply
A step-by-step guide for AWS EC2 provisioning using Terraform: Automating aws ec2 ubuntu AMIs using terraform aws_ami data source — Part 8 by Joel Wembo
A step-by-step guide for AWS EC2 provisioning using Terraform: Automating aws ec2 ubuntu AMIs using terraform aws_ami data source — Part 8

Good !!

Update: Once you are done with this tutorial, you might to check up a follow-up tutorial on the next part, A step-by-step guide for AWS EC2 provisioning using Terraform: EC2 Auto scaling using Terraform for high availability and resource optimization — Part 9

Conclusion

In conclusion, Terraform empowers you to streamline and automate the provisioning of AWS EC2 instances with Ubuntu AMIs. This approach offers several benefits: improved consistency and repeatability across deployments, reduced manual configuration errors, and easier infrastructure management at scale. With Terraform’s declarative configuration language and data sources like aws_ami, you can define your desired infrastructure state and let Terraform handle the creation and configuration of your EC2 instances efficiently.

To enhance readability, this handbook is divided into chapters and split into parts. The first, part, “A step-by-step guide for AWS EC2 provisioning using Terraform: HA, ALB, VPC, and Route53 — Part 1”, and the second part “A step-by-step guide for AWS EC2 provisioning using Terraform: HA, CloudFront, WAF, and SSL Certificate — Part 2”, and “A step-by-step guide for AWS EC2 provisioning using Terraform: Cloud Cost Optimization, AWS EC2 Spot Instances — Part 3”, was covered in a separate article to keep the reading time manageable and ensure focused content. The next part or chapter will be published in the next post, upcoming in a few days, “A step-by-step guide for AWS EC2 provisioning using Terraform: VPC peering, VPN, Site-to-site Connection, tunnels ( multi-Cloud ) — Part 12“ and so much more !!

Thank you for Reading !! 🙌🏻, don’t forget to subscribe and give it a CLAP 👏, and if you found this article useful contact me or feel free to sponsor me to produce more public content. see me in the next article.🤘

About me

I am Joel Wembo, AWS certified cloud Solutions architect, Back-end developer, and AWS Community Builder, I‘m based in the Philippines 🇵🇭; and currently working at prodxcloud as a DevOps & Cloud Architect. I bring a powerful combination of expertise in cloud architecture, DevOps practices, and a deep understanding of high availability (HA) principles. I leverage my knowledge to create robust, scalable cloud applications using open-source tools for efficient enterprise deployments.

I’m looking to collaborate on AWS CDK, AWS SAM, DevOps CI/CD, Serverless Framework, CloudFormation, Terraform, Kubernetes, TypeScript, GitHub Actions, PostgreSQL, and Django.”

For more information about the author ( Joel O. Wembo ) visit:

Links:

References

--

--

Joel Wembo

I am a Cloud Solutions Architect at prodxcloud. Expert in AWS, AWS CDK, EKS, Serverless Computing and Terraform. https://www.linkedin.com/in/joelotepawembo