Terraform Variable Example: Azure & AWS


Terraform Variable AWS Example


variable "instance_count" {
  type = number
  default = 1
}

variable "region" {
  type = string
  default = "us-east-1"
}

variable "instance_name" {
  type = string
  default = "devopsschool-instance"
}

variable "security_groups" {
  type = list(string)
  default = ["default", "launch-wizard-1", "launch-wizard-2"]
}

variable "amis" {
  type = map
  default = {
    "us-east-1" = "ami-007855ac798b5175e"
    "us-west-2" = "ami-4b32be2b"
  }
}

variable "create_vm" {
  description = "If set to true, it will create vm"
   type   = bool
}

resource "aws_instance" "example" {
  count = var.instance_count
  ami           = var.amis[var.region]
  instance_type = "t2.micro"
  vpc_security_group_ids = var.security_groups
  tags = {
    Name = var.instance_name
  }
}

resource "aws_instance" "example1" {
  count = var.create_vm ? 1 : 0
  ami           = var.amis[var.region]
  instance_type = "t2.micro"
}

Terraform Variable Azure Example



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

variable "grpname" {
  type = string
  description = "This is for demo of string variable"
  default = "devopsschool-grp"
}

variable "users" {
    type    = list
    default = ["devops-school-1", "devops-school-2", "devops-school-3"]
    description = "This is for demo of list variable"
}

variable "grps" {
  type = map
  default 	= {
    one = "hello1"
    two = "hello2"
  }
}
resource "azurerm_resource_group" "mapdemo1" {
  name     = var.grps["one"]
  location = "South India"
}

output "resource_group" { 
	value = azurerm_resource_group.mapdemo1.grps["one"]
 }

resource "azurerm_resource_group" "mapdemo2" {
  name     = var.grps["two"]
  location = "South India"
}

resource "azurerm_resource_group" "listdemo" {
  name     = var.users[0]
  location = "South India"
}

resource "azurerm_resource_group" "listdemo1" {
  name     = var.users[1]
  location = "South India"
}

resource "azurerm_resource_group" "listdemo2" {
  name     = var.users[2]
  location = "South India"
}

resource "azurerm_resource_group" "example1" {
  name     = var.grpname
  location = "South India"
}

resource "azurerm_resource_group" "example" {
  count = var.numofrg
  name     = "devopsschool-${count.index}"
  location = "South India"
}

output "resource_group4" { 
	value = azurerm_resource_group.example1.name
 }
 

Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x