Logo

Le Blog Digital

Icone de temps 21 min de lecture

Mastering Infrastructure as Code: Key Trends and Best Practices in Hybrid Cloud, Terraform, and Kubernetes

Image de l'article

Netinq AI

Assistant IA du blog digital

Image de l'article
Arrière-plan

Bienvenue dans cette revue hebdomadaire dédiée au cloud !
Chaque semaine, nous analysons et synthétisons les actualités, tendances et évolutions majeures du cloud en nous basant sur diverses sources de référence : blogs spécialisés, forums, réseaux sociaux et publications techniques.

Que vous soyez passionné par Terraform, Pulumi, AWS CDK, Kubernetes ou d'autres outils IaC, ce résumé vous offre un condensé des informations essentielles pour rester à jour.

Avertissement : Contenu généré par IA avec MistralIA
Cet article a été généré automatiquement à l'aide d'une intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude des informations, des erreurs ou imprécisions peuvent subsister.

Si vous constatez une erreur ou souhaitez signaler un problème, n'hésitez pas à me contacter :
Email : pro@sarquentin.fr
LinkedIn : Quentin Sar

Le résumé de la semaine

  • Hybrid Cloud Management: Gartner predicts 90% of organizations will adopt hybrid cloud models by 2027, driven by AI demands. Managing hybrid cloud without adding friction to innovation workflows is crucial.
  • HCP Terraform: Introduces Hold Your Own Key (HYOK) for enhanced control over sensitive data stored in HCP Terraform, allowing organizations to secure secrets in Terraform artifacts.
  • CNCF Supply Chain Security: The 2025 Supply Chain Security Best Practices Guide emphasizes the importance of SBOMs, attestations, and software integrity tooling.
  • Zepto's Developer Platform: Zepto reduced onboarding time from 2 days to 10 minutes using Backstage, Kubernetes, and ArgoCD, enhancing developer productivity.
  • Kubernetes Conformance for AI: CNCF is exploring a conformance program centered around AI workloads in Kubernetes, with discussions happening in SIG-Architecture and a newly formed Working Group.
  • KubeCon + CloudNativeCon Europe 2026: The event will return to Amsterdam from 23–26 March 2026, focusing on key themes like platform engineering, AI, observability, and more.

Doing hybrid cloud right: Taking the complexity out of infrastructure management

The current operating state

The early days of cloud were exciting, but they also created a complex operating environment filled with a fragmented landscape of tools, inconsistent processes, and security risks. Teams within the same organizations often operated very differently, using different toolsets, provisioning infrastructure in their own way, and applying their own unique interpretation of security policies.

Empowering platform teams

For organizations to advance in cloud maturity, leaders must change how infrastructure, security, and development teams work together. Those that are excelling are using platform engineering teams combined with proper toolsets and standardized workflows to bring a greater measure of control to infrastructure management and implement safeguards where AI use cases can flourish.

The Infrastructure Cloud

The Infrastructure Cloud bridges silos and provides a unified control plane for delivering hybrid cloud infrastructure. Instead of fragmented environments and snowflake tools and workflows, teams use a hybrid-cloud supporting suite of products to bridge together all their environments — public cloud, private cloud, legacy, and on-premises — using one interface and standard workflows for every environment and workload.

HCP Terraform introduces Hold Your Own Key (HYOK)

Secrets access in Terraform

As customers migrate infrastructure to the cloud, there is a growing demand for increased control over secrets access. Secrets are sensitive, discrete pieces of information such as credentials, encryption keys, authentication certificates, and other critical pieces of information your applications need to run consistently and securely.

Introducing Hold Your Own Key (HYOK)

Hold Your Own Key (HYOK) is a security principle that gives organizations ownership of the encryption keys used to access their sensitive data. With HYOK, organizations can take ownership over secret access by securing and encrypting Terraform artifacts before they are uploaded to HCP Terraform.

Getting started

Hold Your Own Key (HYOK) is now available in HCP Terraform. Refer to the HYOK documentation to take ownership of state and plan file encryption today.

Chain Reaction in Amsterdam: What’s New in CNCF’s 2025 Supply Chain Security Guide

Why It Matters Now

Since 2021, the ecosystem around software supply chain security has exploded. SBOMs, attestations, and software integrity tooling have matured fast, and open source communities have kept pace, building standards, frameworks, and pipelines to detect and defend against tampering, dependency confusion, and unauthorized changes.

Projects You’ll Hear About

John will highlight key projects from the CNCF and OpenSSF ecosystem, including Bomctl, GUAC, in-toto, Protobom, SBOMit, SLSA, and TUF.

Also Catch: A Deep Dive into Public Sector Software Security

Immediately after this session, John will return to the stage to explore supply chain security from a public sector perspective.

Zepto Wins CNCF End User Case Study Contest for Developer Platform Innovation with Backstage, Argo, and Kubernetes

Zepto's Developer Platform

To address these challenges, Zepto built an internal developer platform using Backstage, Kubernetes, and ArgoCD, streamlining how teams onboard new services, provision infrastructure, and manage deployments.

The platform delivered measurable outcomes

A 90% reduction in setup time, full CI/CD coverage across services, and complete operational independence for developers. Weekly onboarding queues were eliminated, and the platform now supports frequent, stable deployments with standardized security and configuration practices.

CNCF Celebrates India’s Cloud Native Community Growth, Recognizing a Kubestronaut Milestone

India leads global participation in CNCF’s Kubestronaut program

India accounts for 180 Kubestronauts, making it the country with the highest number of people who have successfully passed certification requirements. The United States and Germany follow closely behind in the second and third highest number of Kubestronauts, respectively.

Golden Kubestronauts

Golden Kubestronauts demonstrate exceptional commitment to cloud native learning by completing all 14 CNCF certifications along with the Linux Foundation Certified System Administrator (LFCS) certification.

The CFP for KubeCon + CloudNativeCon Europe 2026 Is Closing 12 October

Key Dates

  • CFP Deadline for KubeCon + CloudNativeCon Europe 2026: 12 October, 2025
  • Event Location: Amsterdam, The Netherlands
  • Event Dates: 23 – 26 March 2026

KubeCon + CloudNativeCon Europe 2026: Returning to Amsterdam, 23–26 March

Why Attend in 2026

The Netherlands is quickly establishing itself as a hub for cloud native and digital innovation in Europe. The country hosts several CNCF projects, 21 member organizations, and 14 certified partners and providers.

Key Themes: Platform Engineering, AI, Observability, and More

KubeCon + CloudNativeCon Europe 2026 will spotlight critical themes that matter to developers, operators, platform engineers, and open source contributors: from GitOps and service mesh patterns to real-world AI integration and cost-aware observability strategies.

Automating EKS CIS Compliance with Kyverno and KubeBench

The Compliance Challenge in Cloud Native Environments

The CIS Amazon EKS Benchmark v1.7.0 contains 46 security recommendations across five critical areas: Control Plane Configuration, Worker Node Security, RBAC & Service Accounts, Pod Security Standards, and Managed Services.

The Multi-Tool Cloud Native Approach to Complete CIS Coverage

Modern cloud native compliance requires acknowledging that no single tool can validate all CIS controls due to the diverse nature of the requirements. This implementation combines the strengths of multiple CNCF and cloud native security tools.

Framework Strengths and Realistic Limitations

The project takes an honest, engineering-focused approach to tool capabilities. Project Strengths: Multi-Tool Integration, Kube-bench Integration, Comprehensive Documentation, KIND Cluster Testing, Transparent Limitations, Realistic Approach.

What 500+ Experts Revealed About Kubernetes Adoption and Workloads

Cloud native infrastructure has undergone a transformational journey

Once used for ephemeral workloads and DevTest environments, technologies like Kubernetes are now becoming the gold standard for application development. In fact, 41% of respondents say their current application footprint is already mostly cloud native.

Mission critical applications are built in cloud native

It should come as no surprise, then, that this increased investment in cloud native platforms means that most enterprises are running important applications in containers. In fact, 58% are running mission critical applications in containers, meaning applications that have strict requirements for performance and uptime.

Cloud native environments run into challenges with persistent storage

Of course, scaling mission-critical workloads in cloud native environments isn’t without its hurdles. Survey respondents cite top challenges such as security (72%), observability (51%), resilience (35%), and persistent storage (31%).

PaC in the Cloud Native Landscape

Cloud Native PaC

When we get into CNCF’s landscape there’s a Security and Compliance section, where all security-related projects are listed. In this list we have solutions like IDPs (Identity Providers), Runtime Security, Vulnerability Analysis, Key, Secret and Certificate managers.

PaC in Kubernetes

We cannot talk about Cloud Native without talking about Kubernetes. Being one of the pillars of a Cloud Native architecture, the biggest companies in the world are running their solutions in Kubernetes clusters.

Automated Governance Maturity Model

With the purpose of helping companies on their Cloud Native Security and Policy as Code journey, the CNCF TAG Security developed a Maturity Model that outlines expected outcomes of well executed PaC implementation projects.

Help Us Build the Kubernetes Conformance for AI

The CNCF community is exploring a conformance program centered around AI workloads in the Kubernetes space. Announced in alpha form in June 2025 at both KubeCon + CloudNativeCon China and KubeCon + CloudNativeCon Japan, this program is similar to the Kubernetes Conformance program.

CNCF Unveils Schedule for 10th Anniversary Edition of KubeCon + CloudNativeCon North America

Highlights at KubeCon + CloudNativeCon North America 2025 include

  • AI + ML
  • Observability
  • Platform Engineering
  • Operations + Performance
  • Cloud Native Experience

Terraform Fundamentals: EBS (EC2)

Managing EC2 EBS Volumes with Terraform: A Production Deep Dive

The relentless demand for persistent storage in modern applications often leads to complex EC2 EBS volume management. Manually provisioning, resizing, snapshotting, and encrypting these volumes is error-prone and doesn’t scale. Infrastructure as Code (IaC) with Terraform is the solution, but simply using the aws_ebs_volume resource isn’t enough.

What is "EBS (EC2)" in Terraform Context?

Within Terraform, managing EBS volumes is primarily done through the AWS provider and the aws_ebs_volume resource. This resource allows declarative definition of EBS volume characteristics: size, type, availability zone, encryption, tags, and more. It also integrates with other AWS resources like aws_instance for attachment and aws_snapshot for backups.

Use Cases and When to Use

  • Database Provisioning
  • Application Tier Storage
  • Data Analytics Pipelines
  • Disaster Recovery
  • Development/Test Environments

Key Terraform Resources

  • aws_ebs_volume
  • aws_volume_attachment
  • aws_snapshot
  • aws_snapshot_copy
  • aws_instance
  • aws_iam_role
  • aws_iam_policy
  • aws_ebs_encryption

Common Patterns & Modules

  • Dynamic Blocks
  • for_each
  • Remote Backend
  • Layered Modules
  • Monorepo

Hands-On Tutorial

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-west-2"
}

resource "aws_ebs_volume" "example" {
  availability_zone = "us-west-2a"
  size              = 5
  type              = "gp3"
  tags = {
    Name = "example-volume"
  }
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b2ab9998a261a"
  instance_type = "t2.micro"
}

resource "aws_volume_attachment" "example" {
  device_name = "/dev/xvdf"
  volume_id   = aws_ebs_volume.example.id
  instance_id = aws_instance.example.id
}

output "volume_id" {
  value = aws_ebs_volume.example.id
}

Enterprise Considerations

Large organizations leverage Terraform Cloud/Enterprise for state management, remote operations, and collaboration. Sentinel or Open Policy Agent (OPA) are used for policy-as-code, enforcing compliance and security constraints.

Security and Compliance

Enforce least privilege using IAM roles and policies. Use aws_iam_policy to restrict access to only necessary EBS actions. Implement tagging policies to categorize and track volumes. Enable EBS encryption by default. Regularly audit EBS snapshots for compliance. Drift detection tools identify unauthorized changes.

Integration with Other Services

  • AWS EC2
  • AWS RDS
  • AWS Lambda
  • AWS Auto Scaling
  • AWS CloudWatch

Module Design Best Practices

  • Abstraction
  • Input Variables
  • Output Variables
  • Locals
  • Documentation
  • Versioning

CI/CD Automation

# .github/workflows/ebs-deploy.yml

name: EBS Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: hashicorp/setup-terraform@v2
      - run: terraform fmt
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - run: terraform apply tfplan

Pitfalls & Troubleshooting

  • Volume Attachment Errors
  • Resizing Issues
  • Encryption Conflicts
  • IAM Permissions
  • State Corruption
  • Incorrect Device Names

Pros and Cons

Pros:

  • Automation
  • Consistency
  • Version Control
  • Scalability
  • Auditing

Cons:

  • Complexity
  • State Management
  • Disruptive Operations
  • Vendor Lock-in

Terraform Fundamentals: DynamoDB

DynamoDB with Terraform: A Production-Grade Deep Dive

The relentless pressure to deliver features faster often leads to complex application architectures. A common challenge is managing rapidly changing data requirements for features like user profiles, session management, or real-time analytics. Traditional relational databases can become bottlenecks, requiring schema migrations and scaling efforts that slow down development.

What is "DynamoDB" in Terraform Context?

In Terraform, DynamoDB is managed through the aws provider. The primary resource is aws_dynamodb_table, allowing you to define table schemas, provisioned capacity, and other critical settings.

Use Cases and When to Use

  • User Session Management
  • Gaming Leaderboards
  • E-commerce Shopping Carts
  • Real-time Analytics
  • Content Management Systems (CMS)

Key Terraform Resources

  • aws_dynamodb_table
  • aws_dynamodb_global_secondary_index
  • aws_dynamodb_local_secondary_index
  • aws_dynamodb_table_encryption
  • aws_dynamodb_stream_enabled
  • aws_dynamodb_stream_view
  • aws_dynamodb_tag
  • aws_dynamodb_point_in_time_recovery

Common Patterns & Modules

  • Remote Backend
  • Dynamic Blocks
  • for_each
  • Layered Modules
  • Monorepo

Hands-On Tutorial

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_dynamodb_table" "users" {
  name             = "user-data"
  billing_mode     = "PAY_PER_REQUEST"
  hash_key         = "user_id"
  attribute {
    name = "user_id"
    type = "S"
  }
  attribute {
    name = "email"
    type = "S"
  }
}

Enterprise Considerations

Large organizations leverage Terraform Cloud/Enterprise for state locking, remote execution, and collaboration. Sentinel or Open Policy Agent (OPA) are used for policy-as-code, enforcing constraints on DynamoDB configurations (e.g., requiring encryption, limiting provisioned capacity).

Security and Compliance

Enforce least privilege using aws_iam_policy to restrict access to DynamoDB resources.

resource "aws_iam_policy" "dynamodb_policy" {
  name        = "dynamodb-access-policy"
  description = "Policy for accessing DynamoDB tables"
  policy      = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "dynamodb:GetItem",
          "dynamodb:PutItem",
          "dynamodb:UpdateItem",
          "dynamodb:DeleteItem"
        ]
        Effect   = "Allow"
        Resource = "${aws_dynamodb_table.users.arn}/*"
      }
    ]
  })
}

Integration with Other Services

  • Lambda
  • API Gateway
  • S3
  • CloudWatch
  • IAM

Module Design Best Practices

Abstract DynamoDB configurations into reusable modules. Use input variables for configurable parameters (e.g., table name, billing mode, capacity). Define output variables for important attributes (e.g., table ARN, stream ARN). Utilize locals for derived values. Document modules thoroughly with examples and usage instructions. Employ a backend like S3 for remote state storage.

CI/CD Automation

name: DynamoDB Deployment

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: hashicorp/setup-terraform@v2
      - run: terraform fmt
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - run: terraform apply tfplan

Pitfalls & Troubleshooting

  • Provisioned Capacity Issues
  • Attribute Type Mismatches
  • Global Secondary Index Limitations
  • IAM Permission Errors
  • State Corruption
  • DynamoDB Streams Throttling

Pros and Cons

Pros:

  • Scalability
  • Low Latency
  • Managed Service
  • Flexibility
  • Terraform Integration

Cons:

  • Complexity
  • Query Limitations
  • Cost
  • Vendor Lock-in

Terraform Fundamentals: Documentation

Terraform Documentation: A Production-Grade Deep Dive

Infrastructure as code (IaC) has become the standard for managing cloud resources. However, simply having code isn’t enough. Maintaining a clear understanding of why infrastructure exists, its intended purpose, and the responsible teams is critical, especially as environments scale.

What is "Documentation" in Terraform Context?

Terraform doesn’t have a dedicated “Documentation” resource. Instead, documentation is achieved through the strategic use of metadata embedded within resources, modules, and variables. This metadata is typically stored as string values within resource attributes, module input/output variables, or local variables.

Use Cases and When to Use

  • Ownership & Accountability
  • Cost Allocation
  • Compliance & Auditability
  • Application Context
  • Environment Purpose

Key Terraform Resources

  • resource "aws_instance" "example"
  • module "vpc" { ... }
  • variable "owner" { ... }
  • data "aws_caller_identity" "current"
  • local "environment"
  • terraform_remote_state
  • aws_security_group
  • aws_iam_policy

Common Patterns & Modules

  • Remote Backend with Tagging
  • Dynamic Blocks for Tags
  • for_each for Repetitive Resources
  • Monorepo Structure
  • Layered Modules

Hands-On Tutorial

variable "name" {
  type        = string
  description = "The name of the VPC."
}

variable "owner" {
  type        = string
  description = "The team responsible for this VPC."
}

variable "purpose" {
  type        = string
  description = "The purpose of this VPC."
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name        = var.name
    Owner       = var.owner
    Purpose     = var.purpose
    Environment = "Development"
  }
}

output "vpc_id" {
  value = aws_vpc.main.id
}

Enterprise Considerations

Large organizations leverage Terraform Cloud/Enterprise for state management, remote runs, and collaboration. Sentinel policies can be used to validate the presence and format of documentation metadata.

Security and Compliance

Enforce least privilege using IAM policies that restrict Terraform access to only the necessary resources.

resource "aws_iam_policy" "terraform_access" {
  name        = "terraform-access-policy"
  description = "Policy granting Terraform access to create VPCs"
  policy      = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "ec2:CreateVpc",
          "ec2:DescribeVpcs"
        ]
        Effect   = "Allow"
        Resource = "*"
      }
    ]
  })
  tags = {
    Environment = local.environment
  }
}

Integration with Other Services

  • CloudWatch (AWS)
  • Azure Monitor (Azure)
  • Google Cloud Operations Suite (GCP)
  • ServiceNow
  • PagerDuty

Module Design Best Practices

Abstract documentation into reusable modules by accepting documentation metadata as input variables. Use descriptive variable names and provide clear descriptions. Utilize locals to standardize documentation values. Document modules thoroughly using Markdown. Use a consistent naming convention for documentation attributes. Employ a robust testing strategy to ensure documentation metadata is correctly applied.

CI/CD Automation

# .github/workflows/terraform.yml

name: Terraform CI/CD

on:
  push:
    branches:
      - main

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: hashicorp/setup-terraform@v2
      - run: terraform fmt
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - run: terraform apply -auto-approve tfplan

Pitfalls & Troubleshooting

  • Inconsistent Tagging
  • Missing Documentation
  • State Corruption
  • Policy Violations
  • Difficult Search
  • Overly Verbose Tags

Pros and Cons

Pros:

  • Improved infrastructure understanding and maintainability
  • Enhanced cost allocation and governance
  • Simplified compliance and auditability
  • Faster incident response and troubleshooting
  • Increased developer productivity

Cons:

  • Requires discipline and consistent application of conventions
  • Adds complexity to Terraform configurations
  • Metadata is stored in Terraform state, increasing state size
  • No enforced schema, leading to potential inconsistencies

Terraform Fundamentals: DocumentDB Elastic

DocumentDB Elastic with Terraform: A Production Deep Dive

The relentless pressure to scale applications while maintaining data consistency and low latency is a constant challenge. Traditional database provisioning often becomes a bottleneck, requiring manual intervention and slowing down development cycles.

What is DocumentDB Elastic in Terraform Context?

DocumentDB Elastic isn’t a standalone Terraform resource; it’s a configuration within an existing Azure Cosmos DB account. Terraform manages the Cosmos DB account and its associated Elastic capabilities through the azurerm provider.

Use Cases and When to Use

  • Event-Driven Architectures
  • Microservices with Spiky Traffic
  • Development/Testing Environments
  • Content Management Systems (CMS)
  • Personalization Engines

Key Terraform Resources

  • azurerm_resource_group
  • azurerm_cosmosdb_account
  • azurerm_cosmosdb_sql_container
  • azurerm_cosmosdb_sql_role_definition
  • azurerm_cosmosdb_sql_user
  • azurerm_cosmosdb_sql_role_assignment
  • azurerm_diagnostic_setting
  • azurerm_monitor_diagnostic_setting

Common Patterns & Modules

  • Remote Backend
  • Dynamic Blocks
  • for_each
  • Layered Architecture
  • Monorepo

Hands-On Tutorial

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "rg-documentdb-elastic-demo"
  location = "East US"
}

resource "azurerm_cosmosdb_account" "example" {
  name                = "cosmosdb-elastic-demo"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  kind                = "GlobalDocumentDB"
  consistency_level   = "Session"

  capabilities {
    enable_elastic = true
  }
}

resource "azurerm_cosmosdb_sql_container" "example" {
  name                = "my-demo-container"
  account_name        = azurerm_cosmosdb_account.example.name
  database_name = "my-database"
  partition_key_path = "/id"
}

Enterprise Considerations

Large organizations typically leverage Terraform Cloud/Enterprise for state management, remote operations, and collaboration. Sentinel or Open Policy Agent (OPA) are used for policy-as-code, enforcing compliance rules (e.g., allowed locations, consistency levels).

Security and Compliance

  • Least Privilege
  • RBAC
  • Policy Constraints
  • Drift Detection
  • Tagging Policies
  • Auditability

Example IAM policy:

resource "azurerm_role_assignment" "example" {
  scope              = azurerm_resource_group.example.id
  role_definition_id = "/subscriptions/<subscription_id>/providers/Microsoft.Authorization/roleDefinitions/4e95e578-5d9c-43a9-84f6-89988c8994d5" # Contributor Role

  principal_id       = "<service_principal_id>"
}

Integration with Other Services

  • Azure Functions
  • Azure Event Hubs
  • Azure Logic Apps
  • Azure Synapse Analytics
  • Azure API Management

Module Design Best Practices

  • Abstraction
  • Input/Output Variables
  • Locals
  • Backends
  • Documentation

CI/CD Automation

# .github/workflows/cosmosdb-elastic.yml

name: Deploy Cosmos DB Elastic

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: hashicorp/setup-terraform@v2
      - run: terraform fmt
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - run: terraform apply tfplan

Pitfalls & Troubleshooting

  • State Corruption
  • Resource Naming Conflicts
  • Incorrect Partition Key
  • Insufficient RU/s
  • IAM Permissions
  • Elastic Not Enabled

Pros and Cons

Pros:

  • Scalability
  • Cost-Effectiveness
  • Simplified Management
  • MongoDB Compatibility

Cons:

  • Complexity
  • Vendor Lock-in
  • Monitoring
  • Potential Latency

Terraform Fundamentals: DocumentDB

DocumentDB with Terraform: A Production-Grade Deep Dive

The relentless pressure to deliver features faster often leads to complex data modeling requirements. Traditional relational databases can become bottlenecks, hindering agility. Many teams find themselves needing a flexible, scalable, and schema-less database solution.

What is "DocumentDB" in Terraform Context?

Within Terraform, DocumentDB is managed through the azurerm provider. The core resource is azurerm_cosmosdb_account, representing the Cosmos DB account itself.

Use Cases and When to Use

  • Personalization Engines
  • Content Management Systems (CMS)
  • IoT Data Ingestion
  • E-commerce Catalogs
  • Gaming Leaderboards & Player Data

Key Terraform Resources

  • azurerm_cosmosdb_account
  • azurerm_resource_group
  • azurerm_cosmosdb_sql_container
  • azurerm_cosmosdb_sql_database
  • azurerm_role_assignment
  • data.azuread_client_config
  • time_sleep
  • azurerm_cosmosdb_virtual_network_rule

Common Patterns & Modules

  • Remote Backend
  • Dynamic Blocks
  • for_each
  • Layered Architecture
  • Monorepo

Hands-On Tutorial

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "cosmosdb-example-rg"
  location = "East US"
}

resource "azurerm_cosmosdb_account" "example" {
  name                = "cosmosdb-example-account"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  kind                = "GlobalDocumentDB"
  consistency_level   = "Session"
}

resource "time_sleep" "wait_for_cosmosdb" {
  depends_on = [azurerm_cosmosdb_account.example]
  create_duration = "60s"
}

resource "azurerm_cosmosdb_sql_database" "example" {
  account_name = azurerm_cosmosdb_account.example.name
  name = "example-database"
}

resource "azurerm_cosmosdb_sql_container" "example" {
  account_name = azurerm_cosmosdb_account.example.name
  database_name = azurerm_cosmosdb_sql_database.example.name
  name = "example-container"
  partition_key_path = "/id"
}

Enterprise Considerations

Large organizations leverage Terraform Cloud/Enterprise for state management, remote runs, and collaboration. Sentinel or Azure Policy can enforce compliance rules. IAM design should follow the principle of least privilege, using Azure AD groups and role assignments.

Security and Compliance

Enforce least privilege using azurerm_role_assignment. Implement RBAC to control access to Cosmos DB resources. Use Azure Policy to enforce tagging policies (e.g., environment, owner) for cost tracking and governance.

resource "azurerm_role_assignment" "cosmosdb_contributor" {
  scope              = azurerm_cosmosdb_account.example.id
  role_definition_name = "Cosmos DB Contributor"
  principal_id       = data.azuread_group.example.id
}

data "azuread_group" "example" {
  display_name = "CosmosDBAdmins"
}

Integration with Other Services

  • Azure Functions
  • Azure Logic Apps
  • Azure Event Hubs
  • Azure Synapse Analytics
  • Azure App Service

Module Design Best Practices

Abstract DocumentDB into reusable modules with well-defined input variables (e.g., name, location, resource_group_id, consistency_level). Use output variables to expose key attributes (e.g., account_id, endpoint). Utilize locals for complex configurations. Document the module thoroughly with examples and usage instructions. Consider using a backend like Terraform Cloud for versioning and collaboration.

CI/CD Automation

# .github/workflows/cosmosdb-deploy.yml

name: Deploy Cosmos DB

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: hashicorp/setup-terraform@v2
      - run: terraform fmt
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - run: terraform apply tfplan

Pitfalls & Troubleshooting

  • Provisioning Delays
  • Partition Key Selection
  • Throttling
  • Consistency Level
  • State Corruption
  • Network Connectivity

Pros and Cons

Pros:

  • Scalability and Flexibility
  • Global Distribution
  • Schema-less Data Model
  • Strong Integration with Azure Services
  • Terraform-managed lifecycle

Cons:

  • Cost can be high
  • Asynchronous provisioning requires workarounds
  • Partition key design is critical
  • Complexity of consistency levels
  • Potential for throttling

Terraform Fundamentals: Docs

Terraform Docs: A Production-Grade Deep Dive

Infrastructure as code (IaC) has matured beyond simply provisioning resources. Modern challenges demand robust documentation as code – not separate, often outdated, documents.

What is "Docs" in Terraform Context?

Terraform doesn’t have a dedicated “Docs” resource in the traditional sense. Instead, documentation is intrinsically linked to Terraform modules and providers. The Terraform Registry (https://registry.terraform.io/) serves as the central repository for these documented components.

Use Cases and When to Use

  • Self-Service Infrastructure Platforms
  • Compliance and Auditability
  • Onboarding New Engineers
  • Complex Module Abstractions
  • Standardized Infrastructure Patterns

Key Terraform Resources

  • terraform_registry_module (Data Source)
  • module (Resource)
  • local (Resource)
  • terraform_remote_state (Data Source)
  • null_resource (Resource)
  • terraform_remote_state (Resource)
  • output (Block)
  • variable (Block)

Common Patterns & Modules

  • Remote Backend with Version Control
  • Dynamic Blocks for Documentation
  • Monorepo Structure
  • Layered Modules
  • Environment-Based Modules

Hands-On Tutorial

Module (modules/simple_ec2/main.tf):

resource "aws_instance" "example" {
  ami           = "ami-0c55b2ab9998a969f" # Replace with a valid AMI
  instance_type = var.instance_type
  tags = {
    Name = "SimpleEC2"
  }
}

variable "instance_type" {
  type        = string
  description = "The EC2 instance type to use."
  default     = "t2.micro"
}

output "public_ip" {
  value       = aws_instance.example.public_ip
  description = "The public IP address of the EC2 instance."
}

Module Documentation (modules/simple_ec2/README.md):

# Simple EC2 Module

This module creates a single EC2 instance.

## Usage

terraform module "ec2" { source = "./modules/simpleec2" instancetype = "t3.medium" }

output "ec2ip" { value = module.ec2.publicip }

## Inputs

| Name          | Type   | Description                 | Default |
|---------------|--------|-----------------------------|---------|
| `instance_type` | string | The EC2 instance type to use | `t2.micro` |

## Outputs

| Name      | Description                     |
|-----------|---------------------------------|
| `public_ip` | The public IP address of the instance |

Root Module (main.tf):

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1" # Replace with your desired region
}

module "ec2" {
  source = "./modules/simple_ec2"
  instance_type = "t3.medium"
}

output "ec2_ip" {
  value = module.ec2.public_ip
}

Enterprise Considerations

Large organizations leverage Terraform Cloud/Enterprise for state management, remote runs, and collaboration. Sentinel policies can be used to validate module inputs against documented constraints.

Security and Compliance

Enforce least privilege using IAM policies like:

resource "aws_iam_policy" "terraform_policy" {
  name        = "TerraformPolicy"
  description = "Policy for Terraform access"
  policy      = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "s3:GetObject",
          "s3:PutObject",
          "s3:DeleteObject",
          "s3:ListBucket"
        ]
        Effect   = "Allow"
        Resource = [
          "arn:aws:s3:::my-terraform-state-bucket",
          "arn:aws:s3:::my-terraform-state-bucket/*"
        ]
      }
    ]
  })
}

Integration with Other Services

  • Terraform Cloud/Enterprise
  • GitHub/GitLab
  • CI/CD Pipelines
  • Sentinel
  • Cloud Providers (AWS, Azure, GCP)

Module Design Best Practices

  • Clear Input/Output Variables
  • Locals for Complex Logic
  • Well-Structured Directory Layout
  • Comprehensive README.md
  • Backend Configuration

CI/CD Automation

# .github/workflows/terraform.yml

name: Terraform CI/CD

on:
  push:
    branches:
      - main

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: hashicorp/setup-terraform@v2
      - run: terraform fmt
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - run: terraform apply -auto-approve -input=false

Pitfalls & Troubleshooting

  • Documentation Drift
  • Incorrect AMI IDs
  • Missing Provider Configuration
  • State Locking Issues
  • Insufficient IAM Permissions

Pros and Cons

Pros:

  • Improved documentation accuracy and consistency
  • Reduced onboarding time for new engineers
  • Enhanced compliance and auditability
  • Increased reusability of infrastructure components

Cons:

  • Requires discipline from module authors to maintain documentation
  • Reliance on the Terraform Registry
  • Potential for documentation drift if not actively managed

Source

Découvre d'autres articles sur ce sujet

Image d'illustration de l'article

Optimiser l'infrastructure as Code : Tendances et innovations pour les développeurs

Image d'illustration de l'article

Les 10 questions clés pour concevoir un environnement cloud sécurisé

Image d'illustration de l'article

Les tendances et innovations de l'infrastructure as code en 2024 : Terraform, AWS, Azure, GitOps et plus