Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions plugin/skills/azure-iac-generator/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
name: azure-iac-generator
description: "Generate deployment-ready Bicep templates from existing Azure environments or Draw.io architecture diagrams. Reverse-engineer live infrastructure into Infrastructure as Code. WHEN: generate bicep, azure to bicep, generate bicep from azure, bicep from diagram, diagram to bicep, create bicep templates from resources, export infrastructure as code, generate infrastructure code, reverse engineer azure, generate iac from azure. DO NOT USE FOR: creating new applications, deploying existing resources, comparing environments."
license: MIT
metadata:
author: Microsoft
version: "1.0.0"
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'll need to update this to "0.0.0-placeholder" and create a version.json file with the initial major.minor version. After that, versions numbers are updated automatically.

See other skills for examples.

---
Comment thread
Ba4bes marked this conversation as resolved.

# Azure IaC Generator

Reverse-engineer live Azure resources or Draw.io diagrams into deployment-ready, modular Bicep. The goal is an **environment-identical** redeployment for supported configurations. When Azure uses an end-of-life runtime, preserve the extracted value in comments and default to the current supported upgrade path.

## Prerequisites

- Azure MCP and Bicep MCP servers available
- For diagram source: a `.drawio` file in the workspace
- For live Azure / `azure-to-bicep`: an authenticated Azure CLI session (`az login`) with access to the target subscription and resource group

## When to Use This Skill

- Generate Bicep from existing Azure resources or resource groups
- Reverse-engineer live infrastructure into Infrastructure as Code
- Convert Draw.io architecture diagrams to Bicep templates
- Export Azure infrastructure as code

## Quick Reference

| Property | Value |
|---|---|
| **MCP tools** | Azure MCP (`group_resource_list`, `appservice`, `compute`, `storage`, `keyvault`), Bicep MCP (`get_bicep_best_practices`, `get_az_resource_type_schema`) |
| **CLI fallback** | `az resource show --ids <id>`, `az webapp show`, `az webapp config appsettings list` |
| **Output** | Project folder with `main.bicep`, `.bicepparam`, `modules/`, `dependencies/`, `README.md` |

## Design Notes

Named `azure-iac-generator` rather than `azure-bicep-generator` to leave room for future expansion to additional Infrastructure as Code targets. Bicep is the only supported target today.

## Routing — MUST follow the matched workflow

```
User request
├── Live Azure ("resource group", "subscription", "reverse engineer")
│ └─► FOLLOW [azure-to-bicep-workflow.md](references/azure-to-bicep-workflow.md) — ALL steps are HARD GATES
└── Draw.io diagram ("from diagram", ".drawio")
└─► FOLLOW [diagram-to-bicep-workflow.md](references/diagram-to-bicep-workflow.md)
```

## Mandatory References — MUST read before generating any Bicep

- [bicep-best-practices.md](references/bicep-best-practices.md) — Generation rules
- [azure-resource-configs.md](references/azure-resource-configs.md) — Per-type property extraction
- [azure-deployment-verification.md](references/azure-deployment-verification.md) — Pre-deployment checks
- [version-currency.md](references/version-currency.md) — API + runtime version rules
- [bicep-parsing.md](references/procedures/bicep-parsing.md) — Parse existing Bicep and `.bicepparam` files when merging with generated output

## Output Structure — MUST create this folder layout

```
<scope-name>/
├── README.md # Original request, resource summary, verification, deploy commands
├── main.bicep # Orchestrator — module refs only, no inline resources
├── main.bicepparam # All param values with comments (alternatives, EOL dates)
├── modules/ # One file per resource category (only if resources exist)
│ ├── networking.bicep # VNets, subnets, NSGs, private endpoints
│ ├── compute.bicep # VMs, App Services, Functions, Container Apps
│ ├── data.bicep # SQL, Cosmos DB, Storage, Redis, Key Vault
│ ├── identity.bicep # Managed identities, role assignments
│ └── monitoring.bicep # App Insights, Log Analytics
└── dependencies/ # Out-of-scope external dependencies (if any)
└── README.md # What each dependency needs and who owns it
```

> ⚠️ **NEVER generate a single flat `main.bicep` with all resources inline.** Resources MUST be in `modules/`.

## Error Handling

| Error | Remediation |
|---|---|
| Not authenticated | Run `az login` — see [azure-authentication.md](references/procedures/azure-authentication.md) |
| Resource type unsupported | Placeholder with `// TODO:` and resource ID |
| Secrets detected | `@secure()` param + `readEnvironmentVariable()` in `.bicepparam` |
| API version missing | Latest stable from Bicep MCP or Microsoft docs |
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Auto-Detection Rules

Settings automatically applied based on diagram topology during Bicep generation.

| Condition | Auto-Setting |
|-----------|-------------|
| Resource has a Private Endpoint connection | Set `publicNetworkAccess: 'Disabled'` on target resource |
| App Service connected to a Subnet | Set `vnetIntegrationSubnet` to the subnet reference |
| Private Endpoint connected to SQL Server | Set `groupIds: ['sqlServer']` |
| Private Endpoint connected to Storage Account | Set `groupIds: ['blob']` |
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storage accounts support multiple private endpoint group IDs: blob, file, queue, table, web, dfs. Hardcoding ['blob'] here means any PE targeting file shares, queues, or tables will get incorrect Bicep. Consider making this conditional on the connection target, or at minimum document this as a blob-only default.

| Private Endpoint connected to App Service | Set `groupIds: ['sites']` |
| Private Endpoint connected to Key Vault | Set `groupIds: ['vault']` |
| Private Endpoint connected to Cosmos DB | Set `groupIds: ['Sql']` |
| Private Endpoint exists in a subnet | Set `privateEndpointNetworkPolicies: 'Disabled'` on that subnet |
| VM exists without NIC in diagram | Auto-add NIC resource |
| App Service exists without App Service Plan | Auto-add App Service Plan |
| Subnet index N | Derive `addressPrefix` from the VNet `addressSpace` when present; otherwise require or prompt for a base CIDR before auto-assigning a non-overlapping subnet |

Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# Azure Deployment Verification Rules

Shared pre-deployment verification rules for generated Bicep templates. These cover **gotcha-prone constraints** that are easy to miss — SKU dependencies, resource compatibility, and networking rules that cause deployment failures.

For rules not listed here (security defaults like TLS 1.2, HTTPS enforcement, runtime version currency), verify against Bicep MCP `get_az_resource_type_schema`, [bicep-best-practices.md](bicep-best-practices.md), and Microsoft documentation.

Any skill that generates or modifies Bicep for deployment MUST run these checks before presenting results. Failures block deployment; warnings are reported but don't block.

---

## How to Use

1. After generating or modifying Bicep files, run every applicable rule category below against the generated code and the `.bicepparam` values.
2. Present results as a checklist (see "Output Format" at the end).
3. **Errors** must be fixed automatically. If automatic fixing is not possible, notify the user and present the issue with a concrete recommended fix. Do not present generated code that has known unfixed errors.
4. **Warnings** are informational — present them so the user can decide.

---

## 1. SKU Dependency Rules

Certain SKUs require companion resources or specific configurations. Missing these causes deployment failures.

### 1.1 Application Gateway WAF_v2 requires WAF Policy
- **Applies to**: `Microsoft.Network/applicationGateways` with `sku.tier == 'WAF_v2'`
- **Rule**: A `Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies` resource MUST exist and be referenced via the `firewallPolicy.id` property on the Application Gateway.
- **Fix**: Create a WAF policy resource with OWASP 3.2 managed rules in Prevention mode and link it to the gateway.
- **Severity**: Error

### 1.2 Application Gateway v2 requires Standard Public IP
- **Applies to**: `Microsoft.Network/applicationGateways` with `sku.tier` ending in `_v2`
- **Rule**: The associated `Microsoft.Network/publicIPAddresses` MUST use `sku.name = 'Standard'` and `allocationMethod = 'Static'`.
- **Fix**: Set Public IP SKU to Standard and allocation to Static.
- **Severity**: Error

### 1.3 App Service VNet Integration requires Standard+ SKU
- **Applies to**: `Microsoft.Web/sites` with VNet integration configured
- **Rule**: The associated `Microsoft.Web/serverfarms` MUST use SKU `S1` or higher. `F1` and `B1` do not support VNet integration.
- **Fix**: Upgrade App Service Plan SKU to at least `S1`.
- **Severity**: Error

### 1.4 Private Endpoint requires Standard+ resources
- **Applies to**: `Microsoft.Network/privateEndpoints` connected to Storage, SQL, Key Vault, etc.
- **Rule**: The target resource must support private endpoints at its current SKU tier (e.g., Key Vault Standard, Storage all SKUs, SQL all SKUs, Redis Premium only, Service Bus Premium only).
- **Fix**: Upgrade the target resource SKU to one that supports private endpoints.
- **Severity**: Error

### 1.5 AKS network policy requires compatible plugin
- **Applies to**: `Microsoft.ContainerService/managedClusters` with `networkPolicy` set
- **Rule**: If `networkPolicy = 'azure'`, then `networkPlugin` must be `'azure'`. If `networkPolicy = 'calico'`, `networkPlugin` can be `'azure'` or `'kubenet'`.
- **Fix**: Align network policy and plugin settings.
- **Severity**: Error

### 1.6 Azure Firewall requires dedicated subnet
- **Applies to**: `Microsoft.Network/azureFirewalls`
- **Rule**: The firewall MUST be placed in a subnet named exactly `AzureFirewallSubnet` with a minimum size of `/26`.
- **Fix**: Add or rename subnet to `AzureFirewallSubnet` with at least `/26` prefix.
- **Severity**: Error

### 1.7 Bastion requires dedicated subnet
- **Applies to**: `Microsoft.Network/bastionHosts`
- **Rule**: The bastion MUST be placed in a subnet named exactly `AzureBastionSubnet` with a minimum size of `/26`.
- **Fix**: Add or rename subnet to `AzureBastionSubnet` with at least `/26` prefix.
- **Severity**: Error

---

## 2. Resource Compatibility Rules

Resources that reference each other must be compatible in configuration.

### 2.1 Backend protocol must match target
- **Applies to**: `Microsoft.Network/applicationGateways` backend HTTP settings
- **Rule**: If the backend is an App Service, `backendHttpSettings.protocol` should be `Https` and `pickHostNameFromBackendAddress` should be `true`.
- **Severity**: Warning

### 2.2 VM NIC must exist in same subnet
- **Applies to**: `Microsoft.Compute/virtualMachines`
- **Rule**: Every VM must have at least one `Microsoft.Network/networkInterfaces` in the template, attached to a subnet in the same VNet.
- **Fix**: Generate a NIC resource if missing.
- **Severity**: Error

### 2.3 Private DNS zone must match service
- **Applies to**: `Microsoft.Network/privateEndpoints` with DNS zone groups
- **Rule**: The private DNS zone name must match the expected zone for the service type:
- SQL Server → `privatelink.database.windows.net`
- Blob Storage → `privatelink.blob.core.windows.net`
- Key Vault → `privatelink.vaultcore.azure.net`
- App Service → `privatelink.azurewebsites.net`
- ACR → `privatelink.azurecr.io`
- Cosmos DB → `privatelink.documents.azure.com`
- **Fix**: Use the correct zone name for the target resource type.
- **Severity**: Error

### 2.4 Private DNS zone must link to VNet
- **Applies to**: `Microsoft.Network/privateDnsZones`
- **Rule**: A `Microsoft.Network/privateDnsZones/virtualNetworkLinks` resource MUST exist linking the DNS zone to the VNet containing the private endpoint.
- **Fix**: Add a VNet link resource.
- **Severity**: Error

---

## 3. Networking Rules

### 3.1 No subnet address overlap
- **Applies to**: All subnets within a VNet
- **Rule**: Subnet address prefixes MUST NOT overlap with each other or exceed the VNet address space.
- **Fix**: Recalculate subnet prefixes to avoid overlap.
- **Severity**: Error

### 3.2 Subnet sizing for delegations
- **Applies to**: Subnets with delegations
- **Rule**: Subnets delegated to `Microsoft.Web/serverFarms` (VNet integration) should be at least `/26` (64 addresses). App Gateway subnets should be at least `/24`.
- **Severity**: Warning

### 3.3 Application Gateway subnet must be dedicated
- **Applies to**: `Microsoft.Network/applicationGateways`
- **Rule**: The App Gateway subnet must not contain any other resources (except other App Gateways). No delegations allowed.
- **Fix**: Move other resources to a different subnet.
- **Severity**: Error

### 3.4 NSG cannot be applied to App Gateway subnet (v2)
- **Applies to**: `Microsoft.Network/applicationGateways` with v2 SKU
- **Rule**: NSGs on App Gateway v2 subnets require special rules (allow GatewayManager inbound, allow Azure Load Balancer, allow health probes on ports 65200-65535). If an NSG is attached, verify these rules exist.
- **Severity**: Warning

---

## Output Format

Present verification results after validation:

```
## Pre-Deployment Verification

✅ N checks passed
⚠️ N warnings
❌ N errors

### Errors (must fix before deployment)
- ❌ **Rule 1.1**: Application Gateway uses WAF_v2 SKU but no WAF policy is defined.
→ Fix: Added `waf-policy-appgw` resource with OWASP 3.2 rules linked to `appgw-web`.

### Warnings
- ⚠️ **Rule 2.1**: App Gateway backend uses HTTP — consider HTTPS with `pickHostNameFromBackendAddress: true`.
```

When errors are found and auto-fixed, re-run the affected checks to confirm the fix resolves the issue.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Azure Resource Configuration Reference

Per-resource-type property retrieval mapping for drift detection and Bicep generation. For per-resource defaults (SKUs, sizes, settings), derive from Bicep MCP `get_az_resource_type_schema`, Azure Verified Modules, or Microsoft documentation. Do not hardcode defaults — verify at generation time.

## SKU Extraction Rules (Global)

For all resource types with `skuName` / `skuTier` properties, extract from the top-level `sku` object:
- `sku.name` → `skuName`
- `sku.tier` → `skuTier`

**Composite property** — `Microsoft.Compute/virtualMachines` `osImage`: assembled from `storageProfile.imageReference` as `publisher:offer:sku:version`.

## Per-Resource Property Maps

Detailed ARM field paths are split by category. Load the relevant file on demand:

- **Compute & Containers**: [resource-configs-compute.md](resource-configs-compute.md) — VMs, VMSS, App Service, Functions, AKS, Container Apps, ACR
- **Networking**: [resource-configs-network.md](resource-configs-network.md) — VNet, Subnet, NSG, Load Balancer, App Gateway, Public IP, NIC, Private Endpoints, VNet Gateway, Firewall, Bastion, Private DNS
- **Data & Storage**: [resource-configs-data.md](resource-configs-data.md) — Storage Accounts, SQL Server/DB, Cosmos DB, Redis
- **Platform & Integration**: [resource-configs-platform.md](resource-configs-platform.md) — Key Vault, App Insights, Log Analytics, Service Bus, Event Hub, APIM

## Auto-Detection Rules

Topology-based settings applied automatically during generation: [auto-detection-rules.md](auto-detection-rules.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Azure Resource Metadata Model



## Schema

Each Azure environment is represented as a **resource model** — a JSON structure with the following shape:

```json
{
"resources": [
{
"id": "/subscriptions/<sub>/resourceGroups/<rg>/providers/<provider>/<type>/<name>",
"localId": "<optional-short-slug>",
"type": "<Azure-resource-type>",
"name": "<resource-name>",
"resourceGroup": "<resource-group-name>",
"location": "<azure-region>",
"properties": {},
"tags": {},
"relationships": [
{
"targetId": "/subscriptions/<sub>/resourceGroups/<rg>/providers/<provider>/<type>/<related-name>",
"type": "<relationship-type>"
}
]
}
]
}
```

## Field Definitions

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | Yes | **Canonical ARM resource ID** (for example, `/subscriptions/<sub>/resourceGroups/<rg>/providers/Microsoft.Compute/virtualMachines/vm-web-01`). This is the primary key for matching resources across workflows. |
| `localId` | string | No | Optional short slug for readability (for example, `vm-web-01`). Do not use as the canonical identifier. |
| `type` | string | Yes | Azure resource provider type (for example, `Microsoft.Compute/virtualMachines`). Must align with `id`. |
| `name` | string | Yes | Display name of the resource. |
| `resourceGroup` | string | No | Resource group the resource belongs to. |
| `location` | string | No | Azure region (e.g., `eastus`, `westeurope`). |
| `properties` | object | No | Resource-specific properties (SKU, tier, size, etc.). |
| `tags` | object | No | Azure resource tags as key-value pairs. |
| `relationships` | array | No | Connections to other resources in the model. |

## Relationship Types

| Type | Description | Example |
|------|-------------|---------|
| `contains` | Parent contains child resource | VNet contains Subnet |
| `connects` | Network or data flow connection | VM connects to Storage Account |
| `depends` | Deployment dependency | App Service depends on App Service Plan |
| `peers` | Bidirectional peering | VNet peers with VNet |
| `secures` | Security association | NSG secures Subnet |
| `routes` | Traffic routing | Load Balancer routes to VM |

## Usage by Workflow

- **Azure to Bicep workflow**: Builds a resource model from live Azure resources; generates Bicep from it.
- **Diagram to Bicep workflow**: Parses Draw.io XML into a resource model; enriches it with configuration manifest; generates Bicep.

## Common Azure Resource Types

| Resource Type | Short Name |
|---------------|------------|
| `Microsoft.Compute/virtualMachines` | VM |
| `Microsoft.Web/sites` | App Service |
| `Microsoft.Web/serverfarms` | App Service Plan |
| `Microsoft.Storage/storageAccounts` | Storage Account |
| `Microsoft.Sql/servers` | SQL Server |
| `Microsoft.Sql/servers/databases` | SQL Database |
| `Microsoft.Network/virtualNetworks` | VNet |
| `Microsoft.Network/virtualNetworks/subnets` | Subnet |
| `Microsoft.Network/networkSecurityGroups` | NSG |
| `Microsoft.Network/loadBalancers` | Load Balancer |
| `Microsoft.Network/applicationGateways` | App Gateway |
| `Microsoft.Network/publicIPAddresses` | Public IP |
| `Microsoft.Network/networkInterfaces` | NIC |
| `Microsoft.Network/privateDnsZones` | Private DNS Zone |
| `Microsoft.Network/privateEndpoints` | Private Endpoint |
| `Microsoft.Network/virtualNetworkGateways` | VPN Gateway |
| `Microsoft.KeyVault/vaults` | Key Vault |
| `Microsoft.ContainerRegistry/registries` | Container Registry |
| `Microsoft.ContainerService/managedClusters` | AKS |
| `Microsoft.App/containerApps` | Container App |
| `Microsoft.App/managedEnvironments` | Container App Environment |
| `Microsoft.DocumentDB/databaseAccounts` | Cosmos DB |
| `Microsoft.ServiceBus/namespaces` | Service Bus |
| `Microsoft.EventHub/namespaces` | Event Hub |
| `Microsoft.Cache/redis` | Redis Cache |
| `Microsoft.Insights/components` | Application Insights |
| `Microsoft.OperationalInsights/workspaces` | Log Analytics Workspace |
| `Microsoft.ApiManagement/service` | API Management |
| `Microsoft.SignalRService/signalR` | SignalR |
| `Microsoft.CognitiveServices/accounts` | Cognitive Services |
| `Microsoft.ManagedIdentity/userAssignedIdentities` | Managed Identity |
| `Microsoft.Authorization/roleAssignments` | Role Assignment |
| `Microsoft.Resources/resourceGroups` | Resource Group |
Loading