Terraform Code For Creating Resource Group and vnet in Azure using Modules
Terraform is an open-source infrastructure as code software tool created by HashiCorp. Users define and provide data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language, or optionally JSON.
Below codes is for Creating Resource Group and vnet in Azure using Modules and it is tested in Azure Platform:
Privider.tf
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~>2.0"
}
}
}
provider "azurerm" {
features {}
subscription_id = var.subscription_id
client_id = var.client_id
client_secret = var.client_secret
tenant_id = var.tenant_id
}
Variable.tf
variable "subscription_id" {
description = "Enter Subscription ID for provisioning resources in Azure"
}
variable "client_id" {
description = "Enter Client ID for Application in Azure AD"
}
variable "client_secret" {
description = "Enter Client Secret for Application in Azure AD"
}
variable "tenant_id" {
description = "Enter Tenant ID / Dirctory ID of your Azure AD. Run Get-AzureSubscription"
}
main.tf
module "Module" {
source = "./Module"
resource_group = "Build-RG"
location = "centralindia"
vnet = "Build-vnet"
}
Module
main.tf
resource "azurerm_resource_group" "example" {
name = var.resource_group
location = var.location
}
resource "azurerm_virtual_network" "example" {
name = var.vnet
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
address_space = [var.address_space]
}
resource "azurerm_subnet" "subnet" {
name = var.subnet_name[count.index]
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["${var.subnet_prefix[count.index]}"]
count = length(var.subnet_name)
}
variable.tf
variable "resource_group" {
default = "Dabang-RG"
}
variable "location" {
default = "westus"
}
variable "vnet" {
default = "Dabang-vnet"
}
variable "address_space" {
default = "10.0.0.0/16"
}
variable "subnet_name" {
default = ["Subnet-1", "Subnet-2", "Subnet-3"]
}
variable "subnet_prefix" {
default = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
}
command.sh
# make sure terraform CLI is installed
terraform
# format the tf files
terraform fmt
# initialize terraform Azure modules
terraform init
# validate the template
terraform validate
# plan and save the infra changes into tfplan file
terraform plan -out tfplan
terraform plan -out tfplan --var-file="/Config/config.perf.tfvars"
# show the tfplan file
terraform show -json tfplan
terraform show -json tfplan >> tfplan.json
# Format tfplan.json file
terraform show -json tfplan | jq '.' > tfplan.json
# apply the infra changes
terraform apply tfplan
# delete the infra
terraform destroy
# cleanup files
rm terraform.tfstate
rm terraform.tfstate.backup
rm tfplan
rm tfplan.json
rm -r .terraform/
Key Terms:
- azure ,
- Open Source Software ,
- Terraform