Skip to content

how to create a Terraform module

Mohammad Javad Kazemi edited this page Sep 21, 2023 · 1 revision

Creating a Terraform Module for building block

This guide will walk you through the process of creating a Terraform module that you can use as a building block within meshStack. For additional information on how to create a building block in meshStack using a Terraform module, please consult this guide.

File Structure

To ensure simplicity and ease of understanding, it is recommended that you organize your project files as follows:

  1. Main Code: Store your primary Terraform configuration code in a dedicated file.
  2. Variables: Maintain variable definitions in a separate file.
  3. Outputs: Manage output configurations in their own file.
  4. Terraform and Provider Configuration: Keep your Terraform configuration settings in a distinct file.
  5. Backend Configuration: As the backend configuration contains environment-specific information, it's best to provide this as an input parameter.

Here's an example file structure:

image

For configuring the backend, please refer to this guide. It is essential to customize the backend settings according to your environment-specific requirements.

Example: Azure storage account

We are going to create this module based on the example given in Terraform registry

main.tf

resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "West Europe"
}

resource "azurerm_storage_account" "example" {
  name                     = "storageaccountname"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = var.storage_account_location
  account_tier             = "Standard"
  account_replication_type = var.replication_type

  tags = {
    environment = "staging"
  }
}

provider.tf



terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.73.0"
    }
  }
}

provider "azurerm" {
  # Configuration options
}

variables.tf

variable "storage_account_location" {
  type        = string
  description = "The region where storage account will be deployed"
  default     = "westeurope"
}

variable "replication_type" {
  type        = string
  description = "Possible values like LRS, ZRS, GRS"
  default     = "GRS"
}

outputs.tf

output "account_kind" {
  value = azurerm_storage_account.example.account_kind
}

backend.tf Please refer to this guide