Variable example:
provider "aws" {
region = "eu-central-1"
access_key = "AKIAYLT72WWP3MQN3Y6D"
secret_key = "SlG5zvS9tujqan1sN2a2ospIC86b09WstQBSMkAZ"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = var.instance_type
tags = {
Name = "Terraform EC2"
}
}
variable "instance_type" {
description = "Instance type t2.micro"
type = string
default = "t2.micro"
}
terraform init
Leave a Comment / Terraform / By admin
![](https://sheikhkamranmuneer.cloud/wp-content/uploads/2023/06/terraform-variable-types.png)
number variable type
provider "aws" {
region = "us-east-1"
access_key = "AKIAYLT72WWP3MQN3Y6D"
secret_key = "SlG5zvS9tujqan1sN2a2ospIC86b09WstQBSMkAZ"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
count = var.instance_count
tags = {
Name = "Terraform EC2"
}
}
variable "instance_count" {
description = "EC2 instance count"
type = number
default = 2
}
boolean variable type
provider "aws" {
region = "us-east-1"
access_key = "AKIAYLT72WWP3MQN3Y6D"
secret_key = "SlG5zvS9tujqan1sN2a2ospIC86b09WstQBSMkAZ"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
count = 1
associate_public_ip_address = var.enable_public_ip
tags = {
Name = "Terraform EC2"
}
}
variable "enable_public_ip" {
description = "Enable public IP address"
type = bool
default = true
}
List variable type:
provider "aws" {
region = "us-east-1"
access_key = "AKIAYLT72WWP3MQN3Y6D"
secret_key = "SlG5zvS9tujqan1sN2a2ospIC86b09WstQBSMkAZ"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
count = 1
tags = {
Name = "Terraform EC2"
}
}
resource "aws_iam_user" "IAM" {
count = length(var.user_names)
name = var.user_names[count.index]
}
variable "user_names" {
description = "IAM usernames"
type = list(string)
default = ["user1", "user2", "user3"]
}
Map variable type:
provider "aws" {
region = "us-east-1"
access_key = "AKIAYLT72WWP3MQN3Y6D"
secret_key = "SlG5zvS9tujqan1sN2a2ospIC86b09WstQBSMkAZ"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
tags = var.project_environment
}
variable "project_environment" {
description = "project name and environment"
type = map(string)
default = {
project = "project-alpha",
environment = "dev"
}
}
![](https://sheikhkamranmuneer.cloud/wp-content/uploads/2023/06/terraform-variables-twitter-1024x368.png)
Example of variable.tf
# variable.tf
# No default value
variable "instance_type" {
type = string
description = "EC2 Instance Type"
}
# No default value
variable "tag" {
type = string
description = "The tag for the EC2 instance"
}
# default value for the variable location
variable "location" {
type = string
description = "The project region"
default = "us-east-1"
}
provider "aws" {
region = var.location
access_key = "<INSERT_YOU_ACCESS_KEY>"
secret_key = "<INSERT_YOU_SECRET_KEY>"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = var.instance_type
tags = {
Name = var.tag
}
}
use command.
In Terraform, variables have different types that define the kind of values they can hold. Here are the commonly used variable types in Terraform:
String: The string type represents a sequence of characters, such as text. String variables are enclosed in double quotes (“).
Number: The number type represents numerical values, including both integers and floating-point numbers. Number variables can hold numeric values for calculations or specifying quantities.
Bool: The bool type represents Boolean values, which can be either true or false. Bool variables are commonly used for conditional expressions or enabling/disabling certain features.
List: The list type represents an ordered collection of elements. List variables can hold multiple values of the same type, enclosed in square brackets ([]). Elements in a list are accessed using zero-based indices.
Map: The map type represents a set of key-value pairs. Map variables can hold a collection of key-value pairs, where the keys and values can have different types. Map variables are enclosed in curly braces ({}) and each key-value pair is separated by commas.
The next variable type we are going to take is number
.
For example, we are going to increase the instance_count
of the ec2_instances
.
Let’s create the variable first –
Terraform variable.tf is a file where you can define variables for your Terraform configuration. This file can contain the variable definitions as well as the optional default value for the variable.
Let’s create variable.tf file for region, instance type, and tags
# variable.tf
Create main.tf for provisioning EC2 instance
How to create terraform.tfvars?
Here is the content of terraform-dev.tfvars, terraform-qa.tfvars, terraform-prod.tfvars
based on different environment types.
There can be a situation where you need to create multiple tfvars files based on the environment like DEV, QA, PRODUCTION
.
So in such scenario, you can create one tfvars
file for each environment –
- terraform-dev.tfvars
- terraform-qa.tfvars
- terraform-prod.tfvars
#main.tf
provider "aws" {
region = var.location
access_key = "<INSERT_YOU_ACCESS_KEY>"
secret_key = "<INSERT_YOU_SECRET_KEY>"
}
resource "aws_instance" "ec2_example" {
ami = "ami-053b0d53c279acc90"
instance_type = var.instance_type
tags = {
Name = var.tag
}
}
#variable.tf
variable "instance_type" {
}
variable "tag" {
}
variable "location" {
}
#terraform.tfvars
# terraform-dev.tfvars instance_type = "t2.micro" tag = "EC2 Instnace for DEV" location = "us-east-1"
# terraform-qa.tfvars instance_type = "t2.micro" tag = "EC2 Instnace for QA" location = "us-east-1"
# terraform-prod.tfvars instance_type = "t2.micro" tag = "EC2 Instnace for PROD" location = "us-east-1"
Run the terraform init, terraform plan and terraform apply
command in DEV, QA, and PROD environment.
terraform init --var-file="terraform-dev.tfvars" terraform plan --var-file="terraform-dev.tfvars" terraform apply --var-file="terraform-dev.tfvars"
terraform init --var-file="terraform-qa.tfvars" terraform plan --var-file="terraform-qa.tfvars" terraform apply --var-file="terraform-qa.tfvars"
terraform init --var-file="terraform-prod.tfvars"
terraform plan --var-file="terraform-prod.tfvars"
terraform apply --var-file="terraform-prod.tfvars"
END OF NOTES –
![](https://sheikhkamranmuneer.cloud/wp-content/uploads/2023/06/6149d8beabf1a76c4878ad1f_570x330-1024x593.png)
Terraform locals are a feature of the Terraform infrastructure as code (IaC) tool that allows you to define and use variables within your Terraform configurations. Locals provide a way to define intermediate values or expressions that can be used within the same configuration file without exposing them as input variables or outputs.
CODE EXAMPLE:
provider "aws" {
region = "us-east-1"
access_key = "<YOUR_AWS_ACCESS_KEY>"
secret_key = "<YOUR_AWS_SECRET_KEY>"
}
locals {
staging_env = "staging"
}
resource "aws_vpc" "staging-vpc" {
cidr_block = "10.5.0.0/16"
tags = {
Name = "${local.staging_env}-vpc-tag"
}
}
resource "aws_subnet" "staging-subnet" {
vpc_id = aws_vpc.staging-vpc.id
cidr_block = "10.5.0.0/16"
tags = {
Name = "${local.staging_env}-subnet-tag"
}
}
resource "aws_instance" "ec2_example" {
ami = "ami-0767046d1677be5a0"
instance_type = "t2.micro"
subnet_id = aws_subnet.staging-subnet.id
tags = {
Name = "${local.staging_env} - Terraform EC2"
}
}
Apply the code and observe the results in AWS.
END OF NOTES.
![](https://sheikhkamranmuneer.cloud/wp-content/uploads/2023/06/ec2-.jpg)
Generating SSH key-pairs(public key, private key) using ssh keygen.
Let us generate the key pair using the following command
ssh-keygen -t rsa -b 2048
#main.tf
provider "aws" {
region = "us-east-1"
access_key = "AKIAYLT72WWP3MQN3Y6D"
secret_key = "SlG5zvS9tujqan1sN2a2ospIC86b09WstQBSMkAZ"
}
resource "aws_instance" "ec2_example_001" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
key_name= "aws_key"
vpc_security_group_ids = [aws_security_group.main1.id]
}
resource "aws_security_group" "main1" {
egress = [
{
cidr_blocks = [ "0.0.0.0/0", ]
description = ""
from_port = 0
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "-1"
security_groups = []
self = false
to_port = 0
}
]
ingress = [
{
cidr_blocks = [ "0.0.0.0/0", ]
description = ""
from_port = 22
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "tcp"
security_groups = []
self = false
to_port = 22
}
]
}
resource "aws_key_pair" "deployer" {
key_name = "aws_key"
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCc+aEOpxgQwZj/EJHTR3czbhwKaedZelWYBatu5+jgsFVf+vFTKgWG/aFd/8xbTNjgbqaWxkNb4qLOmA56P7/lY8oYD/WWmMh3kUYjk3rL8firehMofgJTduWSmFu+PZkNf5thnjM3mRZ+C6Cs9QSQ8f0OBfH3Ax75Da46w9Bi34D0tqC0VRxSEtiseRwlzpqNLyP6AuxzvmMbhzHEcXyKEbv+9oEwBjqiSM+SgaihxOc3uToKxYsxagcV8qlpQfKloW2pfEpcr5OECN/R41BkLBKJH4u/KLkFjLA1QNqwEDKrGJFsNTIOUUwTjBGi8GbvzFTR/Q3lA2UqFz9orFFv root@k8s"
}
terraform apply
Apply configuration:
Give permission to the aws_key.
Now connect using SSH to the AWS EC2 Instance.
In Terraform, variables are used to parameterize and customize your infrastructure configuration. They allow you to define values that can be reused across your Terraform codebase and provide flexibility when deploying infrastructure resources. Here are some key definitions related to Terraform variables:
Variable: A variable is a named entity that represents a value in your Terraform configuration. It can be thought of as a placeholder for a value that will be supplied during runtime.
Variable Block: In Terraform, variables are defined within a variable block. The variable block is used to declare the variable’s name, type, description, and default value (if any).
Type: Variables in Terraform have a type associated with them, such as string, number, bool, list, map, etc. The type determines the kind of value that can be assigned to the variable.
Default Value: Variables can have default values specified within the variable block. If a value is not explicitly provided when running Terraform commands, the default value will be used.
Input Variables: Input variables are defined in the Terraform configuration to allow users to provide values when running Terraform commands. These values can be provided via command-line flags, environment variables, or by using a .tfvars file.
Output Variables: Output variables allow you to define values that are exposed after Terraform applies the configuration. These outputs can be used by other Terraform configurations or accessed through the Terraform CLI.
Variable Interpolation: Variable interpolation allows you to reference variables within other parts of your Terraform configuration. It is done using the var.<variable_name> syntax.
By utilizing variables, you can create more reusable and dynamic Terraform configurations that can be easily customized based on different environments or deployment scenarios. Variables provide a way to parameterize your infrastructure code and make it more flexible and adaptable to changing requirements.
No comments:
Post a Comment