21
loading...
This website collects cookies to deliver better user experience
main.tf
file is good for beginners. However, this approach will lead to maintainability issues as our underlying infrastructure grows. Moreover, in practical situations, you might also need to deal with multiple environments (e.g. DTAP - dev/test/acceptance/production).provider.tf
- contains provider configuration in root modulemain.tf
- call modules, locals, and data sources to create all resourcesvariables.tf
- contains variable declarations used in main.tf
outputs.tf
- contains outputs from the resources created in main.tf
terraform.tfvars
- contains variable definitions to provide default variable values. Terraform will automatically load variables from those files.provider.tf
main.tf
variables.tf
. The following block must be defined for every variable.variable "aws_region" {
type = string
description = "AWS Region"
# default value is optional.
default = "us-east-1"
}
terraform apply -var aws_region="eu-west-1"
TF_VAR_
followed by the name of a declared variable. This can be useful when running Terraform in automation.export TF_VAR_aws_region = eu-west-1
.tfvars
or .tfvars.json
)terraform.tfvars
or terraform.tfvars.json
..auto.tfvars
or .auto.tfvars.json
.region = var.aws_region
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~>3.0"
}
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
"Environment" = "dev"
"Owner" = "g33kzone"
}
}
}
variable "aws_region" {
type = string
description = "AWS Region"
}
variable "instance_type" {
type = string
description = "AWS EC2 Instance Type"
}
variable "aws_ec2_ami" {
type = string
description = "EC2 AMI for Amazon Linux 2"
}
resource "aws_instance" "web" {
instance_type = var.instance_type
ami = var.aws_ec2_ami
tags = {
"Name" = "aws-ec2-demo"
}
}
aws_region = "us-east-1"
instance_type = "t2.micro"
aws_ec2_ami = "ami-04d29b6f966df1537"
# 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
21