Skip to content
Snippets Groups Projects

Test work

Merged Daniel Scholl (MS] requested to merge test-work into master
Files
19
---
description: This rule defines how osdu rules are created.
globs:
---
# Terraform Module Development Guidelines
This document outlines the standards and patterns for developing Terraform modules in our infrastructure codebase.
## Module Structure
```
module-name/
├── README.md # Module documentation
├── main.tf # Main module configuration
├── variables.tf # Input variable definitions
├── outputs.tf # Output definitions
├── test.sh # Test execution script
├── testing/ # Basic test configuration
│ ├── main.tf # Test implementation
│ └── unit_test.go # Basic unit tests
└── tests/ # Extended test suite
├── .env.testing.template # Environment variables template
├── tf_options.go # Common test configuration
├── unit/ # Extended unit tests
│ └── *_test.go
└── integration/ # Integration tests
└── *_test.go
```
## Code Organization
### 1. Main Configuration (main.tf)
- Start with required provider configuration
- Include copyright header
- Group resources logically
- Use data sources for existing resources
- Implement resource configurations
- Use dynamic blocks for optional features
```hcl
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "=3.90.0" # Pin to specific version
}
}
}
provider "azurerm" {
features {}
}
data "azurerm_resource_group" "main" {
name = var.resource_group_name
}
resource "azurerm_example" "main" {
name = var.name
resource_group_name = data.azurerm_resource_group.main.name
location = data.azurerm_resource_group.main.location
dynamic "optional_block" {
for_each = var.optional_feature_enabled ? [1] : []
content {
// Configuration
}
}
}
```
### 2. Variables (variables.tf)
- Group variables by purpose
- Include clear descriptions
- Provide type constraints
- Set defaults where appropriate
- Mark sensitive variables
```hcl
variable "name" {
description = "The name of the resource"
type = string
}
variable "resource_tags" {
description = "Map of tags to apply to resources"
type = map(string)
default = {}
}
```
### 3. Outputs (outputs.tf)
- Include essential resource information
- Mark sensitive outputs
- Group related outputs
- Use maps for collections
- Include resource IDs and names
```hcl
output "id" {
description = "The ID of the created resource"
value = azurerm_example.main.id
}
output "properties" {
description = "Properties of the deployed resource"
value = {
id = azurerm_example.main.id
name = azurerm_example.main.name
}
sensitive = true
}
```
## Testing Framework
### 1. Common Test Functions Library (test-functions.sh)
The common test functions library provides essential functionality for all module tests. Key functions include:
Note: The `test-functions.sh` script should be sourced into test scripts using the relative path `../test-functions.sh`.
```
### 2. Test Script Implementation (test.sh)
Each module must implement these required components:
1. **Required Variables**
```bash
COMMON_LIB="../test-functions.sh" # Path to common functions
SCRIPT_DIR # Current script directory
RESOURCE_GROUP_PREFIX # Prefix for resource group names
DEFAULT_LOCATION # Default Azure region
RESOURCE_NAME # Module-specific resource name
```
2. **Required Functions**
```bash
setup_configuration() {
# Must implement:
# 1. Call setup_base_configuration
# 2. Generate resource names if needed
# 3. Export variables for Go tests
}
create_tfvars_files() {
# Must implement:
# 1. Define tfvars content
# 2. Call create_base_tfvars_files
}
validate_variables() {
# Should implement:
# 1. Call validate_base_variables
# 2. Validate module-specific variables
}
print_help() {
# Should implement:
# 1. Call print_common_help
# 2. Add module-specific help info
}
```
3. **Standard Error Handling**
```bash
# Required error handling patterns
set -e # Exit on any error
trap 'cleanup' EXIT # Ensure cleanup on exit
validate_azure_credentials # Check Azure authentication
# Error checking examples
if [ ! -f "$COMMON_LIB" ]; then
echo "Error: Common library not found"
exit 1
fi
if [ -z "$REQUIRED_VAR" ]; then
log "Error: Required variable not set" 1
exit 1
fi
```
### 3. Testing Directory Structure
Explanation of required test files and their purposes:
```
module-name/
├── testing/ # Basic test configuration
│ ├── main.tf # Basic test implementation
│ │ # Required sections:
│ │ # - Provider configuration
│ │ # - Resource group module
│ │ # - Module under test
│ │ # - Required variables
│ │
│ └── unit_test.go # Basic unit tests
│ # Required tests:
│ # - Resource count validation
│ # - Basic attribute validation
│ # - Required tag validation
└── tests/ # Extended test suite
├── tf_options.go # Test configuration
│ # Required configuration:
│ # - TF_VAR environment variables
│ # - Terraform options
│ # - Test fixtures
├── unit/ # Extended unit tests
│ └── *_test.go # Specific resource tests
│ # Should include:
│ # - Detailed attribute validation
│ # - Configuration variants
│ # - Error cases
└── integration/ # Integration tests
└── *_test.go # Live resource tests
# Should include:
# - Resource creation verification
# - Resource update testing
# - Resource deletion testing
```
### 4. Common Test Patterns
1. **Resource Name Generation**
```bash
# Standard pattern for resource names
generate_unique_name() {
local prefix="$1"
local resource_type="$2"
echo "${prefix}${resource_type}${RANDOM}"
}
# Usage example
STORAGE_ACCOUNT_NAME=$(generate_unique_name "" "sa")
LOG_ANALYTICS_NAME=$(generate_unique_name "" "logs")
```
2. **Variable Validation**
```bash
validate_variables() {
validate_base_variables
# Resource name validation
if [[ ! "$RESOURCE_NAME" =~ ^[a-z0-9]+$ ]]; then
log "Error: Resource name must be lowercase alphanumeric" 1
exit 1
fi
# Location validation
if [[ ! "$LOCATION" =~ ^[a-z]+[a-z0-9]+$ ]]; then
log "Error: Invalid location format" 1
exit 1
fi
}
```
3. **Terraform Variable File Creation**
```bash
create_tfvars_files() {
# Standard format for tfvars content
local tfvars_content="
name = \"$RESOURCE_NAME\"
resource_group_name = \"$RESOURCE_GROUP_NAME\"
location = \"$LOCATION\"
# Optional configurations
tags = {
environment = \"testing\"
module = \"example\"
}
# Resource-specific configurations
specific_setting = \"value\"
"
create_base_tfvars_files "$tfvars_content"
}
```
## Documentation
### 1. README.md
- Module description
- Usage examples
- Input variables table
- Output variables table
- License information
### 2. Code Comments
- Include copyright header
- Document non-obvious logic
- Explain variable purposes
- Detail resource configurations
## Best Practices
1. **Resource Naming**
- Use consistent resource names
- Prefix resources appropriately
- Follow Azure naming conventions
2. **Security**
- Enable HTTPS by default
- Use latest TLS versions
- Implement proper access controls
- Mark sensitive outputs
3. **Resource Management**
- Implement proper cleanup
- Use resource locks where needed
- Handle dependencies correctly
4. **Testing**
- Implement both unit and integration tests
- Use meaningful test names
- Clean up test resources
- Validate all configurations
## Continuous Integration
1. **Pre-commit Checks**
- Run terraform fmt
- Validate configurations
- Check for sensitive data
2. **Automated Testing**
- Execute unit tests
- Run integration tests
- Verify outputs
3. **Documentation Updates**
- Keep README current
- Update examples
- Document changes
## License and Copyright
All terraform and go files must include the Apache 2.0 license header:
```hcl
// Copyright © Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
```
\ No newline at end of file
Loading