|
| 1 | +// -------------------------------------------------------------------------------------- |
| 2 | +// AI-Driven Cost Optimization for Stamps Pattern |
| 3 | +// - Implements intelligent cost tracking and optimization |
| 4 | +// - Provides predictive scaling recommendations |
| 5 | +// - Enables automated cost control measures |
| 6 | +// -------------------------------------------------------------------------------------- |
| 7 | + |
| 8 | +@description('Azure region for deployment') |
| 9 | +param location string = resourceGroup().location |
| 10 | + |
| 11 | +@description('Cost optimization name prefix') |
| 12 | +param costOptimizationPrefix string = 'stamps-cost-opt' |
| 13 | + |
| 14 | +@description('Environment name') |
| 15 | +@allowed(['dev', 'test', 'staging', 'prod']) |
| 16 | +param environment string = 'prod' |
| 17 | + |
| 18 | +@description('Tags for resources') |
| 19 | +param tags object = {} |
| 20 | + |
| 21 | +@description('Application Insights resource ID') |
| 22 | +param applicationInsightsId string |
| 23 | + |
| 24 | +@description('Log Analytics Workspace ID') |
| 25 | +param logAnalyticsWorkspaceId string |
| 26 | + |
| 27 | +@description('Storage Account ID for cost data') |
| 28 | +param storageAccountId string |
| 29 | + |
| 30 | +@description('Cost threshold for alerts (USD)') |
| 31 | +param costThreshold int = 1000 |
| 32 | + |
| 33 | +// ============ COST MANAGEMENT COMPONENTS ============ |
| 34 | + |
| 35 | +// Cost Anomaly Detection using Automation Account |
| 36 | +resource costOptimizationAutomation 'Microsoft.Automation/automationAccounts@2023-11-01' = { |
| 37 | + name: '${costOptimizationPrefix}-automation-${environment}' |
| 38 | + location: location |
| 39 | + tags: tags |
| 40 | + properties: { |
| 41 | + sku: { |
| 42 | + name: 'Basic' |
| 43 | + } |
| 44 | + encryption: { |
| 45 | + keySource: 'Microsoft.Automation' |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// Managed Identity for Cost Optimization |
| 51 | +resource costOptimizationIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = { |
| 52 | + name: '${costOptimizationPrefix}-identity-${environment}' |
| 53 | + location: location |
| 54 | + tags: tags |
| 55 | +} |
| 56 | + |
| 57 | +// ============ COST TRACKING AUTOMATION ============ |
| 58 | + |
| 59 | +// Cost Optimization Variables |
| 60 | +resource costThresholdVariable 'Microsoft.Automation/automationAccounts/variables@2020-01-13-preview' = { |
| 61 | + parent: costOptimizationAutomation |
| 62 | + name: 'CostThreshold' |
| 63 | + properties: { |
| 64 | + description: 'Monthly cost threshold for alerts' |
| 65 | + value: '"${costThreshold}"' |
| 66 | + isEncrypted: false |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +resource environmentVariable 'Microsoft.Automation/automationAccounts/variables@2020-01-13-preview' = { |
| 71 | + parent: costOptimizationAutomation |
| 72 | + name: 'Environment' |
| 73 | + properties: { |
| 74 | + description: 'Current environment name' |
| 75 | + value: '"${environment}"' |
| 76 | + isEncrypted: false |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +// ============ INTELLIGENT SCALING LOGIC ============ |
| 81 | + |
| 82 | +// Logic App for Predictive Scaling |
| 83 | +resource predictiveScalingLogicApp 'Microsoft.Logic/workflows@2019-05-01' = { |
| 84 | + name: '${costOptimizationPrefix}-predictive-scaling-${environment}' |
| 85 | + location: location |
| 86 | + tags: tags |
| 87 | + identity: { |
| 88 | + type: 'UserAssigned' |
| 89 | + userAssignedIdentities: { |
| 90 | + '${costOptimizationIdentity.id}': {} |
| 91 | + } |
| 92 | + } |
| 93 | + properties: { |
| 94 | + definition: { |
| 95 | + '$schema': 'https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#' |
| 96 | + contentVersion: '1.0.0.0' |
| 97 | + parameters: { |
| 98 | + applicationInsightsId: { |
| 99 | + type: 'string' |
| 100 | + defaultValue: applicationInsightsId |
| 101 | + } |
| 102 | + logAnalyticsWorkspaceId: { |
| 103 | + type: 'string' |
| 104 | + defaultValue: logAnalyticsWorkspaceId |
| 105 | + } |
| 106 | + } |
| 107 | + triggers: { |
| 108 | + recurrence: { |
| 109 | + type: 'Recurrence' |
| 110 | + recurrence: { |
| 111 | + frequency: 'Hour' |
| 112 | + interval: 1 |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + actions: { |
| 117 | + 'Get-Performance-Metrics': { |
| 118 | + type: 'Http' |
| 119 | + inputs: { |
| 120 | + method: 'POST' |
| 121 | + uri: 'https://api.applicationinsights.io/v1/apps/${last(split(applicationInsightsId, '/'))}/query' |
| 122 | + headers: { |
| 123 | + 'Content-Type': 'application/json' |
| 124 | + } |
| 125 | + body: { |
| 126 | + query: 'requests | where timestamp > ago(1h) | summarize RequestCount = count(), AvgDuration = avg(duration), ErrorRate = countif(success == false) * 100.0 / count() by cloud_RoleInstance' |
| 127 | + } |
| 128 | + authentication: { |
| 129 | + type: 'ManagedServiceIdentity' |
| 130 | + identity: costOptimizationIdentity.id |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + 'Analyze-Scaling-Requirements': { |
| 135 | + type: 'Compose' |
| 136 | + inputs: { |
| 137 | + scalingRecommendations: { |
| 138 | + scaleUp: '@greater(body(\'Get-Performance-Metrics\')?[\'tables\']?[0]?[\'rows\']?[0]?[1], 5000)' |
| 139 | + scaleDown: '@less(body(\'Get-Performance-Metrics\')?[\'tables\']?[0]?[\'rows\']?[0]?[1], 1000)' |
| 140 | + timestamp: '@utcNow()' |
| 141 | + } |
| 142 | + } |
| 143 | + runAfter: { |
| 144 | + 'Get-Performance-Metrics': ['Succeeded'] |
| 145 | + } |
| 146 | + } |
| 147 | + 'Send-Scaling-Recommendations': { |
| 148 | + type: 'Http' |
| 149 | + inputs: { |
| 150 | + method: 'POST' |
| 151 | + uri: 'https://${last(split(logAnalyticsWorkspaceId, '/'))}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01' |
| 152 | + headers: { |
| 153 | + 'Content-Type': 'application/json' |
| 154 | + 'Log-Type': 'ScalingRecommendations' |
| 155 | + } |
| 156 | + body: '@outputs(\'Analyze-Scaling-Requirements\')' |
| 157 | + authentication: { |
| 158 | + type: 'ManagedServiceIdentity' |
| 159 | + identity: costOptimizationIdentity.id |
| 160 | + } |
| 161 | + } |
| 162 | + runAfter: { |
| 163 | + 'Analyze-Scaling-Requirements': ['Succeeded'] |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +// ============ COST OPTIMIZATION WORKBOOK ============ |
| 172 | + |
| 173 | +resource costOptimizationWorkbook 'Microsoft.Insights/workbooks@2022-04-01' = { |
| 174 | + name: guid('cost-optimization-workbook', resourceGroup().id) |
| 175 | + location: location |
| 176 | + kind: 'shared' |
| 177 | + tags: tags |
| 178 | + properties: { |
| 179 | + displayName: 'Stamps Pattern: Cost Optimization Intelligence' |
| 180 | + serializedData: ''' |
| 181 | +{ |
| 182 | + "version": "Notebook/1.0", |
| 183 | + "items": [ |
| 184 | + { |
| 185 | + "type": 1, |
| 186 | + "content": { |
| 187 | + "json": "# 💰 Cost Optimization Intelligence\\n\\n**AI-driven insights for optimizing costs across the Stamps Pattern deployment.**" |
| 188 | + } |
| 189 | + }, |
| 190 | + { |
| 191 | + "type": 12, |
| 192 | + "content": { |
| 193 | + "version": "NotebookGroup/1.0", |
| 194 | + "groupType": "editable", |
| 195 | + "items": [ |
| 196 | + { |
| 197 | + "type": 3, |
| 198 | + "content": { |
| 199 | + "version": "KqlItem/1.0", |
| 200 | + "query": "customMetrics\\n| where name == \\"CostPerTenant\\"\\n| extend TenantId = tostring(customDimensions.TenantId)\\n| extend CellId = tostring(customDimensions.CellId)\\n| summarize AvgCost = avg(value), TotalCost = sum(value) by TenantId, CellId\\n| top 20 by TotalCost desc", |
| 201 | + "size": 0, |
| 202 | + "title": "💸 Cost by Tenant and CELL", |
| 203 | + "queryType": 0, |
| 204 | + "visualization": "table", |
| 205 | + "gridSettings": { |
| 206 | + "formatters": [ |
| 207 | + { |
| 208 | + "columnMatch": "TotalCost", |
| 209 | + "formatter": 1, |
| 210 | + "formatOptions": { |
| 211 | + "customColumnWidthSetting": "100px" |
| 212 | + } |
| 213 | + } |
| 214 | + ] |
| 215 | + } |
| 216 | + } |
| 217 | + }, |
| 218 | + { |
| 219 | + "type": 3, |
| 220 | + "content": { |
| 221 | + "version": "KqlItem/1.0", |
| 222 | + "query": "requests\\n| where timestamp > ago(7d)\\n| extend TenantId = tostring(customDimensions.TenantId)\\n| summarize RequestCount = count(), AvgDuration = avg(duration) by TenantId, bin(timestamp, 1d)\\n| render timechart", |
| 223 | + "size": 0, |
| 224 | + "title": "� Resource Utilization Trends", |
| 225 | + "queryType": 0, |
| 226 | + "visualization": "timechart" |
| 227 | + } |
| 228 | + } |
| 229 | + ] |
| 230 | + } |
| 231 | + }, |
| 232 | + { |
| 233 | + "type": 1, |
| 234 | + "content": { |
| 235 | + "json": "## 🎯 Cost Optimization Recommendations\\n\\n### Automated Insights:\\n- **Right-sizing**: Monitor CPU and memory utilization to identify over-provisioned resources\\n- **Predictive Scaling**: Use AI models to predict traffic patterns and scale proactively\\n- **Tenant Cost Allocation**: Track per-tenant costs for accurate billing and optimization\\n- **Idle Resource Detection**: Identify and decommission unused resources automatically\\n\\n### Key Metrics:\\n- **Cost per Request**: Track cost efficiency across tenants\\n- **Resource Utilization**: Monitor CPU, memory, and storage usage\\n- **Scaling Events**: Analyze auto-scaling patterns for optimization opportunities" |
| 236 | + } |
| 237 | + } |
| 238 | + ] |
| 239 | +} |
| 240 | +''' |
| 241 | + category: 'workbook' |
| 242 | + sourceId: logAnalyticsWorkspaceId |
| 243 | + } |
| 244 | +} |
| 245 | + |
| 246 | +// ============ STORAGE LIFECYCLE OPTIMIZATION ============ |
| 247 | + |
| 248 | +// Lifecycle Management Policy for Cost Optimization |
| 249 | +resource storageLifecyclePolicy 'Microsoft.Storage/storageAccounts/managementPolicies@2023-01-01' = { |
| 250 | + name: 'default' |
| 251 | + parent: storageAccount |
| 252 | + properties: { |
| 253 | + policy: { |
| 254 | + rules: [ |
| 255 | + { |
| 256 | + name: 'ArchiveOldLogs' |
| 257 | + enabled: true |
| 258 | + type: 'Lifecycle' |
| 259 | + definition: { |
| 260 | + filters: { |
| 261 | + blobTypes: ['blockBlob'] |
| 262 | + prefixMatch: ['logs/', 'diagnostics/'] |
| 263 | + } |
| 264 | + actions: { |
| 265 | + baseBlob: { |
| 266 | + tierToCool: { |
| 267 | + daysAfterModificationGreaterThan: 30 |
| 268 | + } |
| 269 | + tierToArchive: { |
| 270 | + daysAfterModificationGreaterThan: 90 |
| 271 | + } |
| 272 | + delete: { |
| 273 | + daysAfterModificationGreaterThan: 2555 // 7 years retention |
| 274 | + } |
| 275 | + } |
| 276 | + } |
| 277 | + } |
| 278 | + } |
| 279 | + { |
| 280 | + name: 'DeleteTempFiles' |
| 281 | + enabled: true |
| 282 | + type: 'Lifecycle' |
| 283 | + definition: { |
| 284 | + filters: { |
| 285 | + blobTypes: ['blockBlob'] |
| 286 | + prefixMatch: ['temp/', 'tmp/'] |
| 287 | + } |
| 288 | + actions: { |
| 289 | + baseBlob: { |
| 290 | + delete: { |
| 291 | + daysAfterModificationGreaterThan: 7 |
| 292 | + } |
| 293 | + } |
| 294 | + } |
| 295 | + } |
| 296 | + } |
| 297 | + ] |
| 298 | + } |
| 299 | + } |
| 300 | +} |
| 301 | + |
| 302 | +// Reference to existing storage account |
| 303 | +resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' existing = { |
| 304 | + name: last(split(storageAccountId, '/')) |
| 305 | +} |
| 306 | + |
| 307 | +// ============ OUTPUTS ============ |
| 308 | + |
| 309 | +output costOptimizationAutomationId string = costOptimizationAutomation.id |
| 310 | +output costOptimizationIdentityId string = costOptimizationIdentity.id |
| 311 | +output predictiveScalingLogicAppId string = predictiveScalingLogicApp.id |
| 312 | +output costOptimizationWorkbookId string = costOptimizationWorkbook.id |
| 313 | +output storageLifecyclePolicyId string = storageLifecyclePolicy.id |
0 commit comments