Skip to content

Latest commit

 

History

History
338 lines (263 loc) · 12.8 KB

File metadata and controls

338 lines (263 loc) · 12.8 KB

AI Agents Guidelines for OpenTofu Module Development

This document provides shared guidelines for AI agents working on OpenTofu modules to ensure consistency, clarity, and alignment with best practices.

Overview

When working on OpenTofu modules, AI agents should optimize modules, outputs, variables, and file structures according to the specifications outlined in this document. The goal is to maintain consistency across all OpenTofu configurations while following established best practices.

Key Principles

  1. Consistency: Maintain uniform naming conventions and structures across all modules
  2. Clarity: Ensure code is readable and well-documented
  3. Best Practices: Follow OpenTofu and Terraform community standards
  4. Retrocompatibility: Preserve backward compatibility when making changes

Shared Implementation Guidelines

1. Output Management

Replace module and resource output names consistently:

  • Use id instead of app_service_id
  • Use name instead of app_service_name

Add a global resource output for the main resource in every module:

output "resource" {
  value = [RESOURCE_TYPE].main
}

Ensure outputs are added for all resources and modules referred within each module:

output "module_service_plan" {
  value = module.service_plan
}
output "resource_application_insights" {
  value = azurerm_application_insights.main
}

2. Resource Naming

Rename the main resource of each module to "main" for consistent reference:

resource "azurerm_service_plan" "main" {}

Add the moved block for retrocompatibility:

moved {
  from = azurerm_service_plan.old_resource_name
  to   = azurerm_service_plan.main
}

3. Variable Standards

  • Update variable descriptions to include clear punctuation (add dots at the end of sentences)
  • Use Markdown links consistently within descriptions [text](http://example_url)
  • Update variable naming for clarity and consistency (e.g., change custom_diagnostic_settings_name to diagnostic_settings_custom_name)
  • Ensure lookup() includes a default value:
    lookup("parameter_name", var.parameter, "default_value")
  • Avoid using lookup for typed variables

4. File Organization Standards

Use standardized naming conventions for files:

  • Data sources: d-naming.tf for specific naming datasources and data-sources.tf for grouped datasources
  • Resources: For example, r-app-service.tf for specific resources like azurerm_app_service
  • Module calls: m-logs.tf for example for logs diagnostic settings module, m- prefix for others module calls
  • Split providers constrains into a dedicated providers.tf file
  • Split inputs in variables-xx.tf files and outputs in outputs-xx.tf files, where xx is a specific category (e.g., variables-logs.tf, outputs-resources.tf)

5. Documentation Requirements

  • Add a table for OpenTofu versions, including version 8.x.x
  • Include a warning about modules not being verified for Terraform versions >= 1.3
  • Add notes to indicate optimization for OpenTofu versions >= 1.8
  • Light rework of examples:
    • Provide examples in base.tf (used for initialization/validation/plan) but exclude detailed examples from README
  • Align README content with updated module names, outputs, and conventions
  • Use the terraform-docs tool for generating documentation and ensure it is up-to-date with the latest module structure and outputs

6. Control Flow Best Practices

Ensure IDs in keys are avoided; use fixed strings or clearly defined keys.

Use count for conditional/boolean operations:

resource "my_resource" {
  count = var.resource_enabled ? 1 : 0
  ...
}

Avoid the use of generated values (like resource's id) in count or for_each. Replace with an object-wrapping approach:

variable "resource" { type = object({ id = string }) }
resource "my_other_resource" {
  count = var.resource == null ? 1 : 0
  attr_id = var.resource.id
}

7. Version Management

  • Enforce Terraform version constraints >= 1.3 in versions.tf
  • Require OpenTofu >= 1.12 in CI/CD configurations
  • Update both .gitlab-ci.yml and providers.tf to reflect AzureRM provider version constraints

8. Miscellaneous Updates

  • Fork and use Claranet's "azurecaf naming" provider for naming conventions
  • Avoid "unknown values" comparison issues using non-null wrappers for input-generated values

Do not use:

variable "resource_id" {}
resource "my_other_resource" {
  count = var.resource_id == null ? 1 : 0
  ...
}

Instead, wrap into objects:

variable "resource" { type = object({ id = string }) }
resource "my_other_resource" {
  count = var.resource == null ? 1 : 0
  attr_id = var.resource.id
}

Example Transformation

Before (Input):

output "app_service_id" {
  value = azurerm_app_service.main.id
}

output "app_service_name" {
  value = azurerm_app_service.main.name
}

After (Transformed Output):

output "id" {
  value = azurerm_app_service.main.id
}

output "name" {
  value = azurerm_app_service.main.name
}

output "resource" {
  value = azurerm_app_service.main
}

output "module_service_plan" {
  value = module.service_plan
}

output "resource_application_insights" {
  value = azurerm_application_insights.main
}

Module Upgrade to v9

This file is designed to be read by OpenCode directly. From the OpenCode prompt, tell the agent:

Using @../../ci/{{cookiecutter.module_name}}/AGENTS.md guidelines, upgrade this module to v9

When upgrading a module to v9, apply the following changes in addition to the guidelines above:

0. Development Branch

1. OpenTofu Version

  • Set the OpenTofu version constraint to >= 1.12 in versions.tofu:
    terraform {
      required_version = ">= 1.12"
    }
  • Update the opentofu entry to 1.12.5 (or the latest patch satisfying >= 1.12) in both mise lockfiles: .tool-versions and mise.lock (if present in the module).

2. AzureRM Provider Version

  • Set the AzureRM provider version constraint to ~> 5.0 in providers.tf:
    terraform {
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 5.0"
        }
      }
    }

3. Examples Directory

  • Update every examples/*/versions.tf (and any other version-pinning file under examples/) to match the same required_version (OpenTofu >= 1.12) and AzureRM provider (~> 5.0) constraints applied to the module root in steps 1 and 2.
  • Check all examples for breaking changes too, not just the root module.

4. GitLab CI Template

  • During v9 development, point the .gitlab-ci.yml include ref to the v9/SREAA-368 branch instead of master:
    include:
      - project: "claranet/projects/cloud/azure/terraform/ci"
        ref: v9/SREAA-368
        file: "/pipeline.yml"
  • Revert the ref back to master (or the relevant release tag) once v9/SREAA-368 is merged and released.
  • Also update the .gitlab-ci.yml variables block so TF_MIN_VERSION and AZURERM_PROVIDER_MIN_VERSION match the new constraints from steps 1 and 2:
    variables:
      TF_MIN_VERSION: "1.12"
      AZURERM_PROVIDER_MIN_VERSION: "5.0"

5. .config Directory Sync

6. AzureRM 5.0 Code Migration

  • Before touching resource/data-source code, read the official upgrade guide: AzureRM Provider 5.0 Upgrade Guide.
  • Identify and apply every breaking change relevant to the resources used in the module (renamed/removed arguments, changed defaults, removed resources/data sources, behavior changes, etc.) as documented in the guide.
  • Re-run tflint and tofu validate/plan after migration to confirm the module is compatible with AzureRM ~> 5.0.

7. Regenerate README.md

  • After the .config sync (step 5), regenerate README.md with terraform-docs using the updated .config/terraform-docs.yml template, via the tofu_docs hook (prek/pre-commit):
    prek run tofu_docs --all-files
    # or: pre-commit run tofu_docs --all-files
  • Review the diff to ensure inputs/outputs/versions reflect the v9 changes (new variables, outputs, version constraints).

8. Commit and Open MR

  • Commit all v9 upgrade changes using Conventional Commits with the following structure:
    feat(SREAA-368): upgrade module to v9 (OpenTofu >= 1.12, AzureRM ~> 5.0)
    
    {description body}
    
    BREAKING CHANGES: {breaking description}
    
    • {description body}: summarize the changes applied (version bumps, examples updated, AzureRM 5.0 migration, README regeneration, etc.).
    • BREAKING CHANGES: {breaking description}: list every breaking change from the AzureRM 5.0 migration (step 6) and the raised minimum versions, so consumers know what to expect when upgrading.
  • Open a merge request from v9/SREAA-368 against master or main (default branch) using the glab CLI:
    glab mr create \
      --title "feat(SREAA-368): upgrade module to v9 (OpenTofu >= 1.12, AzureRM ~> 5.0)" \
      --description "{description body}" \
      --target-branch v9/SREAA-368
  • Ensure all pre-commit checks and CI pipelines pass before requesting review.

Git Contribution Guidelines

All AI agents must follow these git contribution standards when working on OpenTofu modules:

Branch Management

  • Create a new branch for each contribution
  • Use prefixed branch names based on the type of change:
    • feat/add_new_param - for new features or parameters
    • fix/change_attribute - for bug fixes or corrections
    • docs/update_readme - for documentation updates
    • refactor/rename_variables - for code refactoring
    • chore/update_dependencies - for maintenance tasks

Commit Standards

  • Follow conventional commits structure: type(scope): description
  • Optional unicode emojis are allowed for better readability
  • Examples:
    • feat(outputs): ✨ add global resource output
    • fix(variables): 🐛 correct lookup default value
    • docs(readme): 📝 update version compatibility table
    • refactor(resources): ♻️ rename main resource with moved block

Development Environment

  • Install and update tools using mise-en-place: mise install
  • Keep tools up-to-date before starting work
  • Verify tool versions match project requirements in .tool-versions

Code Quality Assurance

  • Install pre-commit hooks: pre-commit install
  • Pre-commit must trigger on each commit to ensure validity of changes
  • All pre-commit checks must pass before pushing changes
  • Address any pre-commit failures immediately

Review Process

  • Open a merge request when changes are ready for review
  • Provide clear description of changes and their impact
  • Reference related issues or requirements
  • Ensure all CI/CD checks pass before requesting review
  • Address review feedback promptly and thoroughly

AI Agent Responsibilities

When working on OpenTofu modules, AI agents should:

  1. Analyze existing code structure and identify areas for improvement
  2. Apply the standardized naming conventions and file structures
  3. Update outputs, variables, and documentation according to guidelines
  4. Validate configurations against best practices
  5. Ensure retrocompatibility through appropriate migration strategies
  6. Follow git contribution guidelines for all changes
  7. Document changes and maintain clear commit messages

Quality Assurance

  • Validate all examples and configurations against updated specifications
  • Ensure consistency across all documentation files
  • Test variable naming conventions and OpenTofu configurations
  • Verify that all changes maintain backward compatibility
  • Confirm all pre-commit checks pass
  • Ensure proper git workflow is followed

Notes for AI Agents

  • Focus on alignment with best practices for readability
  • Avoid introducing unnecessary complexity
  • Carefully validate examples against specifications
  • Maintain consistency across all files and configurations
  • Always include retrocompatibility measures when making breaking changes
  • Follow git contribution guidelines for proper version control