Terraform Series - Creating an EC2 Instance

 


Before creating a TF File. Lets understand the blocks of the TF file.

There are 3 basic blocks:

1) TF setting block.

2) Provider block.

3) Resource block.

TF setting block:

Each terraform block can contain a number of settings related to Terraform's behavior. 

# Terraform Settings Block
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

Here I am mentioning the required providers as AWS and it downloads the latest version of AWS providers.

The required_providers block specifies all of the providers required by the current module, mapping each local provider name to a source address and a version constraint. If the version not mentioned it download the latest version.

Providers (Plugins):

Terraform relies on plugins called providers to interact with cloud providers, SaaS providers, and other APIs.

Terraform configurations must declare which providers they require so that Terraform can install and use them. Here I am using the provider as "aws".

# Provider Block
provider "aws" {
  profile = "default" # AWS Credentials configured via AWS CLI.
  region  = "us-east-1"
}

Resource Block:

Block where we write actual code.

# Resource Block
resource "aws_instance" "ec2demo" {
  ami           = "ami-0b5eea76982371e91" # Amazon Linux in us-east-1
  instance_type = "t2.micro"
  tags = {
    "Name" = "myfirstvm"
  }
}

aws_instance is the resource for creating EC2.

e2demo is the label for the resource block.

ami - AWS EC2 Machine image to create a VM.

instance_type - VM Spec.

I am using tag which is a key value pair to create VM by the name called "myfistvm". 

So, we are done with the first TF File.

> terraform init -> Pulls the required providers/plugin declared in the TF setting block.

> terraform validate -> Validates syntax of the TF file.

> terraform plan -> Runs and shows a plan of what will be performed.

> terraform apply -> Apply the changes.

> terraform destroy -> Delete the changes.

Running "terraform init" for the first time will take time as it has to download the plugins. 























Comments

Popular posts from this blog

SRE/DevOps Syllabus

AWS Code Commit - CI/CD Series Part 1

Docker - Preventing IP overlapping