In this tutorial, we'll use Terraform to provision an EC2 instance in the eu-west-2 region with specific configurations, including attaching an Elastic IP, creating a key pair, and installing Nginx on the instance.
Prerequisites:
Terraform installed on your machine.
Access to
/root/terraform-challenges/project-citadel
directory for storing Terraform configuration files.
Terraform Configuration:
Step 1: Create variables.tf
File:
Create a file named variables.tf
and define the variables:
variable "region" {
type = string
default = "eu-west-2"
}
Step 2: Create main.tf
File:
Create a file named main.tf
and define the Terraform resources:
resource "aws_key_pair" "citadel-key" {
key_name = "citadel"
public_key = file("/root/terraform-challenges/project-citadel/.ssh/ec2-connect-key.pub")
}
resource "aws_instance" "web" {
ami = "ami-06178cf087598769c"
instance_type = "m5.large"
key_name = aws_key_pair.citadel-key.key_name
user_data = file("/root/terraform-challenges/project-citadel/install-nginx.sh")
}
resource "aws_eip" "eip" {
instance = aws_instance.web.id
vpc = true
provisioner "local-exec" {
command = "echo ${self.public_dns} >> /root/citadel_public_dns.txt"
}
}
Step 3: Create install-nginx.sh
File:
Create a file named install-nginx.sh
and add the following script:
#!/bin/bash
apt-get update -y
apt-get install nginx -y
Step 4: Initialize and Apply Terraform Configuration:
Initialize Terraform and apply the configuration:
terraform init
terraform apply
Conclusion:
In this tutorial, we used Terraform to provision an EC2 instance with specific configurations, including attaching an Elastic IP, creating a key pair, and installing Nginx on the instance. By following the provided steps, you can efficiently manage AWS infrastructure using Terraform, ensuring consistency and reproducibility in your environment.