Terraform on AWS
1. Create AWS Instance Using Terraform
STEP 1: Create a Ubuntu Machine on AWS
sudo su
mkdir terraform
cd terraform
STEP 2: Create an IAM user and login
STEP 3: Login as IAM User and Create an ENV Variable
apt update
apt install awscli
aws configure
#paste accesskey
#paste secretkey
export AWS_ACCESS_KEY_ID=<access_key>
export AWS_SECRET_ACCESS_KEY=<secret_key>
STEP 4: Install Terraform
Install Terraform on Ubuntu Machine by the steps provided by Terraform official website https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update
sudo apt-get install terraform
STEP 5: Create main.tf
file on AWS.
vi main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.67.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_instance" "web_server" {
ami = "ami-08e5424edfe926b43"
instance_type = "t2.micro"
}
output "ec2_pubic_ips" {
value = aws_instance.web_server.public_ip
}
terraform init
terraform validate
terraform plan
terraform apply
After apply command, new Instance will be created on aws
STEP 6: Configure the instance Resource by changing the code to create Multiple Instance.
vi main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.67.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_instance" "web_server" {
count = 2
ami = "ami-08e5424edfe926b43"
instance_type = "t2.micro"
}
output "ec2_pubic_ips" {
value = aws_instance.web_server[*].public_ip
}
terraform plan
terraform apply
terraform destroy
#to delete the created instance
2. Lifecycle Management
mkdir lifecycle
cd lifecycle
vi main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.67.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_instance" "terraform" {
instance_type = "t2.micro"
ami = "ami-08e5424edfe926b43"
tags = {
Name = "Raj"
}
lifecycle {
create_before_destroy = true
prevent_destroy = false
ignore_changes = [
instance_type,
key_name,
tags
]
}
}
terraform init
terraform validate
terraform plan
terraform apply
Thank you shubhamlondhe , for the wonderful session
#devops #terraweek #terraform #hcl #aws
I’m actively searching for new opportunities and eager to broaden my professional network.
Linkedin : https://www.linkedin.com/in/raj-kumar-devops/
Website : https://bento.me/rajdevops
For more Projects : https://medium.com/@rajdevops