A typical Folder contains a main.tf, outputs.tf, providers.tf, and variables.tf, where
Example: main terraform layout
terraform-test
├── main.tf
├── outputs.tf
├── providers.tf
└── variables.tf
Local values are named values that are assigned and can be used throughout your code. Local values can be constant or referenced values. Local values are assigned by created a set of locals block as shown below:
locals {
# Assign the value of 'dev' to environment
instance_name = "dev-instance"
# Obtain the instance ID of the 'app_server' EC2 instance
instance_id = aws_instance.app_server.id
}
To use local variables, the format is local.<variable_name>
.
Here is an example of using a local variable to name the EC2 instance resource.
resource "aws_instance" "this_server" {
# ...
tags = {
# Using local variable
Name = local.instance_name,
"Environment" = "dev"
}
}
Input variables are used to provide parameters for you to customize your Terraform module without altering the module’s source code and prevent hard-coding values and enabled you to re-use code An example of input variables:
variable "app_name" {
type = string
description = "Name of the application"
default = ""
}
To use input variables, the format is var.<variable_name>
. Here is an example of using the input variable to name the EC2 instance resource:
resource "aws_instance" "app_server" {
# ...
tags = {
# Using input variable
Name = var.app_name,
"Environment" = "prod"
}
}
You can also assign variables using the command line:
terraform apply -var="app_name=wordpress-app"
Output variables allows you to expose information on the resources so that others Terraform configurations can use it.
An example of output variables:
output "instance_tags" {
value = aws_instance.this_server.tags
description = "A mapping of EC2 instance tags"
}
Providers provide interactions with cloud providers, Software as a Service (SaaS) providers and other Application Programming Interface (API). Each provider provides a set of resources and data sources that Terraform can manage. Example of an AWS provider:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.47.0"
}
}
}
provider "aws" {
# Configuration options
}
Resources are the core element in Terraform. Declaring a resource can define one or more infrastructure resource objects such as compute, networking, etc
Example of a AWS Simple Storage Service (S3) bucket resource:
resource "aws_s3_bucket" "example" {
bucket = "workshop2-bucket"
}
Data Sources allow lookup of resources defined outside of Terraform and provide the attributes found within that resource
Example of a data source lookup of an existing AWS Virtual Private Cloud (VPC):
data "aws_vpc" "selected" {
id = "vpc-00f0b02721857a89d"
}