Introduction
In this project, an organized structure for the deployment of an infrastructure in Azure using Terraform and Terragrunt is presented. The solution makes it easy to create and manage Azure Key Vault resources, optimizing the reuse of configurations between different environments, such as development and production, through well-structured configuration files.
The project structure allows for a modular and reusable implementation, separating the configuration of specific environments from the main deployment files. Terraform and Terragrunt offer a robust approach to managing common and environment-specific variables and state, facilitating infrastructure management and scalability in enterprise environments.
Project Structure
The organization of the project is as follows:
├── env
│ ├── code
│ │ └── keyvault
│ │ └── 00
│ │ ├── backend.tf
│ │ ├── data.tf
│ │ ├── endpoint.tf
│ │ ├── locals.tf
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ ├── provider.tf
│ │ └── variables.tf
│ └── dev
│ ├── keyvault
│ │ └── 00
│ │ ├── terragrunt.hcl
│ │ └── vars.tfvars
│ └── varEnvironment.hcl
├── varCommon.hcl
└── varDataState.hcl
The folder env contains environment-specific settings, while code hosts the Terraform configuration files for Key Vault deployment. The folder dev contains configuration files specific to the development environment. terragrunt.hcl, varCommon.hcl and varDataState.hcl They are configuration files for Terragrunt and common variables.
Terraform Configuration
Now, let's dive into the Terraform configuration files needed to deploy Key Vault.
backend.tf
terraform {
backend "azurerm" {
}
required_version = "~>0.14"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "3.47.0"
}
}
}
data.tf
The file data.tf contains data blocks that allow Terraform to access information from existing resources in Azure. These blocks are essential for reusing existing infrastructure and ensuring that new resources are deployed consistently.
data "terraform_remote_state" "rg" {
#count = var.terraform_remote_state_route53 ? 1 : 0
backend = "azurerm"
config = {
subscription_id = var.lz_subscription_id
resource_group_name = var.lz_resource_group_name
storage_account_name = var.lz_storage_account_name
container_name = var.lz_container_name
key = "${var.ProjectName}/${var.ServiceName}/env/${var.Environment}/${var.mapProjectPathKey.rg}/terraform.tfstate"
}
}
data "azurerm_subnet" "sbn_data" {
name = var.sbn_data_net_name
virtual_network_name = var.vnet_net_name
resource_group_name = var.rg_net_name
}
data "azurerm_private_dns_zone" "zone_01" {
provider = azurerm.hub
name = var.private_dns_zone_name_keyvault
resource_group_name = var.hub_resource_group_name
}
endpoint.tf
resource "azurerm_private_endpoint" "pren_01" {
name = upper(join("-", [ var.Environment, var.BussinessUnit, var.Provider, var.ServiceName, "kv-pren-01"])) #local.private_endpoint_name_01
resource_group_name = data.terraform_remote_state.rg.outputs.name
location = var.region
subnet_id = data.azurerm_subnet.sbn_data.id
private_service_connection {
name = upper(join("-", [ var.Environment, var.BussinessUnit, var.Provider, var.ServiceName, "kv-pren-01"]))
private_connection_resource_id = azurerm_key_vault.keyvault.id
is_manual_connection = false
subresource_names = ["vault"]
}
private_dns_zone_group {
name = data.azurerm_private_dns_zone.zone_01.name
private_dns_zone_ids = [data.azurerm_private_dns_zone.zone_01.id]
}
tags = local.tags
lifecycle {
ignore_changes = [
tags["CreationDate"]
]
}
}
Explanation:
data "terraform_remote_state" "rg":- Allows access to the remote Terraform state in which the Resource Group definition is located (
rg). backend: Specifies the Azure backend (azurerm) where the state is stored.config: Defines the parameters necessary to access the remote state:subscription_id,resource_group_name,storage_account_name,container_name: Connection data to the storage account where the state is saved.key: Full path on storage for the fileterraform.tfstate.
- Allows access to the remote Terraform state in which the Resource Group definition is located (
data "azurerm_subnet" "sbn_data":- Provides information about a specific subnet, necessary to connect a
Private Endpoint. name: Name of the destination subnet.virtual_network_name: Name of the virtual network to which the subnet belongs.resource_group_name: Name of the resource group where the virtual network is located.
- Provides information about a specific subnet, necessary to connect a
data "azurerm_private_dns_zone" "zone_01":- Gets details of a private DNS zone that will allow name resolution for the
Private Endpoint. provider: Specifies the Azure provider, in this case, the region or hub.name: Name of the private DNS zone associated with the Key Vault.resource_group_name: Resource group where this private DNS zone is located.
- Gets details of a private DNS zone that will allow name resolution for the
endpoint.tf
This file defines the resource Private Endpoint, allowing private connection to the Key Vault. This Private Endpoint is associated with the specified subnet and private DNS zone.
Code:
resource "azurerm_private_endpoint" "pren_01" {
name = upper(join("-", [ var.Environment, var.BussinessUnit, var.Provider, var.ServiceName, "kv-pren-01"]))
resource_group_name = data.terraform_remote_state.rg.outputs.name
location = var.region
subnet_id = data.azurerm_subnet.sbn_data.id
private_service_connection {
name = upper(join("-", [ var.Environment, var.BussinessUnit, var.Provider, var.ServiceName, "kv-pren-01"]))
private_connection_resource_id = azurerm_key_vault.keyvault.id
is_manual_connection = false
subresource_names = ["vault"]
}
private_dns_zone_group {
name = data.azurerm_private_dns_zone.zone_01.name
private_dns_zone_ids = [data.azurerm_private_dns_zone.zone_01.id]
}
tags = local.tags
lifecycle {
ignore_changes = [
tags["CreationDate"]
]
}
}
Explanation:
resource "azurerm_private_endpoint" "pren_01":- This resource defines a
Private Endpointwhich allows a secure and private connection to the Key Vault in Azure. name: Name ofPrivate Endpoint, dynamically generated using several variables (Environment,BussinessUnit,Provider,ServiceName), depending on the environment and business unit.resource_group_name: Resource group where thePrivate Endpoint, using the value obtained interraform_remote_state.location: Specifies the region for the endpoint.subnet_id: ID of the subnet where thePrivate Endpoint, using the value ofazurerm_subnet.sbn_data.id.
- This resource defines a
- Block
private_service_connection:- Configure the private connection to the Key Vault.
name: Name of the private connection, in the same format as the name of thePrivate Endpoint.private_connection_resource_id: ID of the Key Vault to which the endpoint connects.is_manual_connection: Established infalse, indicating that the connection is not manual.subresource_names: Defines the specific subresource of the Key Vault (in this case,vault).
- Block
private_dns_zone_group:- Defines the association of the private DNS zone to the
Private Endpoint. name: DNS zone name, obtained fromazurerm_private_dns_zone.zone_01.private_dns_zone_ids: List of IDs of the associated private DNS zones, using the ID obtained inazurerm_private_dns_zone.zone_01.
- Defines the association of the private DNS zone to the
tags:- Applies tags defined in
local.tagsfor the organization of the resource.
- Applies tags defined in
- Block
lifecycle:- Sets to ignore any changes to the label
CreationDate, preventing Terraform from trying to modify the resource if only that tag changes.
- Sets to ignore any changes to the label
locals.tf
The file locals.tf defines local variables that can be reused in multiple parts of Terraform code. Local variables are useful for centralizing values that are used across multiple resources, improving code clarity and maintainability.
locals {
tags = var.tags
}
Explanation:
locals: This block creates a local variable calledtags, which stores the value ofvar.tags.
tags: When assigningvar.tagstolocal.tags, access to labels in different resources is facilitated without having to referencevar.tagsdirectly every time. This is especially useful ifvar.tagsis used on multiple files or resources as it allows tags to be changed in one place if needed in the future.
main.tf
in the file main.tf The main infrastructure resources are defined. In this case, an Azure Key Vault resource is being created that will serve to store secrets and other sensitive values, thus ensuring the security of the information.
resource "azurerm_key_vault" "keyvault" {
name = upper(join("-", [ var.Environment, var.BussinessUnit, var.Provider, var.ServiceName, "kv-01"]))
location = var.region
tenant_id = var.Tenant
resource_group_name = data.terraform_remote_state.rg.outputs.name
enabled_for_disk_encryption = var.kv_enabled_for_disk_encryption
soft_delete_retention_days = var.kv_soft_delete_retention_days
purge_protection_enabled = var.kv_purgue_protection_enabled
public_network_access_enabled = false
sku_name = var.kv_sku_name
lifecycle {
ignore_changes = [
tags["CreationDate"]
]
}
}
Explanation:
-
resource "azurerm_key_vault" "keyvault": This block defines a resource of typeazurerm_key_vault(Azure Key Vault) in Terraform.keyvaultis the identifier of the resource in Terraform, used to reference it in other parts of the code. -
name: Use a functionupper(join("-", [...]))to construct the name of the Key Vault, combining variables (var.Environment,var.BussinessUnit,var.Provider,var.ServiceName) to generate a unique and standardized name, ensuring consistency and easy identification of the resource. -
location: Defines the geographic location of the resource, specified byvar.region. -
tenant_id: Azure tenant ID, defined invar.Tenant, required to link the Key Vault to the appropriate Azure AD directory. -
resource_group_name: Name of the resource group in which the Key Vault will be located, in this case obtained fromdata.terraform_remote_state.rg.outputs.name, which references the remote Terraform state where the configuration of this resource is stored. -
enabled_for_disk_encryption: Determines whether the Key Vault can be used to encrypt VM disks in Azure. Its value comes fromvar.kv_enabled_for_disk_encryption. -
soft_delete_retention_days: Number of days that deleted items in the Key Vault will be retained before final deletion, defined invar.kv_soft_delete_retention_days. -
purge_protection_enabled: If enabled, prevents accidental permanent deletion of the Key Vault. Its value is assigned byvar.kv_purgue_protection_enabled. -
public_network_access_enabled: Established infalseto disable access from public networks, increasing the security of the resource by restricting access to private networks. -
sku_name: Defines the service level or SKU of the Key Vault, specified invar.kv_sku_name, which can bestandardeitherpremium. -
lifecycle: Defines lifecycle settings for the resource in Terraform. Here it is usedignore_changesto prevent Terraform from applying tag changesCreationDate, allowing said value to remain unchanged even if the value oftags["CreationDate"].
provider.tf
in the file provider.tf infrastructure providers are configured, in this case the Azure provider (azurerm). Here you define two configurations for the Azure provider, one by default and one with an alias. This allows working with multiple Azure subscriptions within the same Terraform project
provider "azurerm" {
subscription_id = var.Subscription
tenant_id = var.Tenant
features {}
}
provider "azurerm" {
alias = "hub"
subscription_id = var.subscription_hub_id
tenant_id = var.Tenant
features {}
}
Explanation:
-
First block
provider "azurerm":subscription_id: This property defines the Azure subscription ID which will be used to provision and manage resources. It is obtained from the variablevar.Subscription, which must be previously configured.tenant_id: He Azure Active Directory tenant ID to which the Azure provider should be associated. In this case, it is taken fromvar.Tenant.features {}: A block required by the Azure provider (azurerm) which may contain additional settings. Although in this case it is empty, it is necessary to correctly initialize the provider.
-
Second block
provider "azurerm"with aliashub:alias: The alias"hub"allows you to create a second Azure provider within the same Terraform configuration, which is useful when you need to work with multiple subscriptions. By assigning an alias, you can reference this specific provider later in your resources or data so that it can be differentiated from the default provider.subscription_id: Similar to the first block, this property is defined viavar.subscription_hub_id, which represents the Azure subscription ID for the hub configuration.tenant_id: He tenant ID remains the same and is taken fromvar.Tenantto maintain consistency in the environment.features {}: Like the first block, this block is required even if it does not contain additional settings.
variables.tf
in the file variables.tf All variables used throughout the Terraform infrastructure are defined. This file centralizes configurable parameters that can change depending on the environment, subscription, resource name, etc. This allows code reuse and makes it easier to manage.
######################
# VARIABLES COMUNES #
######################
variable "lz_subscription_id" {
type = string
description = "ID de la susbcriptcion de los tfstate"
default = ""
}
variable "lz_resource_group_name" {
type = string
description = "Nombre del resoruce group de los tfstate"
default = ""
}
variable "lz_storage_account_name" {
type = string
description = "Nombre del storage account de los tfstate"
default = ""
}
variable "lz_container_name" {
type = string
description = "Nombre del container name de los tfstate"
default = ""
}
variable "Tenant" {
type = string
description = "Nombre del tenant"
default = ""
}
variable "Subscription" {
type = string
description = "Nombre de la subscripcion"
default = ""
}
variable "Provider" {
type = string
description = "Nombre del Provider cloud"
default = ""
}
variable "Environment" {
type = string
description = "(Required) Specifies the Environment where the Resources should exist."
default = ""
}
variable "BussinessUnit" {
type = string
description = "(Required) Bussiness Unit."
default = ""
}
variable "ProjectName" {
type = string
description = "(Required) ProjectName."
default = ""
}
variable "ServiceName" {
type = string
description = "(Required) ServiceName."
default = ""
}
variable "EntityName" {
type = string
description = "(Required) Entity."
default = ""
}
variable "mapProjectPathKey" {
type = map(string)
default = {}
description = "Mapa de rutas de los elementos"
}
variable "region" {
type = string
description = "(Required) Region Name"
default = ""
}
variable "subscription_hub_id" {
type = string
default = ""
description = "Nombre de la subscripcion de HUB"
}
variable "hub_resource_group_name" {
type = string
default = ""
description = "Nombre del resource group de HUB"
}
#############################
# VARIABLES Keyvault #
#############################
variable "private_dns_zone_name_keyvault" {
type = string
description = "Nombre del private dns zone name"
default = ""
}
variable "rg_net_name" {
type = string
description = "Name rg of net"
default = ""
}
variable "vnet_net_name" {
type = string
description = "Name of vnet of net"
default = ""
}
variable "sbn_data_net_name" {
type = string
description = "Name of Subnet Data of net"
default = ""
}
variable "kv_enabled_for_disk_encryption" {
type = string
description = ""
default = ""
}
variable "kv_purgue_protection_enabled" {
type = string
description = ""
default = ""
}
variable "kv_sku_name" {
type = string
description = ""
default = ""
}
variable "kv_soft_delete_retention_days" {
type = string
description = ""
default = ""
}
######################
# VARIABLE TAGS #
######################
variable "tags" {
type = map(string)
default = {}
description = "(Optional) A mapping of tags which should be assigned to the Resource Group."
}Explanation:
Common variables:
These variables contain general information about the project's infrastructure and configuration.
lz_subscription_id- ID of the Azure subscription used to store the remote state (tfstate).lz_resource_group_name: Name of the resource group where Terraform remote state is stored.lz_storage_account_name: Name of the storage account that hosts the remote state file.lz_container_name: Name of the container within the storage where the Terraform state is located.Tenant- Azure Active Directory (AAD) tenant ID.Subscription- ID of the Azure subscription to use to create resources.Provider: Name of the cloud provider (for example,Azure).Environment: The environment where the resources should be deployed (e.g.dev,prod).BussinessUnit: The business unit related to the project.ProjectName: Project name to tag and organize resources.ServiceName: Name of the service being deployed.EntityName: Name of the entity that is being managed.mapProjectPathKey: Map containing specific paths to elements within the project.region- The Azure geographic region where the resources will be created.subscription_hub_id- ID of the subscription to use for the hub infrastructure.hub_resource_group_name: Name of the resource group for the hub infrastructure.
KeyVault variables:
This block defines variables related specifically to Azure Key Vault and its configuration.
private_dns_zone_name_keyvault: Name of the private DNS zone for the Key Vault.rg_net_name: Name of the network resource group.vnet_net_name: Name of the virtual network (VNet).sbn_data_net_name: Name of the data subnet.kv_enabled_for_disk_encryption: Setting whether Key Vault should be enabled for disk encryption.kv_purgue_protection_enabled: Settings to protect the Key Vault against purging.kv_sku_name: Name of the SKU for the Key Vault.kv_soft_delete_retention_days: Number of days the Key Vault will be kept in soft delete state.
Variable Tags:
This variable defines a set of tags that can be assigned to Azure resources, to facilitate their organization, billing and management.
terragrunt.hcl
The file terragrunt.hcl What you provide sets up an environment to manage infrastructure using Terragrunt, which is a tool for managing Terraform configurations in a modular way. Here is a detailed breakdown of what this file does:
dependencies {
paths = [
"../../rg/00/"
]
}
include "varEnvironment" {
path = find_in_parent_folders("varEnvironment.hcl")
expose = true
}
include "varCommon" {
path = find_in_parent_folders("varCommon.hcl")
expose = true
}
include "varDataState" {
path = find_in_parent_folders("varDataState.hcl")
expose = true
}
locals {
#acm = yamldecode(file(find_in_parent_folders("config.yaml"))).dataAcm
mapProjectPathKey = jsonencode(include.varEnvironment.inputs.mapProjectPathKey)
tags = jsonencode(merge({
Managed_By = "Terraform"
Provider = "AZR"
},
include.varCommon.inputs.globalTags,
include.varEnvironment.inputs.environmentTags
))
}
generate "backend"{
path = "backend.tfvars"
if_exists = "overwrite" # "overwrite" "skip" "overwrite_terragrunt"
contents = <<EOF
subscription_id = "${include.varDataState.inputs.lz_subscription_id}"
key = "${include.varCommon.inputs.ProjectName}/${include.varCommon.inputs.ServiceName}/${get_path_from_repo_root()}/terraform.tfstate"
resource_group_name = "${include.varDataState.inputs.lz_resource_group_name}"
storage_account_name = "${include.varDataState.inputs.lz_storage_account_name}"
container_name = "${include.varDataState.inputs.lz_container_name}"
EOF
}
generate "vars"{
path = "vars.tfvars"
if_exists = "overwrite" #"skip" #"overwrite_terragrunt"
contents = <<EOF
###############################
# VALORES DATA DataState #
###############################
lz_subscription_id = "${include.varDataState.inputs.lz_subscription_id}"
lz_resource_group_name = "${include.varDataState.inputs.lz_resource_group_name}"
lz_storage_account_name = "${include.varDataState.inputs.lz_storage_account_name}"
lz_container_name = "${include.varDataState.inputs.lz_container_name}"
###############################
# VALORES GENERALES #
###############################
region = "${include.varEnvironment.inputs.region}"
Environment = "${include.varEnvironment.inputs.Environment}"
BussinessUnit = "${include.varCommon.inputs.BussinessUnit}"
ProjectName = "${include.varCommon.inputs.ProjectName}"
ServiceName = "${include.varCommon.inputs.ServiceName}"
EntityName = "${include.varCommon.inputs.EntityName}"
Subscription = "${include.varEnvironment.inputs.Subscription}"
Tenant = "${include.varCommon.inputs.Tenant}"
# ApplicationName = null
mapProjectPathKey = ${local.mapProjectPathKey}
subscription_hub_id = "${include.varEnvironment.inputs.subscription_hub_id}"
hub_resource_group_name = "${include.varEnvironment.inputs.hub_resource_group_name}"
private_dns_zone_name_keyvault = "${include.varEnvironment.inputs.private_dns_zone_name_keyvault}"
###################################
# Valores Keyvault #
###################################
kv_enabled_for_disk_encryption = "true"
kv_soft_delete_retention_days = "7"
kv_purgue_protection_enabled = "true"
kv_sku_name = "standard"
###########################
# VALORES TAGS #
###########################
tags = ${local.tags}
EOF
}
terraform {
source = "../../..//code/keyvault/00/"
before_hook "print_tags" {
commands = ["plan", "apply"] #["${get_terraform_commands_that_need_vars()}"]
execute = ["echo", "tags", "=", "${local.tags}", ">", "vars.tfvars"]
}
before_hook "copy_vars" {
commands = ["plan", "apply"] #["${get_terraform_commands_that_need_vars()}"]
execute = ["cp", "-f", "vars.tfvars", "${get_original_terragrunt_dir()}/vars.tfvars"]
}
extra_arguments "backend_vars" {
commands = ["init"]
arguments = [
"-backend-config=backend.tfvars"
]
}
extra_arguments "vars_vars" {
commands = ["plan", "apply", "destroy", "import"]
arguments = [
"-var-file=vars.tfvars"
]
}
}Explanation:
dependencies: This block defines the Terragrunt dependencies. In this case, no dependency paths are specified, since the blockpathsIt is empty.
include: These blocks include external variable files (varEnvironment.hcl,varCommon.hcl,varDataState.hcl) in Terragrunt. The included files can expose their variables to be used in this Terragrunt file.
locals: This block defines local variables that are used within this Terragrunt file.
mapProjectPathKey: Encode the map as JSONmapProjectPathKeyfrom the filevarEnvironment.hcl.
tags: JSON-encodes a set of tags by combining a fixed set of tags (Managed_ByandProvider), the global labels defined invarCommon.hcland the environment-specific tags defined invarEnvironment.hcl.
generate "backend": This block generates a file calledbackend.tfvars. This file is used to configure the Terraform backend. It contains variables likesubscription_id,key,resource_group_name,storage_account_name, andcontainer_name. The values of these variables are obtained from the included files (varDataState.hclandvarCommon.hcl).
generate "vars": This block generates a file calledvars.tfvars. This file is used to provide variable values to Terraform. Contains values for specific variables defined in the included files (varDataState.hcl,varCommon.hcl,varEnvironment.hcl). The values are interpolated from the included variables.
terraform: This block provides additional settings for Terraform.
source: Specifies the source path of the Terraform module. In this case, the origin is set to a relative directory../../..//code/rg/00/.
before_hook: This block defines execution hooks that will be executed before certain Terraform commands, such asplanandapply. In this case, two hooks are executed:print_tagsandcopy_vars.
extra_arguments: This block specifies additional arguments to be passed to Terraform commands (init,plan,apply,destroy,import). In this case, additional arguments are specified for the backend configuration (backend_vars) and for the variables (vars_vars).
vars.tfvars
This file vars.tfvars Contains configuration settings that will be used in Terraform modules to configure resources in Azure. Here I explain the blocks and key values present in the file:
###############################
# VALORES DATA DataState #
###############################
lz_subscription_id = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
lz_resource_group_name = "PRO-HUB-01"
lz_storage_account_name = "keyvault"
lz_container_name = "keyvault"
###############################
# VALORES GENERALES #
###############################
region = "northeurope"
Environment = "dev"
BussinessUnit = "ag"
ProjectName = "infa"
ServiceName = "infa"
EntityName = "RO"
Subscription = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
Tenant = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
# ApplicationName = null
mapProjectPathKey = {"keyvault":"keyvault/00","rg":"rg/00","sbn00":"networking/sbn/sbn00","sbnVint00":"networking/sbn/vint00"}
subscription_hub_id = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
hub_resource_group_name = "PRO-NWHUB-RGP-01"
private_dns_zone_name_keyvault = "privatelink.vaultcore.azure.net"
###################################
# Valores Keyvault #
###################################
kv_enabled_for_disk_encryption = "true"
kv_soft_delete_retention_days = "7"
kv_purgue_protection_enabled = "true"
kv_sku_name = "standard"
Explanation:
1. Data State values (DataState)
These settings are related to configuring data state and basic infrastructure in Azure.
- lz_subscription_id: The ID of the Azure subscription where the resources will be managed. It is a unique identifier for the subscription in Azure.
- lz_resource_group_name: The name of the Azure resource group where resources related to this project will be grouped.
- lz_storage_account_name- The name of the Azure storage account used to store Terraform state or other persistent data.
- lz_container_name: The name of the container within the storage account where Terraform data or resource state is stored.
2. General Values
This block defines general parameters that are used to characterize the infrastructure environment and resources.
- region: The Azure region where the resources will be deployed. In this case, "northeurope" is specified as the region in which the infrastructure will be created.
- Environment: Defines the work environment, in this case "dev" (development).
- BusinessUnit: The business unit associated with this project, in this case "ag" (may refer to an abbreviation of the unit name).
- ProjectName: The name of the project, which in this case is "infa".
- ServiceName: The name of the service related to the project, here it is also "infa".
- EntityName: The name of the entity to which the service or project belongs, which is "RO".
- Subscription: The ID of the Azure subscription where the resources are managed, similar to
lz_subscription_id. - Tenant- The Azure tenant ID, which is the unique identifier for the Azure Active Directory directory.
- mapProjectPathKey: A JSON map that associates key names with project or module paths within the repository, making it easier to reference the different resources in the infrastructure.
- subscription_hub_id- The Azure subscription ID for the network hub, used for deployment of network resources.
- hub_resource_group_name: The name of the resource group for the network hub.
- private_dns_zone_name_keyvault: The name of the private DNS zone used by the KeyVault to enable private connectivity.
3. KeyVault Settings
This block contains specific settings for the KeyVault resource in Azure.
- kv_enabled_for_disk_encryption: Indicates whether KeyVault is enabled for disk encryption, in this case it is set to "true".
- kv_soft_delete_retention_days: Defines how many days soft deleted data will be kept before being permanently deleted. In this case, it is 7 days.
- kv_purge_protection_enabled: Enables or disables purge protection in KeyVault. Here it is set to "true", which means that deleted secrets cannot be purged until certain conditions are met.
- kv_sku_name: Defines the KeyVault SKU (Stock Keeping Unit). In this case, the "standard" SKU is specified, which is a standard option for KeyVault.
varEnvironment.hcl
locals {
subscription_hub_id = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
hub_resource_group_name = "PRO-NWHUB-RGP-01"
region = "northeurope"
Subscription = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
Environment = "dev"
rg_net_name = "DEV-REDORBITA-RG-01"
vnet_net_name = "DEV-REDORBITA-NET-01"
subnet_name = "DEV-REDORBITA-SBN-01"
mapProjectPathKey = {
rg = "rg/00"
sbn00 = "networking/sbn/sbn00"
}
}
inputs = {
##############################
# VARIABLES Environment #
##############################
subscription_hub_id = local.subscription_hub_id
hub_resource_group_name = local.hub_resource_group_name
vnet_net_name = local.vnet_net_name
subnet_name = local.subnet_name
rg_net_name = local.rg_net_name
Subscription = local.Subscription
region = local.region
#profile = local.profile
Environment = local.Environment
environmentTags = {
Enviroment = "${upper(local.Environment)}"
}
mapProjectPathKey = local.mapProjectPathKey
}Explanation:
Local Variables (locals):
- Variables are defined that can be used throughout the file. This includes subscription IDs, resource group names, network configurations, and more.
- Subscription Identifiers:
subscription_hub_idandSubscriptionThey are critical for authentication and resource management in Azure. - Resource Names: The names of resource groups, virtual networks, and subnets are established for ease of management and reference in the code.
- Project Maps:
mapProjectPathKeyallows you to define access paths to different components of the infrastructure, which can facilitate code reuse and navigation in the project.
Tickets (inputs):
- A map of inputs is defined to be used in Terraform modules. Each entry corresponds to a local variable, allowing modules to receive centrally configured values.
- Environment Tags:
environmentTagsis used to define tags to be applied to resources. Tags are useful for classifying, managing, and billing resources in Azure.
varCommon.hcl
This file varCommon.hcl contains local and input variables that are used in the Terraform project to configure the infrastructure and provide common information that can be reused across different modules and resources. Next, I explain each part of this file:
locals {
#common_vars = yamldecode(file(find_in_parent_folders("config.yaml")))
EntityName = "RO"
ProjectName = "RedOrbita"
ServiceName = "RedOrbita"
BussinessUnit = "XX"
Subscription = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
Tenant = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
Provider = "azr"
required_version = "~>0.14"
globalTags = {
Company = "Red-Orbita"
Owner = "xxxx@redorbita.com"
ProjectName = "XXXX"
"Service Description" = "XXXX"
Status = "Implementacion"
Provider = "Azure"
Cluster = "N/A"
"Operating System" = "N/A"
Temporal = "NO"
"App ID" = "N/A"
}
storage_account = "protfdata"
container_name = "iasearch"
subscription_hub_id2 = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
location = "northeurope"
}
inputs = {
##############################
# VARIABLES COMMON #
##############################
EntityName = local.EntityName
ProjectName = local.ProjectName
ServiceName = local.ServiceName
BussinessUnit = local.BussinessUnit
Subscription = local.Subscription
Tenant = local.Tenant
Provider = local.Provider
required_version = local.required_version
globalTags = local.globalTags
}
inputs = {
##############################
# VARIABLES COMMON #
##############################
EntityName = local.EntityName
ProjectName = local.ProjectName
ServiceName = local.ServiceName
BussinessUnit = local.BussinessUnit
# Subscription = local.Subscription
# Subscription_pro = local.Subscription_pro
Tenant = local.Tenant
Provider = local.Provider
required_version = local.required_version
id_project = local.id_project
globalTags = local.globalTags
}
1. Block locals
The block locals defines local variables within the file that can be used within this same file or by other Terraform modules. Here are some key settings:
- EntityName: Defines the name of the entity, which in this case is "RO". It can refer to a name or identifier for a project or group within the organization.
- ProjectName: The name of the project, here is "RedOrbita". This is the name of the project or initiative under which the resources are created.
- ServiceName: The name of the service related to the project, also "RedOrbita". Refers to the main service or solution to be implemented.
- BusinessUnit: The business unit associated with the project, which in this case is "XX".
- Subscription- The ID of the Azure subscription used to create and manage resources. This value must be the unique identifier for your Azure subscription.
- Tenant- The Azure tenant ID, which is a unique identifier for the Azure Active Directory.
- Provider: The infrastructure provider, in this case, "azr", indicating that the provider is Azure.
- required_version: The required version of Terraform to run the file, in this case, "~>0.14", meaning that any supported version of Terraform 0.14.x is valid.
- globalTags: A set of global tags that are applied to infrastructure resources. These tags include information about the project, such as the company name, owner, project status, and other details.
- Company: The name of the associated company, “Red-Orbita”.
- Owner: The email address of the project owner.
- ProjectName: A generic name for the project.
- Service Description: The description of the associated service.
- Status: The status of the project, which in this case is "Implementation".
- Provider: The infrastructure provider, “Azure”.
- Cluster: Defined as "N/A", suggesting that a cluster is not being used.
- Operating System: Also defined as "N/A", possibly indicating that the operating system is not specified.
- Temporary: Indicator of whether the project is temporary or not, in this case "NO".
- App ID: Set to "N/A", indicating that an application ID is not being used.
- storage_account: The name of the Azure storage account to use, in this case "protfdata".
- container_name: The name of the container within the storage account, which is "iasearch".
- subscription_hub_id2: Another subscription ID for the network hub, suggesting that more than one subscription is being used in the infrastructure.
- location: Defines the Azure region where the resources will be deployed, in this case "northeurope".
2. Block inputs
The block inputs defines variables to be passed to other Terraform modules or configuration files. Two blocks are repeated in this file inputs, but it is not necessary to define the same variables twice. The configuration of the first block is described here inputs:
- EntityName: The variable is assigned
EntityNameof the blocklocals. - ProjectName: The variable is assigned
ProjectNameof the blocklocals. - ServiceName: The variable is assigned
ServiceNameof the blocklocals. - BusinessUnit: The variable is assigned
BussinessUnitof the blocklocals. - Subscription: This value is commented out, indicating that this variable is not being actively used.
- Tenant: The variable is assigned
Tenantof the blocklocals. - Provider: The variable is assigned
Providerof the blocklocals. - required_version: The variable is assigned
required_versionof the blocklocals. - globalTags: The set of global labels defined in the block is assigned
locals.
The second block inputs It has a similar structure, but there are some differences:
- project_id: A variable is referenced
id_projectwhich is not defined in the blocklocals, suggesting that it should be defined elsewhere or passed from another file.
varDataState.hcl
This file varDataState.hcl It is used to define and organize variables related to the state of Terraform data and infrastructure in the workbench. This file contains configurations for storing Terraform state in Azure, which is crucial for managing infrastructure resources and their persistence. The purpose and use of the settings defined in this file are explained below:
locals {
#common_vars = yamldecode(file(find_in_parent_folders("config.yaml")))
lz_subscription_id = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
lz_resource_group_name = "PRO-HUB-01"
lz_storage_account_name = "keyvault"
lz_container_name = "keyvault"
path_resources_terraform_state = jsonencode({
rg = "rg/00"
})
}
inputs = {
##############################
# VARIABLES FOR DATA STATES #
##############################
lz_subscription_id = local.lz_subscription_id
lz_resource_group_name = local.lz_resource_group_name
lz_storage_account_name = local.lz_storage_account_name
lz_container_name = local.lz_container_name
path_resources_terraform_state = local.path_resources_terraform_state
}1. Block locals
The block locals defines local variables that will be used within the file and that can be reused in other parts of the project. Variables defined here include settings related to data storage and Terraform state management:
- lz_subscription_id: This is the ID of the Azure subscription where the resources will be stored. It is an important variable to identify the subscription within Azure in which the infrastructure resources will be created.
- lz_resource_group_name: This is the name of the Azure resource group that will contain the resources to store Terraform state. In this case, the resource group is called “PRO-HUB-01”.
- lz_storage_account_name- The name of the Azure storage account that will be used to save Terraform state. “keyvault” is used in this file.
- lz_container_name: The name of the container within the Azure storage account. In this case, the container is called "keyvault."
- path_resources_terraform_state: This variable is used to define the path where the Terraform state will be stored. In this case, the value of this variable is encoded as a JSON object containing a field
rgwith the value “rg/00”. This field indicates that the status will be stored in a folder called “rg/00” within the configured storage.
2. Block inputs
The block inputs defines variables that will be passed to other Terraform modules or external configurations. In this case, the variables defined in the block locals are exposed through the block inputs, which allows other configurations or modules to make use of them:
- lz_subscription_id: The value of
lz_subscription_iddefined in the blocklocals. This variable indicates the Azure subscription in which Terraform state will be managed.
- lz_resource_group_name: The value of
lz_resource_group_namedefined inlocals, specifying the resource group in Azure.
- lz_storage_account_name: The value of
lz_storage_account_namedefined inlocals, which indicates the storage account where the Terraform state will be saved. - lz_container_name: The value of
lz_container_namedefined inlocals, specifying the container where the state will be stored. - path_resources_terraform_state: The value of
path_resources_terraform_statedefined inlocals, which indicates the path within the container where the Terraform state will be saved (in this case, “rg/00”).
:wq!
Comments