This is the Day 30 of learning Terraform
This is the Day 30 of learning Terraform
Structural types in Terraform allow grouping multiple values with different types into a single
variable.
1. Object (): Represents a collection of values where each key has a specific type.
variable "os_configs"
{
type = object (
{
location = string size = string
instance_count = number
} ) }
Example:
os_configs = {
location = "eastus" size = "Standard_D2s_v3"
instance_count = 3
}
2. Tuple (): Represents a sequence of values where each position has a specific type.
variable "tuple_sample"
{
type = tuple ([string, number, bool])
}
Example:
tuple_sample = ["example", 42, true]
In the Threat Detection Policy block for an Azure MySQL Database, a tuple() type is used to
define related configuration values.
The Threat Detection Policy is not supported for the Basic Tier. Update the SKU to a General
Purpose Tier:
1. Before:
sku_name = "B_Gen5_2"
2. After:
sku_name = "GP_Gen5_2"
Supported values for sku_name include:
Basic: B_Gen4_1, B_Gen5_2, etc.
General Purpose: GP_Gen5_2, GP_Gen5_4, etc.
Memory Optimized: MO_Gen5_2, MO_Gen5_4, etc.
Specify the required values for the database and the Threat Detection Policy:
db_name = "mydb101"
db_storage_mb = 5120
db_auto_grow_enabled = true
tdpolicy = [
true, 10, true, ["user1@example.com", "user2@example.com"]
]
threat_detection_policy
{
enabled = var.tdpolicy[0]
retention_days = var.tdpolicy[1]
email_account_admins = var.tdpolicy[2]
email_addresses = var.tdpolicy[3]
}
1. Initialize Terraform:
terraform init
2. Validate Configuration Files:
terraform validate
3. Format Files:
terraform fmt
4. Review Execution Plan:
terraform plan -var-file="secrets.tfvars"
o Verify the values for the Threat Detection Policy are correctly replaced by the
tdpolicy variable.
5. Apply Changes (Optional):
terraform apply -var-file="secrets.tfvars"
Step-07: Verify Threat Detection Policy
Step-08: Clean-Up
Key Takeaways
c1-versions.tf
Explanation: - The provided Terraform code defines the Terraform block and the Provider
block, both of which are essential for configuring a Terraform project to work with the Azure
platform. Let’s break it down in detail:
Terraform Block: The Terraform block specifies global settings for the Terraform project, such
as the required Terraform version and the providers it uses.
terraform {
required_version = ">= 1.0.0"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = ">= 2.0"
} }}
Key Components:
1. required_version:
- Specifies the minimum version of Terraform that is required to run this configuration.
- >= 1.0.0: Indicates that any version starting from 1.0.0 (inclusive) is acceptable.
- Purpose:
- Ensures compatibility with the configuration syntax and features.
- Prevents issues caused by older versions of Terraform that might lack certain
functionalities.
2. required_providers:
- Declares the providers required for the project and their sources.
- In this example, it specifies the azurerm provider (used for managing Azure resources).
Provider Specification:
- azurerm:
- Refers to the Azure Resource Manager (AzureRM) provider, which enables Terraform to
manage resources in Microsoft Azure.
- source:
- Specifies where Terraform should fetch the provider from. In this case:
- "hashicorp/azurerm": Indicates that the provider is maintained by HashiCorp and is
available in the Terraform Registry.
- version:
- Specifies the minimum acceptable version of the azurerm provider.
- >= 2.0: Ensures that version 2.0 or newer of the provider is used.
Provider Block
The provider block configures settings specific to the declared provider, in this case, AzureRM.
provider "azurerm" {
features {}
}
Key Components:
1. provider "azurerm":
- Indicates the use of the AzureRM provider, which facilitates the creation and management
of Azure resources.
2. features {}:
- A mandatory block for the AzureRM provider from version 2.0 onwards.
- Even if left empty, it must be included to enable the default features of the provider.
- Purpose:
- Ensures compatibility with the provider's architecture and activates necessary internal
features.
- Custom Features:
- In advanced scenarios, this block can be used to enable or configure optional features of
the provider, such as using Azure Active Directory for authentication or custom behaviors for
certain resource types.
1. Setup:
- The terraform block defines the versions and sources of the required components.
- The provider block initializes the connection to Azure and ensures that Terraform can
interact with the Azure API.
2. Provider Download:
- When you run terraform init, Terraform downloads the AzureRM provider plugin based on
the source and version specified in the required_providers block.
3. Project Compatibility:
- By specifying a minimum Terraform version and provider version, this configuration
ensures that your project will run reliably across different environments.
- Reusability: Centralized control over the Terraform and provider versions ensures consistent
behavior across multiple environments.
- Version Control: Avoids compatibility issues by enforcing a minimum version requirement.
- Azure Management: Prepares Terraform to interact with Azure services, enabling the
creation, modification, and deletion of resources.
Example Usage
With this setup, you can now define and deploy Azure resources. For example:
resource "azurerm_resource_group" "example" {
name = "example-resource-group"
location = "East US"
}
1. Terraform will:
- Use the AzureRM provider to communicate with Azure.
- Ensure the provider version is 2.0 or above.
2. The resource group will be created in the "East US" region under your Azure subscription.
This foundational setup is the starting point for managing Azure resources with Terraform.
Terraform Manifest: -
c2-variables.tf
Explanation: - This code defines Terraform input variables to configure and manage resources,
primarily for deploying an Azure MySQL Database and associated infrastructure.
- Defines the business unit context for resource organization (e.g., "hr").
- Default: "hr".
- Default: "dev".
- Specifies the Azure Resource Group name where resources will be created.
- Default: "myrg".
- Default: "eastus".
- A key-value map for tagging Azure resources for identification and billing.
- Default:
{
"CLITool" = "Terraform"
"Tag1" = "Azure"
Threat detection policies define security settings for the MySQL database. Two approaches are shown:
Example:
Key Features
1. Default Values
2. Sensitive Variables
db_username and db_password are marked as sensitive to ensure security.
name = var.resoure_group_name
location = var.resoure_group_location
tags = var.common_tags
}
Terraform Manifest: -
c3-resource-group.tf
Explanation: - This Terraform code block defines an Azure Resource Group using the
azurerm_resource_group resource. A resource group in Azure is a container that holds related
resources for an Azure solution.
- azurerm_resource_group: The type of resource being created, which is an Azure Resource Group in
this case. It uses the AzureRM Terraform provider.
- "myrg": The unique name given to this resource within the Terraform configuration. You use this
name to reference the resource in other parts of your code.
2. Properties/Attributes
name
name = "${var.business_unit}-${var.environment}-${var.resource_group_name}"
- ${}: Denotes string interpolation in Terraform, allowing you to insert variables or expressions into
strings.
- var.environment: Refers to another variable, typically used to denote the environment, such as dev,
test, or prod.
- var.resource_group_name: A variable that represents a specific part of the resource group's name.
When these variables are defined, the resulting name could look like:
finance-prod-my-rg
location
location = var.resource_group_location
- Specifies the Azure region where the resource group will be created.
3. Comments
name = "my-rg1"
name = var.resource_group_name
- name = var.resource_group_name: Demonstrates a simpler use of a variable for the resource group
name, without string interpolation.
These comments provide alternatives for how the name can be defined.
4. Usage
variable "business_unit" {
default = "finance"
variable "environment" {
default = "prod"
variable "resource_group_name" {
default = "my-rg"
variable "resource_group_location" {
default = "eastus"
If these variable values are used, the created resource group will have:
- Name: finance-prod-my-rg
- Location: eastus
Terraform Manifest: -
c4-azure-mysql-database.tf
Explanation: - This Terraform script creates an Azure MySQL Database Server and a MySQL
Database within it.
1. Resource Definition
resource "azurerm_mysql_server" "mysqlserver" {
This defines an Azure MySQL Server resource in Terraform.
The identifier azurerm_mysql_server.mysqlserver is used to reference this resource throughout
the configuration.
2. Server Configuration
- Name:
name = "${var.business_unit}-${var.environment}-${var.db_name}"
- Dynamically constructs the server name using input variables (business_unit, environment,
and db_name).
- Example: If business_unit = "finance", environment = "prod", and db_name = "mydb", the
server name will be finance-prod-mydb.
- Location:
location = azurerm_resource_group.myrg.location
- Uses the location of the resource group (azurerm_resource_group.myrg) where the server
will reside.
- Resource Group:
resource_group_name = azurerm_resource_group.myrg.name
- Associates the server with the resource group (myrg).
3. Administrator Login
administrator_login = var.db_username
administrator_login_password = var.db_password
- Specifies the admin credentials for the MySQL server using variables (db_username and
db_password).
4. SKU Configuration
sku_name = "GP_Gen5_2"
- Defines the SKU (pricing tier) for the server. In this case:
- General Purpose Tier, 2 vCores.
- Suitable for production workloads with balanced performance and cost.
- Note:
- The supported values for sku_name are listed in the comment for reference:
B_Gen4_1, B_Gen4_2, GP_Gen5_4, etc.
- The Basic Tier (B_Gen5_2) is commented out because the Threat Detection Policy isn’t
supported for the Basic Tier.
5. Storage and Version
storage_mb = var.db_storage_mb
version = "8.0"
- Configures:
- storage_mb: Storage size in MB, passed via variable.
- version: Specifies MySQL version (e.g., 8.0).
6. Additional Settings
auto_grow_enabled = var.db_auto_grow_enabled
backup_retention_days = 7
geo_redundant_backup_enabled = false
infrastructure_encryption_enabled = false
public_network_access_enabled = true
ssl_enforcement_enabled = false
tags = var.common_tags
threat_detection_policy {
enabled = var.tdpolicy.enabled
retention_days = var.tdpolicy.retention_days
email_account_admins = var.tdpolicy.email_account_admins
email_addresses = var.tdpolicy.email_addresses
}
- Fields:
- enabled: Whether threat detection is enabled.
- retention_days: Number of days to retain threat detection data.
- email_account_admins: Sends alerts to account admins.
- email_addresses: List of email recipients.
1. Resource Definition
resource "azurerm_mysql_database" "webappdb1" {
Defines a MySQL database within the server.
2. Database Configuration
name = "webappdb1"
resource_group_name = azurerm_resource_group.myrg.name
server_name = azurerm_mysql_server.mysqlserver.name
charset = "utf8"
collation = "utf8_unicode_ci"
- Name:
- Specifies the database name as `webappdb1`.
- Resource Group:
- Associates the database with the same resource group as the server.
- Server Name:
- Links the database to the server created earlier.
Summary
This configuration:
1. Creates an Azure MySQL Server with General Purpose Tier, MySQL version 8.0, and
storage defined via input variables.
2. Implements a flexible Threat Detection Policy using an object variable (tdpolicy).
3. Creates a database (webappdb1) within the server with UTF-8 encoding and collation.
Key Benefits
- Dynamic and Flexible:
- Uses variables for key configurations, making it reusable and environment-agnostic.
- Security:
- Includes Threat Detection Policy to monitor suspicious activities.
- Scalability:
- Enables auto-grow for storage.
- Production-Ready:
- Configures a robust MySQL server suitable for general-purpose workloads.
Terraform Manifest: -
secrets.tfvars
Terraform Manifest: -
terraform.tfvars
Explanation: -
1. Generic Variables
business_unit = "it"
environment = "dev"
Purpose:
These variables define the organizational and environmental context for the resources.
- business_unit:
- Represents the business unit responsible for the resources.
- Example: "It" indicates the IT department.
- environment:
- Specifies the environment in which the resources will be deployed.
- Example: "dev" for a development environment. Other common environments could include
staging, qa, or prod.
Usage:
- These values are typically combined to create consistent naming conventions for resources.
- Example:
- A resource named using "${var.business_unit}-${var.environment}-${var.db_name}" will
result in: it-dev-mydb101.
- resoure_group_name:
- Specifies the name of the Resource Group.
- Example: "rg" for a generic name. A more descriptive name could be used for clarity (e.g.,
"rg-dev-it").
- resoure_group_location:
- Defines the Azure region where the Resource Group and its resources will be deployed.
- Example: "eastus" indicates deployment in the East US region.
- Other common locations include "westus", "centralus", and "westeurope".
3. Database Variables
db_name = "mydb101"
db_storage_mb = 5120
db_auto_grow_enabled = true
Purpose:
These variables define the configuration of the Azure MySQL Database Server.
- db_name:
- Specifies the name of the database server or database.
- Example: "mydb101" for a database named mydb101.
- db_storage_mb:
- Determines the storage capacity for the database server in megabytes.
- Example: 5120 corresponds to 5 GB of storage.
- db_auto_grow_enabled:
- Enables or disables automatic growth of storage as usage increases.
- Example: true ensures the server can scale its storage dynamically.
Purpose:
These variables define the Threat Detection Policy for the Azure MySQL Database Server.
This policy enhances security by monitoring and alerting about unusual database activities.
- tdpolicy:
- An object variable grouping related settings for the threat detection policy.
- This encapsulates multiple parameters into a single structure for simplicity and consistency.
tdpolicy Fields:
1. enabled:
- Enables or disables the threat detection policy.
- Example: true enables the policy.
2. retention_days:
- Defines how long the threat detection logs will be retained, in days.
- Example: 10 days of retention.
3. email_account_admins:
- Determines whether alerts are sent to the database server's account administrators.
- Example: true enables alerting for account admins.
4. email_addresses:
- A list of email addresses that will receive threat detection alerts.
- Example:
1. Resource Naming:
- The business_unit, environment, and db_name variables are combined to create resource
names.
- Example:
name = "${var.business_unit}-${var.environment}-${var.db_name}"
Result: it-dev-mydb101.
3. Database Configuration:
- The db_storage_mb and db_auto_grow_enabled variables configure storage capacity and
scalability.
4. Security:
- The tdpolicy object configures a robust Threat Detection Policy, ensuring:
- Threat detection is active.
- Alerts are retained for 10 days.
- Both administrators and specified recipients receive notifications.
1. Reusability:
- Variables allow the same configuration to be reused across environments (e.g., dev, staging,
prod).
2. Flexibility:
- Changing the value of a single variable can update multiple resources or settings.
3. Maintainability:
- Grouping related settings (e.g., tdpolicy) into an object reduces complexity and improves
readability.
4. Scalability:
- Dynamic naming and configuration support the growth of infrastructure without manual
intervention.