Working With Terraform Variables

Write a terraform script using aws ec2 instance and github and apply following kind of variables

  • Types of Terraform variable – Number
  • Types of Terraform variable – String
  • Types of Terraform variable – List
  • Types of Terraform variable – Map
  • Types of Terraform variable – Boolean

and Decare variables in – Terraform file – Override through Command Line

1. Types of Terraform variable - Number
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-west-2"
  access_key = ""
  secret_key = ""
}


variable "usercount" {
  type = number
  description = "This is for demo of number variable"
  default = 3
}

resource "aws_instance" "avinash" {
  count = "${var.usercount}"
  ami = "ami-03d5c68bab01f3496"
  instance_type = "t2.micro"
  tags = {
    Name = "avinash.${count.index}"
  }
  
}
2. Types of Terraform variable - String 
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-west-2"
  access_key = ""
  secret_key = ""
}


variable "username" {
  type = string
  description = "This is for demo of string variable"
  default = "demouser"
}

resource "aws_instance" "avinash" {
  ami           = "ami-03d5c68bab01f3496"
  instance_type = "t2.micro"
  tags = {
    Name = "${var.username}"
  }  
}
3. Types of Terraform variable – List 
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-west-2"
    access_key = ""
  secret_key = ""
}


variable "users" {
    type    = list
    default = ["devopsschool11", "devopsschool2", "devopsschool3"]
    description = "This is for demo of list variable"
}

resource "aws_instance" "avinash" {
  ami           = "ami-03d5c68bab01f3496"
  instance_type = "t2.micro"
  tags = {
    Name = "${var.users[0]}"
  } 
 


}
4. Types of Terraform variable – Map
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  access_key = ""
  secret_key = ""
}

variable "region" {

  type = string
  default = "us-west-2"

}

variable "amis" {
  type = map
  default = {
    
    "us-west-2" = "ami-03d5c68bab01f3496"
  }
}


resource "aws_instance" "avinash" {
  ami           = "${var.amis[var.region]}"
  instance_type = "t2.micro"
  
  tags = {
    Name = "Avinash M"
  }
}
5.  Types of Terraform variable – Boolean