Dive Deep in Terraform

Dive Deep in Terraform

In the last article, I have discussed the basis of terraform and all the theory revolving around it. Today we are going to see some code and will learn how we can create resources in Azure using Terraform.

First we'll look into Modules and why they are used, then we'll create Azure Virtual Machine using terraform. Lets goooo.......


Terraform Module

Before diving into the Azure setup, let’s start by understanding what a Terraform module is.

A Terraform module is a container for multiple resources that are used together. A module can be thought of as a set of Terraform configuration files in a directory. Modules help in organizing, reusing, and maintaining your infrastructure code efficiently. By breaking down your infrastructure into reusable components, you can create a module for a specific resource (like a VM, storage account, or network) and then reuse that module across different environments or projects.

Connecting Terraform with Azure

To manage Azure resources using Terraform, you'll first need to authenticate Terraform with your Azure account. This is typically done using a Service Principal, which provides Terraform with the necessary permissions to manage resources in your Azure subscription.

Steps to Connect Terraform with Azure:

  • Install Terraform: Make sure Terraform is installed on your machine. You can download it from the official Terraform website.
  • Create an Azure Service Principal: Use the Azure CLI to create a Service Principal with Contributor access to your subscription.

az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/YOUR_SUBSCRIPTION_ID"
        

The output will provide you with the appId, displayName, password, and tenant. You’ll use these details in your Terraform configuration.

  • Set up Environment Variables: Terraform uses environment variables to authenticate with Azure. Set the following variables using the details from the Service Principal:

export ARM_CLIENT_ID="appId"
export ARM_CLIENT_SECRET="password"
export ARM_SUBSCRIPTION_ID="YOUR_SUBSCRIPTION_ID"
export ARM_TENANT_ID="tenant"        

File Structure

/terraform-project
│
├── /vm_module
│   ├── main.tf
│   ├── variables.tf
│   └── outputs.tf
│
├── main.tf
└── terraform.tfvars
        


Creating a VM Using Terraform Modules

Now that Terraform is connected to Azure, let’s create a VM using a Terraform module. First, we’ll define the module, and then we’ll use it in our configuration.

Step 1: Define the VM Module

Create a directory named vm_module and inside it, create the following files:

  • main.tf: Defines the Azure VM resource.

resource "azurerm_virtual_machine" "vm" {
  name                  = var.vm_name
  location              = var.location
  resource_group_name   = var.resource_group_name
  network_interface_ids = [azurerm_network_interface.nic.id]
  vm_size               = var.vm_size

  os_profile {
    computer_name  = var.vm_name
    admin_username = var.admin_username
    admin_password = var.admin_password
  }

  os_profile_windows_config {
    provision_vm_agent = true
  }

  storage_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2019-Datacenter"
    version   = "latest"
  }

  storage_os_disk {
    name              = "${var.vm_name}_osdisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Standard_LRS"
  }
}
        

  • variables.tf: Defines the variables for the module.

variable "vm_name" {
  type = string
}

variable "location" {
  type = string
}

variable "resource_group_name" {
  type = string
}

variable "vm_size" {
  type = string
  default = "Standard_DS2_v2"
}

variable "admin_username" {
  type = string
}

variable "admin_password" {
  type = string
}
        

  • outputs.tf: Optionally, define outputs if you want to expose certain information from the module.

output "vm_id" {
  value = azurerm_virtual_machine.vm.id
}
        

Step 2: Use the VM Module in Your Terraform Configuration

Back in your root directory, create a new main.tf file to call the module:

provider "azurerm" {
  features = {}
}

resource "azurerm_resource_group" "rg" {
  name     = "terraform-vm-rg"
  location = "East US"
}

module "vm_module" {
  source              = "./vm_module"
  vm_name             = "myTerraformVM"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  vm_size             = "Standard_DS1_v2"
  admin_username      = "azureuser"
  admin_password      = "P@ssw0rd1234"
}
        

Step 3: Run Terraform Commands

Now, you’re ready to deploy your VM using Terraform. Here are the key commands you'll use:


  • terraform init: This command initializes the working directory containing the Terraform configuration files. It downloads the necessary provider plugins (in this case, the Azure provider).
  • terraform plan: This command creates an execution plan, showing you what Terraform will do when you apply the configuration. It’s a safe way to verify what will be created, modified, or destroyed.
  • terraform apply: This command applies the changes required to reach the desired state of the configuration. It will prompt you to confirm before proceeding with the changes.
  • terraform destroy: If you ever need to tear down the resources, this command will delete everything that Terraform created.

Conclusion

By using Terraform modules, you can break down complex infrastructure into manageable, reusable components. Connecting Terraform with Azure is straightforward and allows you to automate the provisioning of cloud resources efficiently. Whether you're deploying a single VM or an entire application stack, Terraform's modular approach ensures that your infrastructure is scalable, consistent, and maintainable.


要查看或添加评论,请登录

Shivam Pant的更多文章

社区洞察

其他会员也浏览了