Today, let’s get into a brief Terraform illustration. It’s beneficial to understand Terraform’s workings, even if you’re not directly responsible for its execution. Here’s a straightforward demonstration of Infrastructure as Code (IaC) employing Terraform to establish a fundamental Amazon Web Services (AWS) infrastructure. In this instance, we’ll generate an AWS EC2 instance and configure a corresponding security group.
# Define the provider (AWS)
provider "aws" {
region = "us-east-1"
}
# Create a security group
resource "aws_security_group" "example_sg" {
name = "example-sg"
description = "Example Security Group"
// Define inbound rules to allow SSH and HTTP traffic
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
# Create an EC2 instance
resource "aws_instance" "example_instance" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 AMI ID
instance_type = "t2.micro"
key_name = "your-key-pair-name" # Replace with your SSH key name
security_groups = [aws_security_group.example_sg.name]
tags = {
Name = "ExampleInstance"
}
}
In this example:
- We define the AWS provider with the desired region.
- We create a security group (‘aws_security_group’) named “example-sg” and specify inbound rules to allow SSH and HTTP traffic.
- We create an EC2 instance (‘aws_instance’) named “example_instance” using the specified Amazon Machine Image (AMI) and instance type. Make sure to replace “your-key-pair-name” with your actual SSH key name.