Terraform Challenge-3
This blog consists of a set of challenges that will assist you in mastering provisioning and managing infrastructure using Terraform.
Signup to KodeKloud for performing this challenge. It's free!!!
Architecture Diagram
Challenge
In this challenge, we will implement a simple EC2 instance with some preinstalled packages.
The requirements in detail:
Create a terraform key-pair
citadel-key
with key_namecitadel
.Upload the public key
ec2-connect-key.pub
to the resource. You may use thefile function
to read the public key at/root/terraform-challenges/project-citadel/.ssh
AMI: ami-06178cf087598769c, use variable named
ami
Region: eu-west-2, use variable named
region
Instance Type: m5.large, use variable named
instance_type
Elastic IP address attached to the EC2 instance
Create a local-exec provisioner for the
eip
resource and use it to print the attribute calledpublic_dns
to a file/root/citadel_public_dns.txt
on the iac-serverInstall Nginx on the citadel instance, and make use of the
user_data
argument.
Using the file function or by making use of the heredoc syntax, use the script calledinstall-nginx.sh
as the value for the user_data argument.
Solution:
1. Declare variables
variables.tf
variable "ami" {
type = string
default = "ami-06178cf087598769c"
}
variable "region" {
type = string
default = "eu-west-2"
}
variable "instance_type" {
type = string
default = "m5.large"
}
Let's initialize the provider now.
terraform init
2. Create a terraform resources
Resource Name | Provider Documentation |
citadel-key | aws_key_pair |
citadel | aws_instance |
eip | aws_eip |
Go to the Terraform Registry. The AWS provider is on the front page.
The core documentation for the file function.
The core documentation for local-exec provisioner
main.tf
#A terraform key-pair citadel-key with key_name citadel
resource "aws_key_pair" "citadel-key" {
key_name = "citadel"
public_key = file("/root/terraform-challenges/project-citadel/.ssh/ec2-connect-key.pub")
}
#This step covers both the citadel and Nginx-script tasks.
resource "aws_instance" "citadel" {
ami = var.ami
instance_type = var.instance_type
key_name = aws_key_pair.citadel-key.key_name
user_data = file("/root/terraform-challenges/project-citadel/install-nginx.sh")
}
#A local-exec provisioner for the eip resource
resource "aws_eip" "eip" {
vpc = true
instance = aws_instance.citadel.id
provisioner "local-exec" {
command = "echo ${self.public_dns} >> /root/citadel_public_dns.txt"
}
}
3. Deploy
terraform plan
terraform apply
Thank you so much for taking your valuable time to read
I took the initiative to learn in public and share my work with others. I tried my level best in squeezing as much information as possible in the easiest manner.
Hope you learned something new today :)
Signup to KodeKloud for performing this challenge.