# Azure Well-Architected Framework Implementation Guide

## Overview

This guide provides step-by-step instructions for implementing the Well-Architected Framework recommendations for the DeFi Oracle Meta Mainnet infrastructure.

## Prerequisites

- Azure CLI installed and configured
- Terraform >= 1.0 installed
- Appropriate Azure permissions (Owner or Contributor + User Access Administrator)
- Understanding of Azure Management Groups and Subscriptions

## Phase 1: Management Groups and Subscriptions

### Step 1: Create Management Groups Hierarchy

```bash
# Login to Azure
az login

# Set subscription (replace with your subscription ID)
az account set --subscription <subscription-id>

# Create Management Groups
az account management-group create --name "Production" --display-name "Production"
az account management-group create --name "Non-Production" --display-name "Non-Production"
az account management-group create --name "SharedServices" --display-name "Shared Services"
az account management-group create --name "Sandbox" --display-name "Sandbox"

# Verify Management Groups
az account management-group list
```

### Step 2: Create Subscriptions

```bash
# Create Production Subscription
az account create --name "Production" --offer-id "MS-AZR-0017P"  # Pay-As-You-Go

# Create Development Subscription
az account create --name "Development" --offer-id "MS-AZR-0017P"

# Create Testing Subscription
az account create --name "Testing" --offer-id "MS-AZR-0017P"

# Create Shared Services Subscription
az account create --name "Shared Services" --offer-id "MS-AZR-0017P"

# List subscriptions
az account list --output table
```

### Step 3: Move Subscriptions to Management Groups

```bash
# Get subscription IDs
PROD_SUB_ID=$(az account show --subscription "Production" --query id -o tsv)
DEV_SUB_ID=$(az account show --subscription "Development" --query id -o tsv)
TEST_SUB_ID=$(az account show --subscription "Testing" --query id -o tsv)
SHARED_SUB_ID=$(az account show --subscription "Shared Services" --query id -o tsv)

# Move subscriptions to Management Groups
az account management-group subscription add --name "Production" --subscription $PROD_SUB_ID
az account management-group subscription add --name "Non-Production" --subscription $DEV_SUB_ID
az account management-group subscription add --name "Non-Production" --subscription $TEST_SUB_ID
az account management-group subscription add --name "SharedServices" --subscription $SHARED_SUB_ID
```

## Phase 2: Resource Groups Organization

### Step 1: Deploy Resource Groups Module

```bash
# Navigate to well-architected terraform directory
cd terraform/well-architected

# Initialize Terraform
terraform init

# Create terraform.tfvars
cat > terraform.tfvars <<EOF
environment    = "prod"
location       = "eastus"
project_name   = "defi-oracle-mainnet"
subscription_id = "<your-subscription-id>"
EOF

# Plan deployment
terraform plan -var-file=terraform.tfvars

# Apply deployment
terraform apply -var-file=terraform.tfvars
```

### Step 2: Verify Resource Groups

```bash
# List resource groups
az group list --query "[?contains(name, 'rg-prod-')].{Name:name, Location:location}" --output table
```

## Phase 3: Enhanced Key Vault

### Step 1: Update Key Vault Configuration

The enhanced Key Vault module is already included in the well-architected configuration. Update the variables:

```hcl
# terraform/well-architected/terraform.tfvars
module "keyvault_enhanced" {
  # ... existing configuration ...
  
  # Add subnet IDs for network restrictions
  allowed_subnet_ids = [
    "/subscriptions/<sub-id>/resourceGroups/rg-prod-network-001/providers/Microsoft.Network/virtualNetworks/vnet-prod-001/subnets/subnet-aks",
    "/subscriptions/<sub-id>/resourceGroups/rg-prod-network-001/providers/Microsoft.Network/virtualNetworks/vnet-prod-001/subnets/subnet-validators"
  ]
  
  # Add management IPs
  allowed_ip_ranges = [
    "1.2.3.4/32"  # Your management IP
  ]
  
  # Private endpoint configuration
  enable_private_endpoint = true
  private_endpoint_subnet_id = "/subscriptions/<sub-id>/resourceGroups/rg-prod-network-001/providers/Microsoft.Network/virtualNetworks/vnet-prod-001/subnets/subnet-private-endpoints"
}
```

### Step 2: Deploy Enhanced Key Vault

```bash
# Apply Terraform configuration
terraform apply -var-file=terraform.tfvars
```

### Step 3: Configure RBAC Roles

```bash
# Get Key Vault ID
KV_ID=$(terraform output -raw key_vault_id)

# Assign Key Vault Administrator role
az role assignment create \
  --role "Key Vault Administrator" \
  --assignee <your-object-id> \
  --scope $KV_ID

# Assign Key Vault Secrets User role to AKS managed identity
az role assignment create \
  --role "Key Vault Secrets User" \
  --assignee <aks-managed-identity-id> \
  --scope $KV_ID
```

## Phase 4: Budget and Cost Management

### Step 1: Deploy Budget Module

The budget module is already included in the well-architected configuration. Update the variables:

```hcl
# terraform/well-architected/terraform.tfvars
module "budget" {
  subscription_id = var.subscription_id
  budget_name     = "budget-prod-001"
  amount          = 10000  # $10,000 per month
  time_grain      = "Monthly"
  start_date      = "2024-01-01T00:00:00Z"
  end_date        = "2025-12-31T23:59:59Z"
  
  notification_thresholds = [50, 80, 100]
  contact_emails          = ["devops@example.com"]  # Update with your email
  contact_roles           = ["Owner", "Contributor"]
}
```

### Step 2: Apply Budget Configuration

```bash
# Apply Terraform configuration
terraform apply -var-file=terraform.tfvars
```

### Step 3: Verify Budget

```bash
# List budgets
az consumption budget list --subscription <subscription-id>
```

## Phase 5: Azure Policy

### Step 1: Create Policy Definitions

```bash
# Create policy definition for tagging
az policy definition create \
  --name "require-tag-environment" \
  --display-name "Require Environment Tag" \
  --description "Ensures all resources have an Environment tag" \
  --rules '{
    "if": {
      "not": {
        "field": "tags[Environment]",
        "exists": "true"
      }
    },
    "then": {
      "effect": "deny"
    }
  }'

# Create policy definition for resource group naming
az policy definition create \
  --name "enforce-resource-group-naming" \
  --display-name "Enforce Resource Group Naming Convention" \
  --description "Enforces naming convention for resource groups" \
  --rules '{
    "if": {
      "not": {
        "field": "name",
        "match": "rg-*-*-*"
      }
    },
    "then": {
      "effect": "deny"
    }
  }'
```

### Step 2: Assign Policies to Management Groups

```bash
# Assign tagging policy to Production Management Group
az policy assignment create \
  --name "require-tag-environment-prod" \
  --display-name "Require Environment Tag - Production" \
  --policy "require-tag-environment" \
  --scope "/providers/Microsoft.Management/managementGroups/Production"

# Assign naming policy to Production Management Group
az policy assignment create \
  --name "enforce-resource-group-naming-prod" \
  --display-name "Enforce Resource Group Naming - Production" \
  --policy "enforce-resource-group-naming" \
  --scope "/providers/Microsoft.Management/managementGroups/Production"
```

## Phase 6: Network Security

### Step 1: Create Private Endpoint Subnet

```bash
# Create subnet for private endpoints
az network vnet subnet create \
  --resource-group rg-prod-network-001 \
  --vnet-name vnet-prod-001 \
  --name subnet-private-endpoints \
  --address-prefix 10.0.6.0/24
```

### Step 2: Enable Private Endpoints

Private endpoints are already configured in the enhanced Key Vault module. Verify:

```bash
# List private endpoints
az network private-endpoint list --resource-group rg-prod-security-001
```

## Phase 7: Monitoring and Alerting

### Step 1: Create Log Analytics Workspace

```bash
# Create Log Analytics Workspace
az monitor log-analytics workspace create \
  --resource-group rg-prod-monitoring-001 \
  --workspace-name law-prod-001 \
  --location eastus
```

### Step 2: Configure Alerts

```bash
# Create action group
az monitor action-group create \
  --resource-group rg-prod-monitoring-001 \
  --name ag-prod-001 \
  --short-name prod-alerts \
  --email-receivers name=devops email=devops@example.com

# Create alert rule for Key Vault access
az monitor metrics alert create \
  --name "Key Vault Access Denied" \
  --resource-group rg-prod-monitoring-001 \
  --scopes <key-vault-resource-id> \
  --condition "count Requests > 0" \
  --window-size 5m \
  --evaluation-frequency 1m \
  --action-group ag-prod-001
```

## Phase 8: Backup and Disaster Recovery

### Step 1: Enable Key Vault Backup

```bash
# Create backup vault
az backup vault create \
  --resource-group rg-prod-storage-001 \
  --name backup-vault-prod-001 \
  --location eastus

# Enable backup for Key Vault
az backup protection enable-for-azurekeyvault \
  --resource-group rg-prod-storage-001 \
  --vault-name backup-vault-prod-001 \
  --key-vault-id <key-vault-resource-id>
```

### Step 2: Configure Backup Policy

```bash
# Create backup policy
az backup policy create \
  --resource-group rg-prod-storage-001 \
  --vault-name backup-vault-prod-001 \
  --name keyvault-backup-policy \
  --policy-type AzureKeyVault \
  --backup-management-type AzureKeyVault
```

## Verification Checklist

- [ ] Management Groups hierarchy created
- [ ] Subscriptions created and moved to Management Groups
- [ ] Resource Groups organized by purpose and lifecycle
- [ ] Enhanced Key Vault deployed with RBAC
- [ ] Private Endpoints configured for Key Vault
- [ ] Budget alerts configured
- [ ] Azure Policy assignments created
- [ ] Network security configured
- [ ] Monitoring and alerting configured
- [ ] Backup strategy implemented

## Next Steps

1. **Migrate Existing Resources**: Move existing resources to new resource groups
2. **Update Terraform Configuration**: Update main Terraform configuration to use new resource groups
3. **Test Disaster Recovery**: Test backup and restore procedures
4. **Monitor Costs**: Review cost reports and optimize spending
5. **Security Review**: Conduct security assessment and remediate issues

## References

- [Azure Well-Architected Framework](https://docs.microsoft.com/azure/architecture/framework/)
- [Management Groups](https://docs.microsoft.com/azure/governance/management-groups/)
- [Key Vault Best Practices](https://docs.microsoft.com/azure/key-vault/general/best-practices)
- [Azure Policy](https://docs.microsoft.com/azure/governance/policy/)
- [Cost Management](https://docs.microsoft.com/azure/cost-management-billing/)

