A Terraform configuration for an AWS VPC and an EC2 instance running Amazon Linux 2023
Demonstrates how to provision the following resources in AWS with Terraform:
- A VPC with a single subnet and an Internet gateway
- An EC2 instance running Amazon Linux 2023 with SELinux disabled via kernel command-line parameters configured via instance user data
- An IAM role and associated instance profile that allow connections to the instance using Session Manager
- An AWS account
- Administrative privileges in the AWS account (e.g. access to an IAM user or role that has the AdministratorAccess AWS managed IAM policy attached)
- The following software:
- Git
- Terraform (version 1.0 or later)
- SSH
- AWS CLI configured with credentials for the aforementioned privileges
The following instructions use AWS CloudShell, a browser-based shell that simplifies deployment by providing a predictable, reproducible environment.
- Log into the AWS Management Console and launch CloudShell.
- Install plugin for DNF.
sudo dnf install -y 'dnf-command(config-manager)'
- Add the Terraform repository.
sudo dnf config-manager \ --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
- Install the terraform package.
sudo dnf install -y terraform
- Clone the repository.
git clone https://github.com/RhubarbSin/terraform-aws-vpc-ec2-amazon-linux-2023-example.git
- Change to the repository’s directory.
cd terraform-aws-vpc-ec2-amazon-linux-2023-example
- Initialize the working directory.
terraform init
- Validate the configuration.
terraform validate
- Generate an execution plan to see what actions Terraform would take to apply the current configuration.
terraform plan
- Create the infrastructure.
terraform apply -auto-approve
- After a few minutes, the EC2 instance should be running and can be accessed via SSH or Session Manager.
- Log into the instance with SSH:
ssh -o StrictHostKeyChecking=no \ -i $(terraform output -raw ssh_key_file_name) \ ec2-user@$(terraform output -raw instance_public_ip)
Type
exit
to log out. - Log into the instance with Session Manager:
aws ssm start-session \ --target $(terraform output -raw instance_id) \ --region $(terraform output -raw instance_region)
Type
exit
to log out.
- Log into the instance with SSH:
- When finished, delete all of the resources by destroying the infrastructure.
terraform apply -destroy -auto-approve
The resources deployed include the following:
- One VPC with an Internet gateway and inbound SSH access allowed on port 22 by the default security group
- One key pair to connect to the instance using SSH
- One IAM role that enables AWS Systems Manager service core functionality and associated instance profile
- One EC2 instance with an Elastic IP