Arquitectura de Datos

Data Mesh: Automation, Infrastructure as Code, and DataOps, How to Build Reproducible and Scalable Data Platforms

Learn how to automate the provisioning, validation, and deployment of Data Products in a Data Mesh by combining reusable Terraform modules, CI/CD pipelines with temporary identities, and DataOps practices on AWS.

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

When a Successful Manual Lab Becomes an Operational Bottleneck

In the previous article, we built a working first version of the sales-orders, confirmed-payments, and inventory-availability Data Products for CommerceFlow on AWS. Using AWS CLI commands and interactive DDL statements in Amazon Athena, we separated internal zones from published interfaces, registered technical metadata in AWS Glue Data Catalog, and restricted consumer access with AWS Lake Formation.

The trouble started the following week, when engineering leadership asked to replicate that exact setup across staging and production environments and onboard nine additional Data Products across the three domains. Attempting to scale the manual process triggered three incidents within forty-eight hours:

  1. Configuration Drift: In the lab environment, someone had manually added a discount_amount column to sales_orders through the AWS Glue web console without recording the change in Git. When the table was recreated in staging, Finance queries failed because the column was missing.
  2. Copy-Paste Errors Across Domains: The Inventory team copied the Sales team's CLI script to register Lake Formation permissions, forgot to update one ARN in the --resource flag, and accidentally overwrote permissions belonging to the neighboring domain.
  3. Blind Deployments Without Pre-Validation: A partition change on confirmed-payments was applied directly in production on Friday afternoon without validating the contract first or checking whether the operation would destroy and recreate the catalog table metadata, leaving BI consumers without data for two hours.

A Self-Serve Data Platform cannot rely on engineers remembering manual CLI sequences or clicking through web consoles. Scaling a Data Mesh architecture safely and consistently requires combining Infrastructure as Code (IaC), CI/CD pipelines, and DataOps engineering practices.


Infrastructure as Code, CI/CD, and DataOps: What Each Discipline Solves

Technical discussions frequently blur terms that operate at different layers. Before writing Terraform modules or deployment pipelines, let us distinguish six complementary concepts with precision:

ConceptScopeConcrete Role in CommerceFlowWhat It Does NOT Solve by Itself
Declarative ConfigurationDescribing what target state is desired (in YAML, JSON, or HCL) rather than scripting how to reach it step by step.The Sales domain declares the schema, owner, and sensitivity of sales-orders inside a product.yaml file.A YAML file is inert text until a validator and automation engine translate it into real actions.
Infrastructure as Code (IaC)Provisioning and managing cloud infrastructure (S3 buckets, Glue databases/tables, Lake Formation grants, KMS keys) through version-controlled code.Ensures sales_products.sales_orders has the exact same structure and security policies across dev, staging, and prod.IaC is not DataOps: having a properly provisioned S3 bucket and Glue table does not mean pipelines run or data values are accurate.
Process AutomationExecuting repetitive tasks without manual intervention via scripts or orchestrators.Compiling a product descriptor or scheduling an hourly validation run.Automating a flawed process without tests only propagates errors faster.
Continuous Integration (CI)Automatically validating every proposed Git change using static checks, schema/contract tests, and security scans before merging.Blocks a Pull Request if a change to sales-orders breaks backward compatibility or introduces an IAM * wildcard.Does not deploy changes to target environments or monitor live runtime data.
Continuous Delivery (CD)Promoting validated code and infrastructure artifacts to staging and prod in a controlled, reproducible, and auditable way.Runs terraform apply using short-lived credentials after plan review and verifies that the table responds in Athena.Does not replace ongoing freshness or volume monitoring when upstream data shifts.
DataOpsThe end-to-end set of cultural, architectural, and operational practices to develop, test, version, deploy, monitor, and operate data pipelines and Data Products.Unifies the code lifecycle (IaC + transformations) with the data lifecycle (quality checks, SLI/SLOs, lineage, and incident response).It is not a single commercial tool or a synonym for Terraform.

The Essential Distinction in a Data Mesh Platform

Never assume that a green terraform apply means you have a working Data Product. In production, four distinct milestones must be met:

  1. Provisioned Resources: The S3 bucket, Glue Data Catalog table, and Lake Formation grants exist in AWS.
  2. Operational Pipeline: The ingestion and transformation jobs execute on schedule.
  3. Published Data: Parquet files exist inside the published/ prefix.
  4. Trustworthy Data Product: The published records satisfy their Data Contract, pass quality validations, and meet their freshness and completeness SLOs.

Terraform Fundamentals Applied to a Data Mesh Platform

Terraform lets teams define cloud infrastructure in declarative HCL (HashiCorp Configuration Language) while tracking the real-world state of deployed resources:

  • Providers: Plugins that connect Terraform to cloud provider APIs (here, the official hashicorp/aws provider).
  • Resources: Concrete infrastructure objects that Terraform creates, updates, or destroys (such as aws_glue_catalog_database, aws_glue_catalog_table, or aws_lakeformation_permissions).
  • Variables and Outputs: Typed input parameters and exported return values that let you parameterize configurations without duplicating code.
  • Modules: Reusable packages of resources that encapsulate a standard architectural pattern (for example, CommerceFlow's internal module for provisioning the catalog entry and access grants of any Data Product).
  • State (terraform.tfstate) and Execution Plan (terraform plan): Terraform compares the desired configuration in .tf files against the recorded state file and live AWS APIs to compute an execution plan: which resources will be created (+), modified in place (~), or destroyed/replaced (- / -/+).

Responsibility Boundaries: Platform Team vs. Domain Teams

A common anti-pattern is forcing every domain analyst or engineer to write hundreds of lines of low-level Terraform for S3, KMS, IAM, and Lake Formation from scratch. In a well-designed Self-Serve Data Platform, responsibilities split cleanly across two layers:

+-------------------------------------------------------------------------+
| 1. DOMAIN TEAM (Sales, Payments, Inventory)                             |
|    - Authors the declarative Data Product descriptor (product.yaml)     |
|    - Defines schema, sensitivity classification, and SQL/transformation |
|    - Declares authorized consumers and domain quality expectations      |
+-------------------------------------------------------------------------+
                                   |
                                   v (Validates contract & generates tfvars.json)
+-------------------------------------------------------------------------+
| 2. PLATFORM TEAM (Self-Serve Data Platform)                             |
|    - Maintains versioned, pre-tested reusable Terraform modules         |
|    - Maintains the descriptor compiler/validator and CI/CD templates    |
|    - Manages remote state backends, OIDC federation, and guardrails     |
+-------------------------------------------------------------------------+

Key Technical Clarification: Terraform does not magically parse arbitrary business YAML schemas or build ETL pipelines on its own just because you write metadata. To connect a domain's product.yaml descriptor with infrastructure modules, the platform team provides a validation and translation layer (written in Python or using HCL yamldecode functions) that enforces governance rules and outputs the exact input variables consumed by the Terraform modules.


Practical Case in CommerceFlow: Repository Layout and Declarative Product Descriptor

To turn the manual AWS lab from Article 21 into a reproducible platform for Sales, Payments, and Inventory, we structure our Git repository to separate shared platform modules from domain product declarations:

commerceflow-data-mesh-infra/
├── platform-modules/
│   └── data_product_catalog/         # Reusable module maintained by the Platform Team
│       ├── variables.tf
│       ├── main.tf
│       └── outputs.tf
├── domains/
│   ├── sales/
│   │   └── sales-orders/
│   │       └── product.yaml          # Descriptor maintained by the Sales Domain
│   ├── payments/
│   │   └── confirmed-payments/
│   │       └── product.yaml          # Descriptor maintained by the Payments Domain
│   └── inventory/
│       └── inventory-availability/
│           └── product.yaml          # Descriptor maintained by the Inventory Domain
├── scripts/
│   └── compile_product_descriptor.py # Contract validator & tfvars generator
└── environments/
    └── prod/
        ├── backend.tf                # Remote S3 state configuration
        └── main.tf                   # Module instantiation across products

Declarative Data Product Descriptor (domains/sales/sales-orders/product.yaml)

The Sales domain declares the properties of sales-orders in a concise, human-readable YAML file that can be reviewed in a Pull Request:

apiVersion: mesh.commerceflow.internal/v1
kind: DataProduct
metadata:
  name: sales-orders
  domain: sales
  ownerEmail: sales-data-team@commerceflow.internal
  contractVersion: "1.1.0"
  classification: confidential
  freshnessSloMinutes: 60

storage:
  bucketName: commerceflow-mesh-prod-111122223333
  publishedPrefix: domains/sales/published/sales_orders/v1/
  format: PARQUET
  compression: SNAPPY

catalog:
  databaseName: sales_products
  tableName: sales_orders
  partitionKeys:
    - name: order_date
      type: date
  columns:
    - name: order_id
      type: string
      comment: "Global unique order identifier"
      sensitivity: internal
    - name: customer_id_hash
      type: string
      comment: "Pseudonymized customer identifier (HMAC)"
      sensitivity: confidential
    - name: order_status
      type: string
      comment: "Status: PENDING, PAID, SHIPPED, CANCELLED, REFUNDED"
      sensitivity: internal
    - name: total_amount
      type: decimal(12,2)
      comment: "Gross order amount"
      sensitivity: confidential
    - name: currency
      type: string
      comment: "ISO 4217 currency code"
      sensitivity: public
    - name: created_at
      type: string
      comment: "UTC ISO 8601 creation timestamp"
      sensitivity: internal
    - name: updated_at
      type: string
      comment: "UTC ISO 8601 last update timestamp"
      sensitivity: internal

accessControl:
  producerRoleArn: arn:aws:iam::111122223333:role/commerceflow-sales-producer-role
  authorizedConsumers:
    - team: finance-and-bi
      principalArn: arn:aws:iam::111122223333:role/commerceflow-bi-order-finance-role
      permissions: ["SELECT", "DESCRIBE"]

Self-Contained Governance Validator and Compiler in Python

Before running any Terraform command in the CI/CD pipeline, a platform script validates that the descriptor complies with federated governance rules (naming conventions, S3 prefix isolation per domain, valid sensitivity classifications, and no wildcard * principals) and compiles it into a product.auto.tfvars.json file that parameterizes the Terraform module.

The following Python module is completely self-contained (using only the standard library), enforces preventive governance checks, and includes automated assertions:

import json
import re
from typing import Any, Dict, List


ALLOWED_CLASSIFICATIONS = {"public", "internal", "confidential", "restricted"}
ALLOWED_DOMAINS = {"sales", "payments", "inventory"}
VALID_IDENTIFIER_RE = re.compile(r"^[a-z][a-z0-9_]*$")


def validate_and_compile_descriptor(descriptor: Dict[str, Any]) -> Dict[str, Any]:
    """
    Validates a declarative Data Product descriptor against federated governance
    policies and returns a dictionary matching Terraform module input variables.
    """
    meta = descriptor.get("metadata", {})
    storage = descriptor.get("storage", {})
    catalog = descriptor.get("catalog", {})
    access = descriptor.get("accessControl", {})

    domain = meta.get("domain", "")
    if domain not in ALLOWED_DOMAINS:
        raise ValueError(f"Invalid domain: '{domain}'. Allowed: {sorted(ALLOWED_DOMAINS)}")

    classification = meta.get("classification", "")
    if classification not in ALLOWED_CLASSIFICATIONS:
        raise ValueError(f"Invalid classification: '{classification}'.")

    db_name = catalog.get("databaseName", "")
    table_name = catalog.get("tableName", "")
    if not VALID_IDENTIFIER_RE.match(db_name) or not VALID_IDENTIFIER_RE.match(table_name):
        raise ValueError("databaseName and tableName must use alphanumeric snake_case.")

    # Domain isolation policy: Glue database and S3 prefix must belong to the owning domain
    expected_db_prefix = f"{domain}_"
    if not db_name.startswith(expected_db_prefix):
        raise ValueError(
            f"Domain isolation violation: databaseName '{db_name}' must start with '{expected_db_prefix}'."
        )

    published_prefix = storage.get("publishedPrefix", "")
    expected_s3_prefix = f"domains/{domain}/published/"
    if not published_prefix.startswith(expected_s3_prefix) or not published_prefix.endswith("/"):
        raise ValueError(
            f"S3 path violation: publishedPrefix '{published_prefix}' must start with "
            f"'{expected_s3_prefix}' and end with '/'."
        )

    columns: List[Dict[str, str]] = catalog.get("columns", [])
    if not columns:
        raise ValueError("The Data Product must declare at least one column in the catalog.")

    for col in columns:
        if col.get("sensitivity") not in ALLOWED_CLASSIFICATIONS:
            raise ValueError(
                f"Column '{col.get('name')}' is missing a valid sensitivity classification tag."
            )

    # Security policy: forbid wildcards in consumer principal ARNs
    consumers = access.get("authorizedConsumers", [])
    consumer_principals: List[str] = []
    for consumer in consumers:
        arn = consumer.get("principalArn", "")
        if "*" in arn or not arn.startswith("arn:aws:iam::"):
            raise ValueError(f"Invalid or overly permissive consumer ARN: '{arn}'.")
        consumer_principals.append(arn)

    # Build the Terraform input variable dictionary
    bucket_name = storage["bucketName"]
    return {
        "product_name": meta["name"],
        "domain": domain,
        "owner_email": meta["ownerEmail"],
        "contract_version": meta["contractVersion"],
        "classification": classification,
        "database_name": db_name,
        "table_name": table_name,
        "s3_bucket_name": bucket_name,
        "s3_published_location": f"s3://{bucket_name}/{published_prefix}",
        "columns": [
            {"name": c["name"], "type": c["type"], "comment": c.get("comment", "")}
            for c in columns
        ],
        "partition_keys": catalog.get("partitionKeys", []),
        "consumer_role_arns": consumer_principals,
    }


if __name__ == "__main__":
    sample_sales_descriptor = {
        "metadata": {
            "name": "sales-orders",
            "domain": "sales",
            "ownerEmail": "sales-data-team@commerceflow.internal",
            "contractVersion": "1.1.0",
            "classification": "confidential",
        },
        "storage": {
            "bucketName": "commerceflow-mesh-prod-111122223333",
            "publishedPrefix": "domains/sales/published/sales_orders/v1/",
        },
        "catalog": {
            "databaseName": "sales_products",
            "tableName": "sales_orders",
            "partitionKeys": [{"name": "order_date", "type": "date"}],
            "columns": [
                {"name": "order_id", "type": "string", "comment": "PK", "sensitivity": "internal"},
                {"name": "total_amount", "type": "decimal(12,2)", "comment": "Total", "sensitivity": "confidential"},
            ],
        },
        "accessControl": {
            "authorizedConsumers": [
                {
                    "team": "finance-and-bi",
                    "principalArn": "arn:aws:iam::111122223333:role/commerceflow-bi-order-finance-role",
                }
            ]
        },
    }

    compiled_tfvars = validate_and_compile_descriptor(sample_sales_descriptor)
    assert compiled_tfvars["database_name"] == "sales_products"
    assert compiled_tfvars["s3_published_location"] == (
        "s3://commerceflow-mesh-prod-111122223333/domains/sales/published/sales_orders/v1/"
    )

    # Negative test: attempt to point a Sales product at the Payments domain S3 prefix
    invalid_cross_domain = json.loads(json.dumps(sample_sales_descriptor))
    invalid_cross_domain["storage"]["publishedPrefix"] = "domains/payments/published/hack/v1/"
    try:
        validate_and_compile_descriptor(invalid_cross_domain)
        raise AssertionError("Should have blocked cross-domain S3 path.")
    except ValueError as err:
        assert "S3 path violation" in str(err)

    print("Descriptor validated and compiled to Terraform tfvars JSON successfully.")

Designing the Reusable Terraform Module (platform-modules/data_product_catalog)

Once the validator script checks the descriptor and emits the parameters, the reusable Terraform module maintained by the platform team takes over. Below are the core educational fragments of the module (variables.tf, main.tf, and outputs.tf) that automate provisioning the AWS Glue Data Catalog table and AWS Lake Formation grants:

# platform-modules/data_product_catalog/variables.tf
variable "product_name" {
  type        = string
  description = "Canonical Data Product name (e.g., sales-orders)"
}

variable "domain" {
  type        = string
  description = "Owning business domain (sales, payments, inventory)"
}

variable "owner_email" {
  type        = string
  description = "Contact email of the domain owner team"
}

variable "contract_version" {
  type        = string
  description = "Semantic version of the Data Contract"
}

variable "database_name" {
  type        = string
  description = "Target database name in AWS Glue Data Catalog"
}

variable "table_name" {
  type        = string
  description = "Target table name in AWS Glue Data Catalog"
}

variable "s3_published_location" {
  type        = string
  description = "S3 URI of the Data Product published zone"
}

variable "columns" {
  type = list(object({
    name    = string
    type    = string
    comment = string
  }))
  description = "Published column schema of the Data Product"
}

variable "partition_keys" {
  type = list(object({
    name = string
    type = string
  }))
  default     = []
  description = "Partition keys of the table"
}

variable "consumer_role_arns" {
  type        = set(string)
  default     = []
  description = "Set of IAM role ARNs authorized to query the Data Product"
}
# platform-modules/data_product_catalog/main.tf
resource "aws_glue_catalog_table" "data_product_table" {
  name          = var.table_name
  database_name = var.database_name
  table_type    = "EXTERNAL_TABLE"

  parameters = {
    "EXTERNAL"                      = "TRUE"
    "parquet.compression"           = "SNAPPY"
    "data_product.name"             = var.product_name
    "data_product.domain"           = var.domain
    "data_product.owner"            = var.owner_email
    "data_product.contract_version" = var.contract_version
    "managed_by"                    = "terraform-self-serve-platform"
  }

  dynamic "partition_keys" {
    for_each = var.partition_keys
    content {
      name = partition_keys.value.name
      type = partition_keys.value.type
    }
  }

  storage_descriptor {
    location      = var.s3_published_location
    input_format  = "org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat"
    output_format = "org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat"

    ser_de_info {
      name                  = "parquet-serde"
      serialization_library = "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"
      parameters = {
        "serialization.format" = "1"
      }
    }

    dynamic "columns" {
      for_each = var.columns
      content {
        name    = columns.value.name
        type    = columns.value.type
        comment = columns.value.comment
      }
    }
  }
}

# Declarative AWS Lake Formation grant for each authorized consumer role
resource "aws_lakeformation_permissions" "consumer_table_select" {
  for_each = var.consumer_role_arns

  principal   = each.value
  permissions = ["SELECT", "DESCRIBE"]

  table {
    database_name = var.database_name
    name          = aws_glue_catalog_table.data_product_table.name
  }
}
# platform-modules/data_product_catalog/outputs.tf
output "catalog_table_fqn" {
  description = "Fully qualified database.table identifier registered in Glue"
  value       = "${var.database_name}.${aws_glue_catalog_table.data_product_table.name}"
}

With this module in place, provisioning catalog metadata and Lake Formation permissions for sales-orders, confirmed-payments, and inventory-availability requires zero copy-pasted boilerplate: environments/prod/main.tf simply instantiates module "data_product_catalog" for each validated product descriptor.


Managing Remote State Safely, Temporary Identities, and Destructive Changes

Operating Terraform across multiple teams in a Data Mesh requires three production safeguards that must never be skipped:

1. Encrypted Remote State and Concurrency Locking

The terraform.tfstate file maps your HCL resource blocks to real-world AWS resource IDs. It must never be stored on an engineer's laptop or committed to Git, as it can contain sensitive metadata and will corrupt infrastructure if two pipelines run terraform apply concurrently. In AWS, remote state is stored in a dedicated, versioned, SSE-KMS encrypted S3 bucket with state locking enabled.

2. Zero Static Credentials in CI/CD via OIDC Federation

Never store long-lived AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY secrets in GitHub Actions, GitLab CI, or Jenkins. Instead, configure OpenID Connect (OIDC) federation between your CI/CD provider and AWS IAM: during a workflow run, the runner requests a short-lived signed token and assumes an IAM role via sts:AssumeRoleWithWebIdentity scoped strictly to the authorized repository and branch.

3. Why terraform apply Is Not Automatically Safe

Terraform is declarative, but certain edits to .tf files force a destructive replacement (-/+ destroy and then create replacement):

  • Changing the name attribute of a Glue database or table destroys the existing catalog object and creates a new one, breaking views or grants attached to the previous resource.
  • Changing an S3 bucket name attempts to delete the previous bucket.
  • Furthermore, if someone modifies a Lake Formation permission manually in the AWS console (out-of-band drift), Terraform only detects that drift the next time terraform plan or terraform apply -refresh-only runs.

Consequently, never run terraform apply -auto-approve blindly in production without reviewing the exact terraform plan artifact first.


End-to-End CI/CD and DataOps Workflow for Publishing a Data Product

Let us see how Git, contract validation, Terraform planning/application, and post-deployment data verification connect inside a conceptual CI/CD workflow (shown in GitHub Actions YAML syntax):

# Conceptual CI/CD and DataOps workflow for CommerceFlow
name: deploy-sales-orders-data-product

on:
  pull_request:
    paths:
      - "domains/sales/sales-orders/**"
      - "platform-modules/**"
  push:
    branches:
      - main
    paths:
      - "domains/sales/sales-orders/**"

permissions:
  id-token: write   # Required to request OIDC token for AWS STS
  contents: read

jobs:
  validate-and-plan:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: 1. Validate Data Product descriptor and governance rules
        run: |
          python3 scripts/compile_product_descriptor.py \
            --input domains/sales/sales-orders/product.yaml \
            --output environments/prod/sales_orders.auto.tfvars.json

      - name: 2. Authenticate to AWS via OIDC (Short-lived STS credentials)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::111122223333:role/commerceflow-cicd-planner-role
          aws-region: us-east-1

      - name: 3. Check formatting, initialize, and generate Terraform plan
        working-directory: environments/prod
        run: |
          terraform fmt -check
          terraform init -input=false
          terraform validate
          terraform plan -out=tfplan -input=false

  apply-and-verify-data:
    needs: validate-and-plan
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: production-approval # Requires approval gate before applying changes
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: 1. Assume OIDC deployment role and apply verified plan
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::111122223333:role/commerceflow-cicd-deployer-role
          aws-region: us-east-1

      - name: 2. Execute controlled Terraform Apply
        working-directory: environments/prod
        run: |
          terraform init -input=false
          terraform apply -input=false tfplan

      - name: 3. Post-deployment DataOps verification (Schema & Quality in Athena)
        run: |
          python3 scripts/verify_published_product_athena.py \
            --database sales_products \
            --table sales_orders \
            --workgroup commerceflow-dataops-verification

Notice the final step (verify_published_product_athena.py): this is where DataOps extends beyond Infrastructure as Code. Once Terraform confirms that the Glue catalog entry and Lake Formation permissions are live, the pipeline runs an automated smoke and quality query in Amazon Athena to verify that:

  1. The table can be queried without permission or Parquet serialization errors.
  2. The exposed schema matches contract version 1.1.0.
  3. Baseline uniqueness (order_id), completeness, and freshness indicators meet the thresholds declared in product.yaml.

Three Scenarios with Different Automation and DataOps Decisions

Scenario 1: Multi-Domain E-Commerce Ecosystem (CommerceFlow)

  • Context: Three domains (Sales, Payments, Inventory) managing more than 15 Data Products evolving weekly across dev, staging, and prod.
  • Decision: Adopt per-domain declarative product.yaml descriptors, validated in CI/CD by a governance script that feeds reusable Terraform modules, paired with OIDC authentication and post-deployment Athena verification checks.
  • Why: Standardizes security and metadata tagging across all domains without forcing business domain teams to maintain repetitive low-level HCL code.

Scenario 2: Regulated Banking or Healthcare Environment with Strict Change Auditing

  • Context: A financial institution where every access grant to restricted columns requires auditable compliance evidence for external regulators.
  • Decision: Implement a strict GitOps pipeline with automated Policy as Code checks using Open Policy Agent (OPA / Conftest) evaluated directly against the JSON representation of terraform plan (terraform show -json tfplan), automatically rejecting any plan that attempts to drop tables, disable KMS encryption, or grant access to unapproved principals.
  • Why: Evaluating the computed Terraform plan prior to apply guarantees that no risky change reaches production while preserving an immutable approval trail in Git.

Scenario 3: When a Simpler Alternative Is Sufficient (Two Analytical Tables in a Small Team)

  • Context: A sports-facility booking startup has a single 3-person data team and only 2 external tables in Amazon Athena that change twice a year.
  • Decision: Maintain a single, straightforward main.tf file in Git using terraform fmt, terraform validate, terraform plan, and terraform apply, without building a custom YAML-to-HCL compiler or a hierarchy of internal platform modules.
  • Why: Building a YAML-to-Terraform abstraction layer carries development and maintenance overhead that only pays off when multiple products or autonomous teams repeatedly provision resources following the same pattern.

Incremental Adoption Strategy and Operational Metrics

To roll out Infrastructure as Code and DataOps without halting delivery, progress through three measurable stages:

  1. Stage 1 — Version Control and Eliminating Manual Console Changes (Weeks 1–3): Import existing S3, Glue, and Lake Formation resources into Terraform with locked remote state and OIDC authentication, ending manual console changes (ClickOps).
  2. Stage 2 — Reusable Modules and CI Validation (Weeks 4–6): Extract common resource patterns into a versioned module (data_product_catalog) and enforce automated contract checks and terraform plan on every Pull Request.
  3. Stage 3 — Declarative Self-Service and Continuous DataOps Verification (Weeks 7+): Enable domains to onboard new Data Products via product.yaml descriptors and run automated post-deployment quality assertions against published datasets.

Track four operational metrics to verify whether automation is genuinely improving the platform:

  • Data Product Provisioning Lead Time: Time from opening a Pull Request to having the catalog table and permissions live (reducing days of manual tickets to minutes).
  • Deployment Change Failure Rate: Percentage of infrastructure or schema deployments that cause downstream permission or query failures.
  • Configuration Drift Count: Number of out-of-band discrepancies detected by scheduled terraform plan runs between Git and AWS (target: 0).
  • Mean Time to Recovery (MTTR) when a defective schema or configuration change occurs.

Using AI Assistants to Design Terraform Modules and DataOps Pipelines

AI assistants can accelerate drafting HCL modules and writing policy tests against Terraform plans, provided a human engineer reviews the actual execution plan before applying changes.

Prompt 1: Generating a Reusable Terraform Module for AWS Data Products

Context: I am a Platform Engineer building the Self-Serve Data Platform for CommerceFlow on AWS using Terraform >= 1.6 and hashicorp/aws >= 5.0.
I need a reusable module named "data_product_catalog" that accepts as input variables: an existing Glue database name, table name, contract metadata map (domain, owner, version), published S3 location, column list, partition keys, and a set of consumer IAM role ARNs.

Task: Write variables.tf, main.tf, and outputs.tf to provision aws_glue_catalog_table (Parquet format, SNAPPY compression) and aws_lakeformation_permissions (SELECT and DESCRIBE) for each consumer role using for_each. Include variable validation {} blocks to reject S3 paths that do not start with "s3://" or that contain "*" wildcards.
  • What a human must verify: Ensure the for_each block on aws_lakeformation_permissions keys off stable strings (the role ARNs) rather than numeric list indices (which would cause unnecessary resource recreation whenever list order changes), and verify with terraform validate and terraform plan.

Prompt 2: Auditing a terraform plan for Destructive Replacements and Data Impact

Context: A domain team updated the configuration of its "confirmed-payments" Data Product in Git. Running "terraform plan" produced:
  # module.confirmed_payments.aws_glue_catalog_table.data_product_table must be replaced
  -/+ resource "aws_glue_catalog_table" "data_product_table" {
      ~ name = "confirmed_payments" -> "confirmed_payments_v2" # forces replacement
    }

Task: Analyze the production impact of applying this plan on:
1. Currently registered partitions in AWS Glue Data Catalog for that table.
2. Existing permission grants in AWS Lake Formation.
3. Downstream consumer queries in Amazon Athena referencing "payments_products.confirmed_payments".
Propose how to execute a parallel version migration (v1 and v2 side by side) without destroying the v1 table in production.
  • What a human must verify: Confirm with active consumers in the lineage graph that no v1 table is removed until the deprecation window agreed in the Data Contract has elapsed.

Practical Exercises

Exercise 1: Distinguishing IaC Success from DataOps Success

The Payments domain's CI/CD pipeline runs terraform init, terraform validate, terraform plan, and terraform apply with zero errors. The module creates payments_products.confirmed_payments pointing to s3://commerceflow-mesh-prod-111122223333/domains/payments/published/confirmed_payments/v1/ and grants Lake Formation SELECT permissions to the Finance role. However, when Finance runs its closing query in Amazon Athena, one query returns 0 rows and another partition fails with HIVE_BAD_DATA: Error parsing field value for field settled_amount.

Explain why terraform apply succeeded while the Data Product is broken, identify the technical cause of each of the two Athena failures, and specify which DataOps checks were missing from the publication pipeline.

Exercise 2: Analyzing the Impact of a Destructive Replacement in Terraform

Inside the Inventory domain, an engineer decides to rename the inventory_availability table to warehouse_inventory_availability by directly editing tableName inside domains/inventory/inventory-availability/product.yaml.

Explain what action terraform plan will display for aws_glue_catalog_table.data_product_table, what happens to the physical Parquet files in Amazon S3 versus the partition metadata in AWS Glue Data Catalog, and why this change violates Data Mesh contract evolution rules.

Exercise 3: Extending the Python Validator to Enforce Corporate Ownership and KMS Keys

Modify the validate_and_compile_descriptor function in the Python script to enforce two additional federated governance rules:

  1. metadata.ownerEmail must be present and end with @commerceflow.internal.
  2. If metadata.classification is "confidential" or "restricted", the storage block must include a kmsKeyArn field starting with "arn:aws:kms:" and containing no * wildcards.

Write the Python validation code and explain what operational risk each rule prevents before Terraform is invoked.


Solutions to the Exercises

Solution to Exercise 1

  • Why terraform apply succeeded: Terraform (IaC) only verifies that AWS API calls to register the Glue table definition and Lake Formation grants succeeded; Terraform does not inspect the Parquet files inside S3 or execute validation queries against the data.
  • Cause of the two Athena failures:
    1. 0 rows returned: The table is partitioned (PARTITIONED BY (payment_date DATE)), but after writing files to S3 no process registered the partitions in the catalog (ALTER TABLE ... ADD PARTITION or partition projection), or no files had been published yet.
    2. HIVE_BAD_DATA error: The physical Parquet file written to S3 serialized settled_amount with an incompatible physical type (for example, a STRING containing $ symbols) relative to the DECIMAL(12,2) type declared in the Glue table schema.
  • Missing DataOps steps: Physical Parquet schema validation against the contract before promoting files to published/, automated partition registration, and a post-deployment Athena smoke and data quality check inside the CI/CD pipeline.

Solution to Exercise 2

  • What terraform plan displays: On aws_glue_catalog_table, changing name forces resource replacement (# forces replacement), so the plan outputs -/+ destroy and then create replacement on the catalog table and recreates dependent aws_lakeformation_permissions resources.
  • What happens to S3 vs. Glue: Because it is an EXTERNAL_TABLE, destroying the Glue table does not delete the physical Parquet files in Amazon S3, but it does delete the previous catalog table along with all its registered partitions, leaving the new table empty until partitions are re-registered.
  • Why it violates contract evolution rules: Renaming a published table immediately breaks every downstream SQL query and pipeline referencing inventory_products.inventory_availability. Proper breaking-change evolution requires publishing the new table version alongside v1, keeping the original table active throughout the agreed deprecation period, and migrating consumers before retiring v1.

Solution to Exercise 3

We add the following checks inside validate_and_compile_descriptor:

    owner_email = meta.get("ownerEmail", "")
    if not isinstance(owner_email, str) or not owner_email.endswith("@commerceflow.internal"):
        raise ValueError(
            f"Governance violation: ownerEmail '{owner_email}' must belong to '@commerceflow.internal'."
        )

    kms_key_arn = storage.get("kmsKeyArn")
    if classification in {"confidential", "restricted"}:
        if not kms_key_arn or not str(kms_key_arn).startswith("arn:aws:kms:") or "*" in str(kms_key_arn):
            raise ValueError(
                f"Security violation: products classified as '{classification}' must specify "
                "a valid, non-wildcard kmsKeyArn inside the storage block."
            )
  • What Rule 1 (ownerEmail) prevents: Stops "orphaned" Data Products from being deployed without a verifiable owning team to receive quality alerts or access requests.
  • What Rule 2 (kmsKeyArn) prevents: Enforces Shift-Left Security by ensuring no domain can provision a confidential or restricted product without binding it to a dedicated customer-managed AWS KMS key before terraform plan even runs.

Key Takeaways and Decision Criteria

When automating a Data Mesh platform with Infrastructure as Code and DataOps, apply these core principles:

  • Separate the what from the how via platform modules: Let the platform team encapsulate low-level AWS complexity (Glue, S3, KMS, Lake Formation) inside versioned, pre-tested Terraform modules, while domain teams declare business properties and contracts for their Data Products.
  • Never confuse provisioned infrastructure with trustworthy data: terraform apply guarantees that buckets, catalog tables, and permissions exist reproducibly; DataOps adds contract tests, physical schema validation, and post-publication data checks against live records.
  • Harden the deployment plane: Always use encrypted remote state with concurrency locking, authenticate CI/CD pipelines via federated short-lived identities (OIDC) without static keys, and inspect terraform plan outputs to catch destructive replacements before touching production.

Loading conversation…

Keep learning