Creating EC2 Instances using Terraform

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2021-09-24
Terraform: Automating Infrastructure Deployment and Creating an AWS EC2 Instance
This article explores Terraform, a powerful open-source tool for automating infrastructure deployments, and demonstrates its use in creating an Amazon Elastic Compute Cloud (EC2) instance. Terraform's strength lies in its ability to manage infrastructure across various cloud providers and even on-premises solutions, handling both low-level components like compute, storage, and networking, as well as higher-level components such as SaaS applications and DNS services. This automation significantly streamlines the process of building and managing infrastructure, improving efficiency and reducing errors.
Terraform uses a declarative configuration language designed specifically for infrastructure automation. The core concept revolves around resources. A resource represents a single component of infrastructure, such as a virtual machine, a network, or a database. Groups of related resources can be organized into modules, representing larger, more complex units of configuration. The language itself is structured with blocks, which define the type and properties of a resource; arguments, specifying the settings for each resource; and expressions, allowing for dynamic values and calculations within the configuration.
To illustrate Terraform's capabilities, let's examine the process of creating an EC2 instance. This involves several steps and configuration files. First, we need a development environment. While any text editor will suffice, using an Integrated Development Environment (IDE) such as Visual Studio Code with a Terraform extension is highly recommended. These extensions provide helpful features like syntax highlighting and code completion, significantly improving the development experience.
Before we begin, access to an AWS account is essential. Specifically, we require an AWS Command Line Interface (CLI) user with the necessary permissions to create EC2 instances and security groups. The level of permission required is dependent on the specific actions undertaken in the Terraform code, but for the purpose of this example, a user with full access is adequate. This user's access key ID and secret access key are crucial for authenticating Terraform with AWS.
The configuration is typically spread across several files. The variables.tf file stores variables used throughout the configuration. This includes details like the AWS region, the access key ID and secret access key for the designated AWS user, and parameters specific to the EC2 instance, such as instance type, AMI ID (Amazon Machine Image), and key pair name. This separation of variables keeps the main configuration cleaner and allows for easy modification of settings without altering the core infrastructure setup.
Another critical file is provider.tf. This file specifies the cloud provider Terraform will interact with – in our case, AWS. It contains the necessary credentials to connect to the AWS account, using the access key ID and secret access key defined in the variables.tf file. This file acts as a bridge between Terraform and the AWS infrastructure.
The core of the EC2 instance creation lies in ec2.tf and securitygroup.tf. securitygroup.tf defines the security group for the EC2 instance, essentially acting as a virtual firewall. Security groups control inbound and outbound network traffic, allowing only specified ports and protocols to pass through. This example creates a security group that allows inbound traffic on port 22 (SSH) and allows all outbound traffic. Note that in a production environment, this rule should be significantly more restrictive, only permitting necessary inbound and outbound traffic.
The ec2.tf file then defines the EC2 instance itself. It references the security group defined in securitygroup.tf and other variables from variables.tf, such as the AMI ID, instance type, and key pair. This file outlines the specifics of the EC2 instance's creation, including its resources and configurations.
Finally, outputs.tf defines what information Terraform will output after the infrastructure is created. This might include the ID of the security group, the ID of the EC2 instance, its current status (e.g., running, stopped), and public IP address. This provides a concise summary of the deployment's outcome.
Once these files are prepared, navigating to the project directory and executing Terraform commands from the terminal initiates the process. The first command, terraform init, initializes the Terraform workspace, downloading the necessary providers (in this case, the AWS provider). terraform plan then creates an execution plan, showing exactly what changes Terraform intends to make. This is a critical step, allowing for review before any changes are actually applied to the AWS infrastructure. Only after reviewing and approving the plan is the final command, terraform apply, executed. This command creates the resources defined in the configuration files on AWS.
After successful execution, the AWS console can be used to verify the creation of the security group and EC2 instance. The security group, with a name like "terraform-ec2-sg," should be visible. Similarly, the EC2 instance will be listed, showing its running status and other pertinent information.
The importance of using Terraform, and other Infrastructure as Code (IaC) tools, is far-reaching. It provides a repeatable, version-controlled method for managing infrastructure. Changes are tracked, making it easier to understand how infrastructure has evolved over time. Automated deployment minimizes manual errors, and the declarative nature of the configuration means that the desired state of the infrastructure is explicitly defined, regardless of its current state. This ensures consistency and reduces the risk of configuration drift. Furthermore, the ability to easily destroy infrastructure with the terraform destroy command offers considerable flexibility and reduces manual cleanup.
In conclusion, Terraform offers a streamlined and efficient method for managing infrastructure. This article provided a practical example of using Terraform to create an EC2 instance on AWS, highlighting the key concepts and the configuration files involved. This approach promotes consistency, repeatability, and reduces the risk of human error in infrastructure management, ultimately making it a vital tool for any organization managing cloud resources.