37
loading...
This website collects cookies to deliver better user experience
WHAT
is Terraform, we need to address the WHY
. First, let us understand Infrastructure as Code (IaC) and its role in the current digital transformation context.An imperative
approach instead defines the specific commands required to achieve the desired configuration, and those commands then need to be executed in the correct order.
A declarative
approach defines the system's desired state, including what resources you need and any properties they should have, and an IaC tool will configure it for you.
Providers
and leverages existing infrastructure already used by these providers for their API servers. A provider is responsible for understanding API interactions & exposing resources. Currently, it supports 34 Official Providers and 160+ verified providers.tf-aws-ec2
mkdir tf-aws-ec2 && cd $_
main.tf
. For the purpose of this initial demo, we will hardcode all the configuration values. For production, hardcoding is not recommended. We will see in further tutorials to write terraform code as per best practices.touch main.tf
main.tf
terraform
block configures the required AWS provider along with the relevant version.terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~>3.0"
}
}
}
provider
block configures AWS region and default tags applicable to all resources created via Terraform code.provider "aws" {
region = "us-east-1"
default_tags {
tags = {
"Environment" = "dev"
"Owner" = "g33kzone"
}
}
}
resource
block is responsible to create EC2 instance with the given configuration. It create an EC2 instance with 't2.micro' Instance Type along with the AMI specified.resource "aws_instance" "web" {
instance_type = "t2.micro"
ami = "ami-04d29b6f966df1537"
tags = {
"Name" = "aws-ec2-demo"
}
}
main.tf
file should contain the following code.terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~>3.0"
}
}
}
provider "aws" {
region = "us-east-1"
default_tags {
tags = {
"Environment" = "dev"
"Owner" = "g33kzone"
}
}
}
resource "aws_instance" "web" {
instance_type = "t2.micro"
ami = "ami-04d29b6f966df1537"
tags = {
"Name" = "aws-ec2-demo"
}
}
init
, plan
, apply
, destroy
# open your shell in the same project folder
# download the terraform core components
# and initialize terraform in this directory
terraform init
# Validate changes to be made in AWS after the execution
terraform plan
# -auto-approve is used to skip manual approval prompt
terraform apply -auto-approve
# running this command will destroy all the resources
terraform destroy -auto-approve
getting-started
) - https://github.com/g33kzone/tf-aws-ec2 37