Hybrid cloud architectures are no longer just a theoretical concept; they are the backbone of modern enterprise resilience. However, connecting a private Virtual Private Cloud (VPC) on Amazon Web Services (AWS) with one on Microsoft Azure via Direct Connect or ExpressRoute introduces significant security complexities. A common challenge for IT students and junior engineers is writing a Terraform module that automates this connection while enforcing strict security boundaries. This article provides a concrete, safe-to-run lab scenario demonstrating how to secure VPC peering logic across these disparate platforms using Infrastructure as Code (IaC).
The Architecture and Security Model
Before writing any code, it is crucial to understand the fundamental asymmetry between AWS and Azure networking. In a hybrid environment, you are not simply “peering” two identical clouds; you are bridging different security models. AWS relies heavily on Network Access Control Lists (NACLs) and Security Groups, while Azure utilizes Network Security Groups (NSGs).
In this lab scenario, we assume a standard Direct Connect connection exists between an AWS Region (e.g., us-east-1) and an Azure VNet in the same region. The goal is to allow traffic from an on-premise gateway or an Azure subnet to reach a specific AWS application subnet.
Key Security Assumptions:
* Zero Trust Approach: By default, deny all traffic. Only open ports required for business logic (e.g., HTTPS 443).
* Least Privilege IAM: Terraform execution roles must have minimal permissions to read/write only the specific resources being provisioned.
* State Security: The Terraform state file (terraform.tfstate) must be encrypted and stored in a secure S3 bucket with versioning enabled, separate from the production infrastructure.
Step 1: Project Initialization and State Management
The first step in any secure IaC workflow is establishing a clean repository structure and initializing the state backend. Never store state files locally without encryption.
# Initialize the Terraform project directory
mkdir hybrid-vpc-lab
cd hybrid-vpc-lab
# Initialize Terraform to download provider plugins
terraform init -backend="s3" \
-backend-config="bucket=secure-hybrid-state-bucket" \
-backend-config="key=prod/us-east-1/vpc-peering/state.tfstate" \
-backend-config="region=us-east-1" \
-backend-config="encrypt=true" \
-backend-config="dynamodb_table=terraform-locks-hybrid"
What this does: This command sets up a remote backend. The encrypt=true flag ensures that sensitive data within the state file is protected at rest. Using DynamoDB for locking prevents race conditions where multiple engineers might try to apply changes simultaneously, potentially corrupting the infrastructure.
Step 2: Defining Secure Resource Blocks (AWS Side)
On the AWS side, security is defined by Security Groups and Subnet configurations. A common mistake students make is creating aws_security_group rules that allow 0.0.0.0/0. In a hybrid scenario, you must restrict the CIDR block to the specific Azure IP range or the Direct Connect private interface IP.
# aws/main.tf - AWS Side Configuration
resource "aws_subnet" "app_subnet" {
vpc_id = var.vpc_id
cidr_block = var.app_cidr
availability_zone = var.availability_zone
# Security: Assign a custom tag for cost and ownership tracking
tags = {
Name = "hybrid-app-subnet"
Environment = "Production"
ManagedBy = "Terraform"
}
}
resource "aws_security_group" "app_sg" {
name = "hybrid-app-sg"
description = "Secure ingress for hybrid traffic from Azure only"
vpc_id = var.vpc_id
# Secure Rule: Allow HTTPS from specific Azure Direct Connect IP range
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [var.azure_dx_ip_range]
description = "Allow hybrid peering traffic"
}
# Default deny all other inbound traffic is implicit in AWS SGs unless specified otherwise
}
Verification Step: After applying this block, run terraform plan. Check the output to ensure no 0.0.0.0/0 CIDR blocks appear in the ingress rules. If you see them, review your variable file (variables.tf).
Step 3: Azure Networking and NSG Configuration
The Azure side mirrors this logic using Network Security Groups (NSGs). Unlike AWS, Azure NSGs are applied directly to subnets or NICs. The configuration must reference the Azure resource group and subnet IDs.
# azure/main.tf - Azure Side Configuration
resource "azurerm_subnet" "app_subnet" {
name = "hybrid-app-subnet"
resource_group_name = var.resource_group_name
virtual_network_name = var.virtual_network_name
address_prefixes = [var.app_cidr]
service_endpoints = ["Microsoft.Storage", "Microsoft.SQL"]
}
resource "azurerm_network_security_group" "app_nsg" {
name = "hybrid-app-nsg"
location = var.location
resource_group_name = var.resource_group_name
security_rule {
name = "AllowHybridPeering"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "443"
source_address_prefixes = [var.azure_dx_ip_range] # Must match AWS side logic
destination_address_prefix = "10.0.0.0/8" # Example private range
}
security_rule {
name = "DenyAllElse"
priority = 200
direction = "Inbound"
access = "Deny"
protocol = "*"
source_port_range = "*"
destination_port_range = "*"
source_address_prefixes = ["*"]
destination_address_prefix = ["*"]
}
}
Common Error: A frequent error in Azure labs is forgetting to assign the NSG to the subnet. Ensure you have a corresponding azurerm_subnet_network_security_group_association resource linking the NSG created above to the subnet defined here. Without this association, the rules exist but do not enforce security.
Step 4: Cost Controls and Monitoring Integration
Security is often free until it isn’t; unmonitored hybrid connections can lead to unexpected costs if misconfigured routes allow data exfiltration or DDoS attacks. We must integrate monitoring and cost tags.
# Both AWS and Azure resources should include cost allocation tags
# Example for AWS
tags = {
CostCenter = "CloudOps"
Project = "HybridConnectivity"
}
# Enable CloudWatch Logs for Security Group flow logs
resource "aws_flow_log" "main" {
vpc_id = var.vpc_id
traffic_type = "ALL"
log_group_name = "/aws/vpc/flow-logs/hybrid"
cloudwatch_logs_role_arn = aws_iam_role.flowlogs_assume.arn
# Security: Only export logs for the specific subnet
subnet_ids = [aws_subnet.app_subnet.id]
}
Practical Application: In a real workplace, you would set up an AWS CloudWatch Alarm triggered by high data transfer volumes on these specific flow logs. If traffic spikes unexpectedly outside business hours, the alarm triggers a notification to the security team. This turns passive monitoring into active threat detection.
Step 5: Verification and Troubleshooting
Once the Terraform apply is complete, verification is critical. Do not assume success based solely on terraform apply output.
- Check Connectivity: From an instance inside the Azure subnet, attempt to ping or curl the AWS target IP.
- Review Logs: Check the CloudWatch log group created in Step 4. Look for “ALLOWED” entries matching your test traffic.
- Validate NSG Flow: In the Azure Portal, navigate to the NSG and view the “Flow logs”. Ensure there are no “Deny” rules hitting your legitimate traffic.
Common Mistake & Fix: If connectivity fails, check the Direct Connect BGP session status. If the BGP session is down, the IP ranges advertised during peering will not be reachable, regardless of Security Group settings. Verify the BGP neighbor configuration in both AWS and Azure manifests.
Student Practice Task: The “Break Your Own Build” Exercise
To solidify these concepts, IT students should attempt a controlled breakage exercise in their local lab environments (using awslocal or similar sandbox tools if cloud credits are unavailable):
- Create the Terraform modules as described above.
- Intentionally modify the
aws_security_groupto allow0.0.0.0/0on port 443. - Run
terraform apply. - Challenge: Immediately revert the change using
terraform state listand a precise plan execution, ensuring no data loss occurred during the rollback. - Reflection: Document how long it took to secure the breach compared to manual console fixes. This highlights the value of IaC for rapid remediation.
Conclusion
Securing VPC peering between AWS and Azure requires a disciplined approach that treats the hybrid boundary as a high-security perimeter. By leveraging Terraform to enforce least-privilege CIDR blocks, implementing strict NSG rules in Azure, and integrating flow logs for continuous monitoring, organizations can build resilient hybrid networks. Remember that while this guide provides a robust template, specific policy terms, availability, and legal compliance depend on your organization’s insurance policies, jurisdictional laws, and the specific cloud provider’s current documentation. Always verify the latest pricing and feature sets directly with AWS or Azure before deploying to production.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

