0% found this document useful (0 votes)
13 views30 pages

This is the Day 30 of learning Terraform

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views30 pages

This is the Day 30 of learning Terraform

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Day: - 30

Title: Terraform Input Variables with Structural Type tuple


Description: Learn about Terraform Input Variables with
Structural Type tuple
Explanation: -

Step-01: Introduction to Terraform Variables Structural Types

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]

Step-02: Enabling Threat Detection Policy with tuple()

In the Threat Detection Policy block for an Azure MySQL Database, a tuple() type is used to
define related configuration values.

1. Define the Variable:


variable "tdpolicy"
{
description = "Azure MySQL DB Threat Detection Policy"
type = tuple ([bool, number, bool, list(string)])
}
o Tuple structure:
 bool: Whether the policy is enabled.
 number: Retention days for threat logs.
 bool: Whether to notify admins by email.
 list(string): List of email addresses to notify.

2. Sample Values in terraform.tfvars:

tdpolicy = [true, 10, true, ["user1@example.com", "user2@example.com"]]

Step-03: Update SKU for General Purpose Tier

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.

Step-04: Update terraform.tfvars

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"]
]

Step-05: Define Threat Detection Policy Block

Define the Threat Detection Policy using the tdpolicy variable.

1. Using Hardcoded Values:


threat_detection_policy
{
enabled = true retention_days = 10
email_account_admins = true
email_addresses = ["user1@example.com", "user2@example.com"]
}

2. Using tuple() Variable:

threat_detection_policy
{
enabled = var.tdpolicy[0]
retention_days = var.tdpolicy[1]
email_account_admins = var.tdpolicy[2]
email_addresses = var.tdpolicy[3]
}

Step-06: Execute Terraform Commands

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

1. Navigate to the Azure Portal.


2. Go to Azure MySQL Database > Security > Azure Defender for MySQL.
3. Verify that the settings match the Terraform configuration.

Step-08: Clean-Up

To destroy resources and clean up files:


Destroy Resources
terraform destroy -var-file="secrets.tfvars"
Remove Terraform State Files
rm -rf .terraform rm -rf terraform.tfstate

Key Takeaways

1. Structural Types (object() and tuple()):


o Useful for grouping related variable values with clear type constraints.
2. Threat Detection Policy with tuple():
o Demonstrates how to pass complex configurations into Terraform blocks
dynamically.
3. Modular Configuration:
o Separates variable definitions (tdpolicy) from resource blocks for better
maintainability and flexibility.
4. General-Purpose SKU:
o Required for advanced features like Threat Detection Policy.
Terraform Manifest-v1: -

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.

- Why Specify a Version?


- To maintain stability and avoid unexpected behavior due to breaking changes in newer
versions.

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.

How It Works Together

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.

Purpose and Benefits

- 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"
}

When combined with the above blocks:

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.

Purpose of Each Variable

1. Business Unit Name (business_unit)

- Defines the business unit context for resource organization (e.g., "hr").

- Default: "hr".

2. Environment Name (environment)

- Represents the environment (e.g., development, staging, or production).

- Default: "dev".

3. Resource Group Name (resoure_group_name)

- Specifies the Azure Resource Group name where resources will be created.

- Default: "myrg".

4. Resource Group Location (resoure_group_location)

- Specifies the Azure region for the Resource Group.

- Default: "eastus".

5. Common Tags (common_tags)

- A key-value map for tagging Azure resources for identification and billing.

- Default:
{

"CLITool" = "Terraform"

"Tag1" = "Azure"

6. Azure MySQL Database Name (db_name)

- Name of the MySQL database to be created.

- No default provided (must be explicitly set).

7. Azure MySQL Database Username (db_username)

- Username for the MySQL database administrator.

- Declared as sensitive, ensuring it won’t appear in logs or output.

- No default value provided.

8. Azure MySQL Database Password (db_password)

- Password for the MySQL database administrator.

- Also marked sensitive for security reasons.

- No default value provided.

9. Azure MySQL Database Storage (db_storage_mb)

- Defines storage in MB for the database.

- Data type: number.

- Example usage: 5120 for 5 GB storage.

10. Azure MySQL Database Auto Grow (db_auto_grow_enabled)

- A Boolean flag to enable or disable the database's auto-grow feature.


- Example: true to enable auto-grow.

Threat Detection Policy (tdpolicy)

Threat detection policies define security settings for the MySQL database. Two approaches are shown:

a) Commented object Definition

A structured object type with keys:

- enabled (bool): Enable or disable threat detection.

- retention_days (number): Retention duration for logs (in days).

- email_account_admins (bool): Notify account admins via email.

- email_addresses (list of strings): List of email addresses for notifications.

b) Active tuple Definition

- Defines the same fields as a tuple.

- Tuple sequence: [enabled (bool), retention_days (number), email_account_admins (bool),


email_addresses (list of strings)].

Example:

tdpolicy = [true, 30, true, ["admin@example.com", "security@example.com"]]

Key Features

1. Default Values

Most variables have defaults, simplifying configurations for reusable modules.

2. Sensitive Variables
db_username and db_password are marked as sensitive to ensure security.

3. Flexible Data Types

- String, number, bool for straightforward values.

- Map, object, and tuple for complex configurations.

4. Threat Detection Policy Options

Demonstrates flexibility using either object or tuple.

Use Case in Terraform

This variable definition supports modular deployment of Azure infrastructure by allowing:

- Customization per environment.

- Consistent tagging and resource naming.

- Secure configuration of database credentials.

- Advanced security configurations for threat detection.

Example usage in a main.tf file:

resource "azurerm_resource_group" "rg" {

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.

1. Resource Block Declaration

resource "azurerm_resource_group" "myrg" {

- resource: Specifies a resource to create and manage in Terraform.

- 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}"

- Specifies the name of the Azure Resource Group.


- The value is dynamically constructed using variables. Here's what each part means:

- ${}: Denotes string interpolation in Terraform, allowing you to insert variables or expressions into
strings.

- var.business_unit: Refers to a variable named business_unit, likely defined elsewhere in the


Terraform configuration. This variable might represent a logical grouping (e.g., "finance" or
"marketing").

- 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.

- var.resource_group_location: Refers to a variable containing the location, e.g., `eastus`, `westus2`,


etc.

3. Comments

name = "my-rg1"

name = var.resource_group_name

- These are commented-out lines, likely for testing or future use:

- name = "my-rg1": Shows a hardcoded example of a 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

- This resource will create a Resource Group in Azure with:

- A name composed of the business_unit, environment, and resource_group_name variables.

- A location defined by the resource_group_location variable.

5. Example Variable Definitions

To make this resource functional, the referenced variables (business_unit, environment,


resource_group_name, resource_group_location) must be defined in the Terraform configuration,
typically in a variables.tf file or inline. For example:

variable "business_unit" {

default = "finance"

variable "environment" {

default = "prod"

variable "resource_group_name" {

default = "my-rg"

variable "resource_group_location" {

default = "eastus"

6. Final Generated Resource Group

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.

Azure MySQL Database Server

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

- Auto-grow: Whether to enable auto-scaling of storage.


- Backup Retention: Retains backups for 7 days.
- Geo-Redundant Backup: Disables geo-redundancy for backups.
- Encryption: Infrastructure encryption is disabled.
- Public Network Access: Enables access to the server over the public internet.
- SSL: Disables SSL enforcement.
- Tags: Applies tags for resource management.
7. Threat Detection Policy

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
}

- Configures a Threat Detection Policy for the server.


- Uses input variables (tdpolicy) for flexibility.

- 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.

Azure MySQL Database

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.

- Charset & Collation:


- Configures database character set (utf8) and collation (utf8_unicode_ci).

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.

2. Resource Group Variables


resoure_group_name = "rg"
resoure_group_location = "eastus"
Purpose:
These variables configure the Azure Resource Group, which serves as the logical container for
related resources.

- 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.

4. Threat Detection Policy Variables


tdpolicy = {
enabled = true,
retention_days = 10,
email_account_admins = true,
email_addresses = [ "ankitranjanjobs@gmail.com", "stacksimplify@gmail.com" ]
}

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:

email_addresses = [ "ankitranjanjobs@gmail.com", "stacksimplify@gmail.com" ]


- Sends alerts to the specified recipients.

How These Variables Are Used

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.

2. Azure Resource Group:


- The resoure_group_name and resoure_group_location determine the container and location
for all resources.

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.

Why This Approach?

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy