Skip to content

Blog

Using Enterprise Azure Policy as Code (EPAC)

In this blog post, we will show how to use Enterprise Azure Policy as Code (EPAC) to manage your Azure environment.

Use case

  • Determine desired state strategy.
  • We have some existing Azure Policies that we want to manage as code.
  • For simplicity, we will suppose that we have a unique Centralized Team that manages the policies.
  • We will use a Git repository to store the policies and the CI/CD process to deploy them.
  • We doesn't have any exclude resources in the environment.
  • How to handle Defender for Cloud Policy Assignments:
  • We will use Defender for Cloud to manage the Policy Assignments for Defender Plans when a plan is enabled.
  • EPAC will manage Defender for Cloud Security Policy Assignments at the management group level. This is the default behavior.
  • Design your CI/CD process:
  • We will use Release Flow

Management Groups for Enterprise Scale Landing Zone

This is the common structure for the Management Groups in the Enterprise Scale Landing Zone, now Accelerator Landing Zone:

Syntax error in textmermaid version 11.2.0

For this use case, we will use the Landing Zones Management Group for duplicate and old Management Group hierarchy (manage-azure-policy):

Syntax error in textmermaid version 11.2.0

Note

You could also use two different tenants for the different environments, but this is not the case for this use case.

You can create this Management Groups hierarcly using the Azure CLI with the following commands:

az account management-group create --name "MyManagementGroup"
az account management-group move --name "ChildGroup" --new-parent "NewParentGroup"

For the use case, we will use the following commands:

az account management-group create --name "epac-dev"
az account management-group create --name "dev-decommissioned" --parent "epac-dev"
az account management-group create --name "dev-landingzones" --parent "epac-dev"
az account management-group create --name "dev-platform" --parent "epac-dev"
az account management-group create --name "dev-sandbox" --parent "dev-landingzones"
az account management-group create --name "dev-corp" --parent "dev-landingzones"
az account management-group create --name "dev-online" --parent "dev-landingzones"
az account management-group create --name "dev-connectivity" --parent "dev-platform"
az account management-group create --name "dev-identity" --parent "dev-platform"
az account management-group create --name "dev-management" --parent "dev-platform"
az account management-group create --name "epac-prod"
az account management-group create --name "prod-decommissioned" --parent "epac-prod"
az account management-group create --name "prod-landingzones" --parent "epac-prod"
az account management-group create --name "prod-platform" --parent "epac-prod"
az account management-group create --name "prod-sandbox" --parent "prod-landingzones"
az account management-group create --name "prod-corp" --parent "prod-landingzones"
az account management-group create --name "prod-online" --parent "prod-landingzones"
az account management-group create --name "prod-connectivity" --parent "prod-platform"
az account management-group create --name "prod-identity" --parent "prod-platform"
az account management-group create --name "prod-management" --parent "prod-platform"

Installation

To install EPAC, follow these steps:

    Install-Module Az -Scope CurrentUser
    Install-Module EnterprisePolicyAsCode -Scope CurrentUser

Create an empty repository in github and clone it

Create a repository in github and clone it

    git clone https://github.com/user/demo-EPAC.git

Create a branch for the feature/firstcommit

    git checkout -b feature/firstcommit

Note

From this moment on, we will execute all commands within the repository directory.

Create Definitions

New-EPACDefinitionFolder -DefinitionsRootFolder Definitions

This command creates a folder structure for the definitions. The Definitions folder Structure is as follows:

  • Define the Azure environment(s) in file global-settings.jsonc
  • Create custom Policies (optional) in folder policyDefinitions
  • Create custom Policy Sets (optional) in folder policySetDefinitions
  • efine the Policy Assignments in folder policyAssignments
  • Define the Policy Exemptions (optional) in folder policyExemptions
  • Define Documentation in folder policyDocumentations]

Configure global-settings.jsonc

global-settings.jsonc is the file where you define the Azure environment(s) that you want to manage with EPAC. The file should be located in the Definitions folder. Here is an example of the content of the file:

{
    "$schema": "https://raw.githubusercontent.com/Azure/enterprise-azure-policy-as-code/main/Schemas/global-settings-schema.json",
    "pacOwnerId": "ff2ce5e1-da8a-4cfb-883b-aee9fbfb85d6",
    "pacEnvironments": [
        {
            "pacSelector": "epac-dev",
            "cloud": "AzureCloud",
            "tenantId": "e18e4e7e-d0cc-40af-9907-84923ca55499",
            "deploymentRootScope": "/providers/Microsoft.Management/managementGroups/epac-dev",
            "desiredState": {
                "strategy": "full",
                "keepDfcSecurityAssignments": false
            },
            "managedIdentityLocation": "france"
        },
        {
            "pacSelector": "tenant",
            "cloud": "AzureCloud",
            "tenantId": "e18e4e7e-d0cc-40af-9907-84923ca55499",
            "deploymentRootScope": "/providers/Microsoft.Management/managementGroups/epac-prod",
            "desiredState": {
                "strategy": "full",
                "keepDfcSecurityAssignments": false
            },
            "managedIdentityLocation": "france",
            "globalNotScopes": [
                "/providers/Microsoft.Management/managementGroups/mg-Epac-Dev",
                "/providers/Microsoft.Management/managementGroups/manage-azure-policy"
            ]
        },
        {
            "pacSelector": "manage-azure-policy",
            "cloud": "AzureCloud",
            "tenantId": "e18e4e7e-d0cc-40af-9907-84923ca55499",
            "deploymentRootScope": "/providers/Microsoft.Management/managementGroups/manage-azure-policy",
            "desiredState": {
                "strategy": "full",
                "keepDfcSecurityAssignments": false
            },
            "managedIdentityLocation": "france"
        }
    ]

}

Info

The pacOwner helps to identify who or what owns an Assignment or Policy definition deployment and needs to be unique to your EPAC environment. The pacOwnerId is used to identity policy resources that are deployed by your EPAC repository, or another EPAC isntance, legacy or another solution entirely.

You can generate a new id with New-Guid

Extracting existing Policy Resources

Export-AzPolicyResources

This command extracts all existing Policy Resources in the Azure environment(s) defined in the global-settings.jsonc file. The extracted resources are saved in the Output/Definitions folder.

You needs review the extracted resources and move them to the correct folder in the Definitions folder.

Syncing ALZ Definitions

Sync-ALZPolicies -DefinitionsRootFolder .\Definitions -CloudEnvironment AzureCloud # Also accepts AzureUSGovernment or AzureChinaCloud

You can sync the ALZ Definitions manually or use a GitHub action creating .github\workflows\alz-sync.yaml in your repository with the following content:

name: Sync ALZ Policy Objects

env:
  REVIEWER: anwather # Change this to your GitHub username
  DefinitionsRootFolder: Definitions # Change this to the folder where your policy definitions are stored

on:
  workflow_dispatch

jobs:
    sync:
        runs-on: ubuntu-latest
        steps:
        - name: Checkout
          uses: actions/checkout@v4
        - shell: pwsh
          name: Install Required Modules
          run: |
            Install-Module EnterprisePolicyAsCode -Force
            Sync-ALZPolicies -DefinitionsRootFolder $env:DefinitionsRootFolder
            $branchName = "caf-sync-$(Get-Date -Format yyyy-MM-dd-HH-mm)"
            git config user.name "GitHub Actions Bot"
            git config user.email "<>"
            git checkout -b $branchName
            git add .
            git commit -m "Updated ALZ policy objects"
            git push --set-upstream origin $branchName
            gh pr create -B main -H $branchName --title "Verify Synced Policies - $branchName" -b "Checkout this PR branch and validate changes before merging." --reviewer $env:REVIEWER
        env:
            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

CI/CD with Github Flow

We will use the Github Flow to manage the CI/CD process. We will create a Github Actions to deploy the policies to the Azure environment(s) defined in the global-settings.jsonc file.

Github Flow

We can open a second terminal and execute the following command to create the Github Actions in one upper level folder of our repository. This command will create the Github Actions in the .github\workflows folder of the repository. :

git clone https://github.com/Azure/enterprise-azure-policy-as-code
cd enterprise-azure-policy-as-code
New-PipelinesFromStarterKit -StarterKitFolder .\StarterKit -PipelinesFolder ..\global-azure-2024-demo-EPAC\.github\workflows -PipelineType GitHubActions -BranchingFlow github -ScriptType Module 

Now, we need to create some environments with secrets in the repository to use in the Github Actions. We need to create the following environments:

Environment Purpose App Registration (SPN)
EPAC-DEV Plan and deploy to epac-dev ci-cd-epac-dev-owner
TENANT-PLAN Build deployment plan for tenant ci-cd-root-policy-reader
TENANT-DEPLOY-POLICY Deploy Policy resources for tenant ci-cd-root-policy-contributor
TENANT-DEPLOY-ROLES Deploy Roles for tenant ci-cd-root-user-assignments
TENANT-REMEDIATE-POLICY Remediate Policy resources for tenant ci-cd-root-policy-contributor

You need to Configure a federated identity credential on an app too.

First Commit

Now we can commit the changes to the repository and make a pull request to the main branch.

References

Cambio de nombres de los niveles de servicio de Microsoft Defender para Cloud

No es nuevo pero me gustaría recordar que Microsoft ha cambiado los nombres de los niveles de servicio de Microsoft Defender para Cloud. A continuación, se muestra una tabla con los nombres anteriores y los nuevos nombres de los niveles de servicio de Microsoft Defender para Cloud:

Nombre ANTERIOR del nivel de servicio 2 Nombre NUEVO del nivel de servicio 2 Nivel de servicio: nivel de servicio 4 (sin cambios)
Advanced Data Security Microsoft Defender for Cloud Defender para SQL
Advanced Threat Protection Microsoft Defender for Cloud Defender para registros de contenedor
Advanced Threat Protection Microsoft Defender for Cloud Defender para DNS
Advanced Threat Protection Microsoft Defender for Cloud Defender para Key Vault
Advanced Threat Protection Microsoft Defender for Cloud Defender para Kubernetes
Advanced Threat Protection Microsoft Defender for Cloud Defender para MySQL
Advanced Threat Protection Microsoft Defender for Cloud Defender para PostgreSQL
Advanced Threat Protection Microsoft Defender for Cloud Defender para Resource Manager
Advanced Threat Protection Microsoft Defender for Cloud Defender para Storage
Azure Defender Microsoft Defender for Cloud Administración de superficie expuesta a ataques externos de Defender
Azure Defender Microsoft Defender for Cloud Defender para Azure Cosmos DB
Azure Defender Microsoft Defender for Cloud Defender para contenedores
Azure Defender Microsoft Defender for Cloud Defender for MariaDB
Security Center Microsoft Defender for Cloud Defender para App Service
Security Center Microsoft Defender for Cloud Defender para servidores
Security Center Microsoft Defender for Cloud Administración de la posición de seguridad en la nube de Defender

Azure Policy useful queries

Policy assignments and information about each of its respective definitions

// Policy assignments and information about each of its respective definitions
// Gets policy assignments in your environment with the respective assignment name,definition associated, category of definition (if applicable), as well as whether the definition type is an initiative or a single policy.

policyResources
| where type =~'Microsoft.Authorization/PolicyAssignments'
| project policyAssignmentId = tolower(tostring(id)), policyAssignmentDisplayName = tostring(properties.displayName), policyAssignmentDefinitionId = tolower(properties.policyDefinitionId)
| join kind=leftouter(
 policyResources
 | where type =~'Microsoft.Authorization/PolicySetDefinitions' or type =~'Microsoft.Authorization/PolicyDefinitions'
 | project definitionId = tolower(id), category = tostring(properties.metadata.category), definitionType = iff(type =~ 'Microsoft.Authorization/PolicysetDefinitions', 'initiative', 'policy')
) on $left.policyAssignmentDefinitionId == $right.definitionId

List SubscriptionId and SubscriptionName

ResourceContainers
| where type =~ 'microsoft.resources/subscriptions'
| project subscriptionId, subscriptionName=name

List ManagementGroupId and ManagementGroupName

ResourceContainers
| where type =~ 'microsoft.management/managementgroups'
| project mgname = name, displayName = properties.displayName

Policy assignments and information about each of its respective definitions displaying the scope of the assignment, the subscription display name, the management group id, the resource group name, the definition type, the assignment name, the category of the definition, and the policy assignment ID.

policyResources
| where type =~'Microsoft.Authorization/PolicyAssignments'
| project policyAssignmentId = tolower(tostring(id)), policyAssignmentDisplayName = tostring(properties.displayName), policyAssignmentDefinitionId = tolower(properties.policyDefinitionId), subscriptionId = tostring(subscriptionId),resourceGroup=tostring(resourceGroup), AssignmentDefinition=properties
| join kind=leftouter(
    policyResources
    | where type =~'Microsoft.Authorization/PolicySetDefinitions' or type =~'Microsoft.Authorization/PolicyDefinitions'
    | project definitionId = tolower(id), category = tostring(properties.metadata.category), definitionType = iff(type =~ 'Microsoft.Authorization/PolicysetDefinitions', 'initiative', 'policy'),PolicyDefinition=properties
) on $left.policyAssignmentDefinitionId == $right.definitionId
| extend scope = iff(policyAssignmentId contains '/subscriptions/', 'Subscription', iff(policyAssignmentId contains '/providers/microsoft.management/managementgroups', 'Management Group', 'Resource Group'))
| join kind=leftouter (ResourceContainers
| where type =~ 'microsoft.resources/subscriptions'
| project subscriptionId, subscriptionName=name) on $left.subscriptionId == $right.subscriptionId
| extend SubscriptionDisplayName = iff(isnotempty(subscriptionId), subscriptionName, '')
| extend ManagementGroupName = iff(policyAssignmentId contains '/providers/microsoft.management/', split(policyAssignmentId, '/')[4],'')
| extend resourceGroupDisplayName = iff(isnotempty(resourceGroup), resourceGroup, '')
| project ManagementGroupName,SubscriptionDisplayName,resourceGroupDisplayName, scope,definitionType,policyAssignmentDisplayName, category,policyAssignmentId, AssignmentDefinition, PolicyDefinition
  • Add Management Group Display Name

How to use Azue ARC-enabled servers with managed identity to access to Azure Storage Account

In this demo we will show how to use Azure ARC-enabled servers with managed identity to access to Azure Storage Account.

Prerequisites

  • An Azure subscription. If you don't have an Azure subscription, create a free account before you begin.

Required permissions

You'll need the following Azure built-in roles for different aspects of managing connected machines:

  • To onboard machines, you must have the Azure Connected Machine Onboarding or Contributor role for the resource group where you're managing the servers.
  • To read, modify, and delete a machine, you must have the Azure Connected Machine Resource Administrator role for the resource group.
  • To select a resource group from the drop-down list when using the Generate script method, you'll also need the Reader role for that resource group (or another role that includes Reader access).

Register Azure resource providers

To use Azure Arc-enabled servers with managed identity, you need to register the following resource providers:

az account set --subscription "{Your Subscription Name}"
az provider register --namespace 'Microsoft.HybridCompute'
az provider register --namespace 'Microsoft.GuestConfiguration'
az provider register --namespace 'Microsoft.HybridConnectivity'
az provider register --namespace 'Microsoft.AzureArcData'

Info

Microsoft.AzureArcData (if you plan to Arc-enable SQL Servers) Microsoft.Compute (for Azure Update Manager and automatic extension upgrades)

Networking requirements

The Azure Connected Machine agent for Linux and Windows communicates outbound securely to Azure Arc over TCP port 443. In this demo, we have use Azure Private Link.

Azure ARC-enabled enabled server

We use Use Azure Private Link to securely connect networks to Azure Arc-enabled servers to achieve this.

Some tips:

  • If you have any issue registerin de VM: generate a script to register a machine with Azure Arc following that instructions here

  • If you have an error that says "Path C:\ProgramData\AzureConnectedMachineAgent\Log\himds.log is busy. Retrying..." you can use the following command to resolve it if you know that you are doing:

 (get-wmiobject -class win32_product | where {$_.name -like "Azure *"}).uninstall() 
- Review /etc/hosts file and add the following entries:

$Env:PEname = "myprivatelink"
$Env:resourceGroup = "myResourceGroup"
$file = "C:\Windows\System32\drivers\etc\hosts"

$gisfqdn = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query '[0].privateDnsZoneConfigs[0].recordSets[0].fqdn' -o json).replace('.privatelink','').replace("`"","")
$gisIP = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[0].recordSets[0].ipAddresses[0] -o json).replace("`"","")
$hisfqdn = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[0].recordSets[1].fqdn -o json).replace('.privatelink','').replace("`"","")
$hisIP = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[0].recordSets[1].ipAddresses[0] -o json).replace('.privatelink','').replace("`"","")
$agentfqdn = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[1].recordSets[0].fqdn -o json).replace('.privatelink','').replace("`"","")
$agentIp = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[1].recordSets[0].ipAddresses[0] -o json).replace('.privatelink','').replace("`"","")
$gasfqdn = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[1].recordSets[1].fqdn -o json).replace('.privatelink','').replace("`"","")
$gasIp = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[1].recordSets[1].ipAddresses[0] -o json).replace('.privatelink','').replace("`"","")
$dpfqdn = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[2].recordSets[0].fqdn -o json).replace('.privatelink','').replace("`"","")
$dpIp = (az network private-endpoint dns-zone-group list --endpoint-name $Env:PEname --resource-group $Env:resourceGroup -o json --query [0].privateDnsZoneConfigs[2].recordSets[0].ipAddresses[0] -o json).replace('.privatelink','').replace("`"","")

$hostfile += "$gisIP $gisfqdn"
$hostfile += "$hisIP $hisfqdn"
$hostfile += "$agentIP $agentfqdn"
$hostfile += "$gasIP $gasfqdn"
$hostfile += "$dpIP $dpfqdn"

Storage Account configuration

Create a Storage Account with static website enabled

$resourceGroup = "myResourceGroup"
$location = "eastus"
$storageAccount = "mystorageaccount"
$indexDocument = "index.html"
az group create --name $resourceGroup --location $location
az storage account create --name $storageAccount --resource-group $resourceGroup --location $location --sku Standard_LRS
az storage blob service-properties update --account-name $storageAccount --static-website --index-document $indexDocument

Add private endpoints to the storage accoun for blob and static website

$resourceGroup = "myResourceGroup"
$storageAccount = "mystorageaccount"
$privateEndpointName = "myprivatelink"
$location = "eastus"
$vnetName = "myVnet"
$subnetName = "mySubnet"
$subscriptionId = "{subscription-id}"
az network private-endpoint create --name $privateEndpointName --resource-group $resourceGroup --vnet-name $vnetName --subnet $subnetName --private-connection-resource-id "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Storage/storageAccounts/$storageAccount" --group-id blob --connection-name $privateEndpointName --location $location
az network private-endpoint create --name $privateEndpointName --resource-group $resourceGroup --vnet-name $vnetName --subnet $subnetName --private-connection-resource-id "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Storage/storageAccounts/$storageAccount" --group-id web --connection-name $privateEndpointName --location $location

Disable public access to the storage account except for your ip

$resourceGroup = "myResourceGroup"
$storageAccount = "mystorageaccount"
$ipAddress = "myIpAddress"
az storage account update --name $storageAccount --resource-group $resourceGroup --bypass "AzureServices,Logging,Metrics" --default-action Deny
az storage account network-rule add --account-name $storageAccount --resource-group $resourceGroup --ip-address $ipAddress

Assign the Storage Blob Data Contributor role to the managed identity of the Azure ARC-enabled server

$resourceGroup = "myResourceGroup"
$storageAccount = "mystorageaccount"
$serverName = "myserver"
$managedIdentity = az resource show --resource-group $resourceGroup --name $serverName --resource-type "Microsoft.HybridCompute/machines" --query "identity.principalId" --output tsv
az role assignment create --role "Storage Blob Data Contributor" --assignee-object-id $managedIdentity --scope "/subscriptions/{subscription-id}/resourceGroups/$resourceGroup/providers/Microsoft.Storage/storageAccounts/$storageAccount"

Download azcopy, install it and copy something to $web in the storage account

Download azcopy in the vm

Invoke-WebRequest -Uri "https://aka.ms/downloadazcopy-v10-windows" -OutFile AzCopy.zip

Expand-Archive AzCopy.zip -DestinationPath $env:ProgramFiles

$env:Path += ";$env:ProgramFiles\azcopy"

Copy something to $web in the storage account

$storageAccount = "mystorageaccount"
$source = "C:\Users\Public\Documents\myFile.txt"
$destination = "https://$storageAccount.blob.core.windows.net/\$web/myFile.txt"
azcopy login --identity
azcopy copy $source $destination

Now you can check the file in the static website of the storage account.

Azure ARC

Azure ARC is a service that extends Azure management capabilities to any infrastructure. It allows you to manage resources running on-premises, at the edge, or in multi-cloud environments using the same Azure management tools, security, and compliance policies that you use in Azure. Azure ARC enables you to manage and govern your resources consistently across all environments, providing a unified control plane for your hybrid cloud infrastructure. Let's explore how Azure ARC works and how you can leverage it to manage your resources effectively.

Azure ARC Overview

Azure ARC is a service that extends Azure management capabilities to any infrastructure. It allows you to manage resources running outside of Azure using the same Azure management tools, security, and compliance policies that you use in Azure. Azure ARC provides a unified control plane for managing resources across on-premises, multi-cloud, and edge environments, enabling you to govern your resources consistently.

Azure ARC enables you to:

  • Manage resources: Azure ARC allows you to manage resources running on-premises, at the edge, or in multi-cloud environments using Azure management tools like Azure Policy, Azure Monitor, and Microsoft Defender for Cloud.
  • Governance: Azure ARC provides a unified control plane for managing and governing resources across all environments, enabling you to enforce security and compliance policies consistently.
  • Security: Azure ARC extends Azure security capabilities to resources running outside of Azure, enabling you to protect your resources with Azure security features like Azure Security Center and Azure Defender.
  • Compliance: Azure ARC enables you to enforce compliance policies across all environments, ensuring that your resources meet regulatory requirements and organizational standards.

Azure ARC Components

Azure ARC consists of the following components:

  • Azure ARC-enabled servers: Azure ARC-enabled servers allow you to manage and govern servers running on-premises or at the edge using Azure management tools. You can connect your servers to Azure ARC to manage them using Azure Policy, Azure Monitor, and Microsoft Defender for Cloud.
  • Azure ARC-enabled Kubernetes clusters: Azure ARC-enabled Kubernetes clusters allow you to manage and govern Kubernetes clusters running on-premises or in other clouds using Azure management tools. You can connect your Kubernetes clusters to Azure ARC to manage them using Azure Policy, Azure Monitor, and Microsoft Defender for Cloud.
  • Azure ARC-enabled data services: Azure ARC-enabled data services allow you to manage and govern data services running on-premises or in other clouds using Azure management tools. You can connect your data services to Azure ARC to manage them using Azure Policy, Azure Monitor, and Microsoft Defender for Cloud.
  • SQL Server enabled by Azure Arc: SQL Server enabled by Azure Arc allows you to run SQL Server on any infrastructure using Azure management tools. You can connect your SQL Server instances to Azure ARC to manage them using Azure Policy, Azure Monitor, and Microsoft Defender for Cloud.
  • Azure Arc-enabled private clouds: Azure Arc resource bridge hosts other components such as custom locations, cluster extensions, and other Azure Arc agents in order to deliver the level of functionality with the private cloud infrastructures it supports.

Azure ARC Use Cases

Azure ARC can be used in a variety of scenarios to manage and govern resources across on-premises, multi-cloud, and edge environments. Some common use cases for Azure ARC include:

  • Hybrid cloud management: Azure ARC enables you to manage resources consistently across on-premises, multi-cloud, and edge environments using the same Azure management tools and policies.
  • Security and compliance: Azure ARC allows you to enforce security and compliance policies consistently across all environments, ensuring that your resources meet regulatory requirements and organizational standards.
  • Resource governance: Azure ARC provides a unified control plane for managing and governing resources across all environments, enabling you to enforce policies and monitor resource health and performance.
  • Application modernization: Azure ARC enables you to manage and govern Kubernetes clusters and data services running on-premises or in other clouds, allowing you to modernize your applications and infrastructure.

Getting Started with Azure ARC

To get started with Azure ARC, you need to:

  1. Connect your resources: Connect your servers, Kubernetes clusters, or data services to Azure ARC using the Azure ARC agent.
  2. Manage your resources: Use Azure management tools like Azure Policy, Azure Monitor, and Microsoft Defender for Cloud to manage and govern your resources consistently across all environments.
  3. Enforce security and compliance: Use Azure security features like Microsoft Defender for Cloud to protect your resources and enforce security and compliance policies.

By leveraging Azure ARC, you can manage and govern your resources consistently across on-premises, multi-cloud, and edge environments, providing a unified control plane for your hybrid cloud infrastructure. Azure ARC enables you to enforce security and compliance policies consistently, ensuring that your resources meet regulatory requirements and organizational standards.

Conclusion

Azure ARC is a powerful service that extends Azure management capabilities to any infrastructure, enabling you to manage and govern resources consistently across on-premises, multi-cloud, and edge environments. By leveraging Azure ARC, you can enforce security and compliance policies consistently, ensuring that your resources meet regulatory requirements and organizational standards. Azure ARC provides a unified control plane for managing and governing resources, enabling you to manage your hybrid cloud infrastructure effectively.

For more information on Azure ARC, visit the Azure ARC documentation.

Microsoft Azure Certifications

Microsoft offers a wide range of certifications for IT professionals who want to demonstrate their expertise in Microsoft technologies. These certifications cover a variety of topics, including Azure, Office 365, Windows Server, and more.

Microsoft divide this certifications into different categories, such as:

  • Infrastructure
  • Data and AI
  • Digital app and innovation
  • Modern work
  • Business applications
  • Security

Inside of each category, you can find different certification levels:

  • Fundamentals: This level is designed for individuals who are new to the technology and want to demonstrate their knowledge of the basics.
  • Role-based: This level is designed for individuals who want to demonstrate their expertise in a specific role, such as Azure Administrator or Data Engineer.
  • Specialty: This level is designed for individuals who want to demonstrate their expertise in a specific skill, such as Azure Virtual Desktop or Azure SAP.

In the case of role-based certifications, Microsoft offers different levels of certification, such as:

  • Associate: This level is designed for individuals who have some experience in the technology and want to demonstrate their expertise in a specific role.
  • Expert: This level is designed for individuals who have extensive experience in the technology and want to demonstrate their expertise in a specific role.

Allways is a good idea to start with the fundamentals certifications, and then move on to the role-based certifications that are relevant to your career goals.

In the majority of cases, you need associate certifications to get expert certifications.

Azure Certifications

Here's a table summarizing the Azure Certifications and their description:

Certification Exam required Description url
Azure Administrator Associate AZ-104 The Azure Administrator certification is designed for individuals who want to demonstrate their expertise in managing Azure resources. This certification is ideal for IT professionals who are responsible for implementing, monitoring, and maintaining Azure solutions. https://learn.microsoft.com/en-us/certifications/azure-administrator
Azure Developer Associate AZ-204 The Azure Developer certification is designed for individuals who want to demonstrate their expertise in developing applications on Azure. This certification is ideal for software developers who want to build and deploy cloud-based applications using Azure services. https://learn.microsoft.com/en-us/certifications/azure-developer
Azure Data Engineer Associate DP-203 The Azure Data Engineer certification is designed for individuals who want to demonstrate their expertise in designing and implementing data solutions on Azure. This certification is ideal for data professionals who are responsible for building and maintaining data pipelines and data warehouses on Azure. https://learn.microsoft.com/en-us/certifications/azure-data-engineer
Azure Database Administrator Associate DP-300 The Azure Database Administrator certification is designed for individuals who want to demonstrate their expertise in managing Azure databases. This certification is ideal for database administrators who are responsible for designing, implementing, and maintaining databases on Azure. https://learn.microsoft.com/en-us/certifications/azure-database-administrator
DevOps Engineer Expert AZ-400 The Azure DevOps Engineer certification is designed for individuals who want to demonstrate their expertise in implementing DevOps practices on Azure. This certification is ideal for IT professionals who are responsible for building, testing, and deploying applications using Azure DevOps. https://learn.microsoft.com/en-us/certifications/devops-engineer
Azure Security Engineer Associate AZ-500 The Azure Security Engineer certification is designed for individuals who want to demonstrate their expertise in securing Azure resources. This certification is ideal for IT professionals who are responsible for implementing security controls and monitoring security events on Azure. https://learn.microsoft.com/en-us/certifications/azure-security-engineer
Azure Network Engineer Associate AZ-700 The Azure Network Engineer certification is designed for individuals who want to demonstrate their expertise in designing and implementing network solutions on Azure. This certification is ideal for network engineers who are responsible for building and maintaining network infrastructure on Azure. https://learn.microsoft.com/en-us/certifications/azure-network-engineer
Windows Server Hybrid Administrator Associate AZ-800 AZ-801 The Windows Server Hybrid Administrator certification is designed for individuals who want to demonstrate their expertise in managing Windows Server resources on Azure. This certification is ideal for IT professionals who are responsible for implementing, monitoring, and maintaining Windows Server solutions on Azure. https://learn.microsoft.com/en-us/certifications/windows-server-hybrid-administrator
Fabric Analytics Engineer Associate DP-600 The Fabric Analytics Engineer certification is designed for individuals who want to demonstrate their expertise in designing and implementing analytics solutions on Azure. This certification is ideal for data professionals who are responsible for building and maintaining analytics solutions on Azure. https://learn.microsoft.com/en-us/certifications/fabric-analytics-engineer
Azure AI Engineer Associate AI-102 The Azure AI Engineer certification is designed for individuals who want to demonstrate their expertise in designing and implementing AI solutions on Azure. This certification is ideal for data scientists and AI developers who want to build and deploy AI models using Azure services. https://learn.microsoft.com/en-us/certifications/azure-ai-engineer
Azure Data Scientist Associate DP-100 The Azure Data Scientist certification is designed for individuals who want to demonstrate their expertise in designing and implementing data science solutions on Azure. This certification is ideal for data scientists who are responsible for building and maintaining data science solutions on Azure. https://learn.microsoft.com/en-us/certifications/azure-data-scientist
Azure Enterprise Data Analyst Associate DP-500 The Azure Enterprise Data Analyst certification is designed for individuals who want to demonstrate their expertise in designing and implementing data analysis solutions on Azure. This certification is ideal for data analysts who are responsible for building and maintaining data analysis solutions on Azure. https://learn.microsoft.com/en-us/certifications/azure-enterprise-data-analyst
Azure Solutions Architect Expert AZ-305 The Azure Solutions Architect certification is designed for individuals who want to demonstrate their expertise in designing and implementing solutions on Azure. This certification is ideal for IT professionals who are responsible for designing and implementing cloud-based solutions using Azure services. https://learn.microsoft.com/en-us/certifications/azure-solutions-architect
Azure for SAP Workloads Specialty AZ-120 The Azure for SAP Workloads certification is designed for individuals who want to demonstrate their expertise in deploying and managing SAP workloads on Azure. This certification is ideal for IT professionals who are responsible for implementing and maintaining SAP solutions on Azure. https://learn.microsoft.com/en-us/certifications/azure-for-sap-workloads
Azure Virtual Desktop Specialty AZ-140 The Azure Virtual Desktop certification is designed for individuals who want to demonstrate their expertise in deploying and managing virtual desktop solutions on Azure. This certification is ideal for IT professionals who are responsible for implementing and maintaining virtual desktop solutions on Azure. https://learn.microsoft.com/en-us/certifications/azure-virtual-desktop
Azure Cosmos DB Developer Specialty DP-420 The Azure Cosmos DB Developer certification is designed for individuals who want to demonstrate their expertise in developing applications that use Azure Cosmos DB. This certification is ideal for software developers who want to build and deploy applications that use Azure Cosmos DB. https://learn.microsoft.com/en-us/certifications/azure-cosmos-db-developer
Azure Fundamentals AZ-900 The Azure Fundamentals certification is designed for individuals who are new to Azure and want to demonstrate their knowledge of the platform. This certification is a great starting point for anyone who wants to learn more about Azure and how it can help them build and deploy applications in the cloud. https://learn.microsoft.com/en-us/certifications/azure-fundamentals
Azure AI Fundamentals AI-900 The Azure AI Fundamentals certification is designed for individuals who want to demonstrate their knowledge of AI concepts and how they can be applied to Azure services. This certification is ideal for anyone who wants to learn more about AI and how it can be used to build intelligent applications. https://learn.microsoft.com/en-us/certifications/azure-ai-fundamentals
Azure Data Fundamentals DP-900 The Azure Data Fundamentals certification is designed for individuals who want to demonstrate their knowledge of data concepts and how they can be applied to Azure services. This certification is ideal for anyone who wants to learn more about data and how it can be used to build data-driven applications. https://learn.microsoft.com/en-us/certifications/azure-data-fundamentals

You can find more information about Microsoft certifications on the Microsoft Certification Poster and in the Microsoft Learning website.

Privileged Access Management (PAM) Strategy with Microsoft Entra ID and some Azure Services

Today, I'd like to share a brief of a recommended strategy for Privileged Access Management (PAM) of other vendors with Microsoft Entra ID and some Azure Services. This strategy is divided into seven phases:

Syntax error in textmermaid version 11.2.0

Info

Be hybrid, be secure with a single control plane, use Azure ARC to inherit the same security and compliance policies across your on-premises, multi-cloud, and edge environments as in Azure.

Phase 1: Set Policy

The first step in any PAM strategy is to establish a clear policy. This policy should define who has access to what, when they have access, and what they can do with that access. It should also include guidelines for password management and multi-factor authentication. For example:

  • Define clear access control policies.
  • Establish guidelines for password management and multi-factor authentication.
  • Regularly review and update the policy to reflect changes in the organization.

How to implement this:

  • Use Azure Policy to define and manage policies for your Azure environment.
  • Use Microsoft Entra multifactor authentication for implementing multi-factor authentication.

Phase 2: The Process of Discovery

In this phase, we identify all the privileged accounts across the organization. This includes service accounts, local administrative accounts, domain administrative accounts, emergency accounts, and application accounts. For example:

  • Use automated tools to identify all privileged accounts across the organization.
  • Regularly update the inventory of privileged accounts.
  • Identify any accounts that are no longer in use and deactivate them.

How to implement this:

  • Use Microsoft Entra Privileged Identity Management to discover, restrict and monitor administrators and their access to resources and provide just-in-time access when needed.

Phase 3: Protect Credentials

Once we've identified all privileged accounts, we need to ensure that these credentials are stored securely. This could involve using a secure vault, regularly rotating passwords, and using unique passwords for each account. For example:

  • Store credentials in a secure vault.
  • Implement regular password rotation.
  • Use unique passwords for each account.

How to implement this:

  • Use Azure Key Vault to safeguard cryptographic keys and other secrets used by your apps and services and rotate secrets regularly.
  • Implement Microsoft Entra ID Password Protection to protect against weak passwords that can be easily guessed or cracked.

Phase 4: Secure Privileged Access

Securing privileged access involves implementing controls to prevent unauthorized access. This could include limiting the number of privileged accounts, implementing least privilege, and using just-in-time access. For example:

  • Limit the number of privileged accounts.
  • Implement just-in-time access, where access is granted only for the duration of a task.
  • Use session recording and monitoring for privileged access.

How to implement this:

  • Use Microsoft Entra ID Conditional Access to enforce controls on the access to apps in your environment based on specific conditions.
  • Implement Microsoft Entra Privileged Identity Management for just-in-time access.

Phase 5: Least Privilege

The principle of least privilege involves giving users the minimum levels of access — or permissions — they need to complete their job functions. By limiting the access rights of users, the risk of a security breach is reduced. For example:

  • Implement role-based access control (RBAC) in Azure to grant the minimum necessary access to users.
  • Regularly review user roles and access rights.
  • Implement a process for revoking access when it's no longer needed.

How to implement this:

  • Implement Role-Based Access Control (RBAC) in Azure to grant the minimum necessary access to users.
  • Use Microsoft Entra ID Access Reviews to efficiently manage group memberships, access to enterprise applications, and role assignments.

Phase 6: Control All Applications

In this phase, we ensure that all applications, whether on-premises or in the cloud, are controlled and monitored. This includes implementing application control policies and monitoring application usage. For example:

  • Implement application control policies that dictate what applications can be run on systems.
  • Monitor application usage and block unauthorized applications.
  • Regularly update and patch all applications to reduce vulnerabilities.

How to implement this:

  • Use Microsoft Entra Application Proxy to control and secure access to on-premises and cloud apps.
  • Enable Change Tracking and Inventory in Azure Automation to track changes to your Azure VMs. Use desired state configuration to ensure that your VMs are configured correctly.
  • Implement Microsoft Intune to manage and secure your devices and applications.

Phase 7: Detect and Respond

The final phase involves setting up systems to detect and respond to any suspicious activity. This could involve setting up alerts for unusual activity, regularly auditing access logs, and having a response plan in place for when a breach occurs. For example:

  • Set up alerts for unusual activity.
  • Regularly audit access logs.
  • Have a response plan in place for when a breach occurs, including steps for containment, eradication, and recovery.

How to implement this:

  • Use Microsoft Defender for Cloud for increased visibility into your security state and to detect and respond to threats.
  • Implement Azure Sentinel, Microsoft's cloud-native SIEM solution, for intelligent security analytics.

By following these seven phases, you can create a robust PAM strategy that protects your organization from security breaches and helps you maintain compliance with various regulations.

Remember, a good PAM strategy is not a one-time effort but an ongoing process that needs to be regularly reviewed and updated. Microsoft and Azure services provide a robust set of tools to help you implement and manage your PAM strategy effectively.

Azure Policy Management Best Practices

  1. Version Control: Store your policy definitions in a version-controlled repository. This practice ensures that you can track changes, collaborate effectively, and roll back to previous versions if needed.

  2. Automated Testing: Incorporate policy testing into your CI/CD pipelines. Automated tests can help you catch policy violations early in the development process, reducing the risk of non-compliance.

  3. Policy Documentation: Document your policies clearly, including their purpose, scope, and expected behavior. This documentation helps stakeholders understand the policies and their impact on Azure resources.

  4. Policy Assignment: Assign policies at the appropriate scope (e.g., Management Group, Subscription, Resource Group) based on your organizational requirements. Avoid assigning policies at a broader scope than necessary to prevent unintended consequences.

  5. Policy Exemptions: Use policy exemptions judiciously. Document the reasons for exemptions and periodically review them to ensure they are still valid.

  6. Policy Enforcement: Monitor policy compliance regularly and take corrective action for non-compliant resources. Use Azure Policy's built-in compliance reports and alerts to track policy violations.

  7. Policy Remediation: Implement automated remediation tasks for policy violations where possible. Azure Policy's remediation tasks can help bring non-compliant resources back into compliance automatically.

  8. Policy Monitoring: Continuously monitor policy effectiveness and adjust policies as needed. Regularly review policy violations, exemptions, and compliance trends to refine your policy implementation.

  9. Policy Governance: Establish a governance framework for Azure Policy that includes policy creation, assignment, monitoring, and enforcement processes. Define roles and responsibilities for policy management to ensure accountability.

  10. Policy Lifecycle Management: Define a policy lifecycle management process that covers policy creation, testing, deployment, monitoring, and retirement. Regularly review and update policies to align with changing organizational requirements.

  11. Unique source of truth: Use EPAC, terraform, ARM,.... but use an unique source of truth for your policies.

By following these best practices, you can effectively manage Azure policies and ensure compliance with organizational standards across your Azure environment. Azure Policy plays a crucial role in maintaining governance, security, and compliance, and adopting these practices can help you maximize its benefits.

Enterprise Azure Policy as Code (EPAC)

Enterprise Azure Policy as Code (EPAC) is a powerful tool that allows organizations to manage Azure Policies as code in a git repository. It's designed for medium and large organizations with a larger number of Policies, Policy Sets, and Assignments, and/or complex deployment scenarios.

Key Features of EPAC

  • Single and multi-tenant policy deployment: EPAC supports both single and multi-tenant policy deployments, making it versatile for different organizational structures.
  • Easy CI/CD Integration: EPAC can be easily integrated with any CI/CD tool, which makes it a great fit for DevOps environments.
  • Operational scripts: EPAC includes operational scripts to simplify operational tasks.
  • Integration with Azure Landing Zones: EPAC provides a mature integration with Azure Landing Zones. Utilizing Azure Landing Zones together with EPAC is highly recommended.

Who Should Use EPAC?

EPAC is designed for medium and large organizations with a larger number of Policies, Policy Sets, and Assignments, and/or complex deployment scenarios. However, smaller organizations implementing fully-automated DevOps deployments of every Azure resource (known as Infrastructure as Code) can also benefit from EPAC.

How Does EPAC Work?

EPAC works by deploying all policies and policy assignments defined in the EPAC repository to the deploymentRootScope and its children. It takes possession of all Policy Resources at the deploymentRootScope and its children.

Alt text

The process depicted in the image involves three key scripts that manage a deployment sequence. Here's a breakdown of the process:

  1. Definition Files: The process begins with various definition files in JSON, CSV, or XLSX formats. These files contain policy definitions, policy set (initiative) definitions, assignments, exemptions, and global settings.

  2. Planning Script: The Build-DeploymentPlans.ps1 script uses these definition files to create a deployment plan. This script requires Resource Policy Reader privileges.

  3. Deployment Scripts: The deployment plan is then used by two deployment scripts:

  4. Deploy-PolicyPlan.ps1: This script deploys Policy resources using the policy-plan.json file from the deployment plan. It requires Resource Policy Contributor privileges.
  5. Deploy-RolesPlan.ps1: This script deploys Role Assignments using the roles-plan.json file from the deployment plan. It requires User Access Administrator privileges.

The process includes optional approval gates after each deployment step. These are typically used in production environments to ensure each deployment step is reviewed and approved before moving to the next.

Warning

EPAC is a true desired state deployment technology. It takes possession of all Policy Resources at the deploymentRootScope and its children. It will delete any Policy resources not defined in the EPAC repo.

Conclusion

EPAC is a robust solution for managing Azure Policies as code. It offers a high level of assurance in highly controlled and sensitive environments, and a means for the development, deployment, management, and reporting of Azure policy at scale.

References

Manage Azure Policy GitHub Action

It's recommended to review:

Overview

The Manage Azure Policy GitHub Action empowers you to enforce organizational standards and assess compliance at scale using Azure policies. With this action, you can seamlessly integrate policy management into your CI/CD pipelines, ensuring that your Azure resources adhere to the desired policies.

Info

This project does not have received any updates since some time, but it is still a simple option to develop your Azure Policies. As everything cannot be good to say that this deployment method has a major drawback, deletions must be done by hand :S

Key Features

  1. Customizable Workflows: GitHub workflows are highly customizable. You have complete control over the sequence in which Azure policies are rolled out. This flexibility enables you to follow safe deployment practices and catch regressions or bugs well before policies are applied to critical resources.

  2. Azure Login Integration: The action assumes that you've already authenticated using the Azure Login action. Make sure you've logged in using an Azure service principal with sufficient permissions to write policies on selected scopes. Refer to the full documentation of Azure Login Action for details on permissions.

  3. Policy File Structure: Your policy files should be organized in a specific directory structure within your GitHub repository. Here's how it should look:

    |- policies/
       |- <policy1_name>/
          |- policy.json
          |- assign.<name1>.json
          |- assign.<name2>.json
          ...
       |- <policy2_name>/
          |- policy.json
          |- assign.<name1>.json
          |- assign.<name2>.json
          ...
    
    • Each policy resides in a subfolder under the policies/ directory.
    • The policy.json file contains the policy definition.
    • Assignment files (e.g., assign.<name1>.json) specify how the policy is applied.
  4. Inputs for the Action:

    • Paths: Specify the mandatory path(s) to the directory containing your Azure policy files.

Sample Workflow

Here's an example of how you can apply policies at the Management Group scope using the Manage Azure Policy action:

name: 'Test Policy'
on:
  push:
    branches: 
    - "*" 
    paths: 
     - 'policies/**'
     - 'initiatives/**'
  workflow_dispatch:

jobs:
  apply-azure-policy:    
    runs-on: ubuntu-latest
    steps:
    # Azure Login
    - name: Login to Azure
      uses: azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS }}
        allow-no-subscriptions: true

    - name: Checkout
      uses: actions/checkout@v2 

    - name: Create or Update Azure Policies
      uses: azure/manage-azure-policy@v0
      with:      
        paths:  |                
          policies/**
          initiatives/**
        assignments:  |
          assign.*_testRG_*.json

Remember to replace the placeholder values (such as secrets.AZURE_CREDENTIALS) with your actual configuration, you can follow this instructions to create a service principal and get the credentials: Create a service principal and get the credentials

Example of use for Policy

In this example we define all our policies and initiatives at management group level and assign to resource group, and we have a policy that requires a specific tag and its value.

You need to create a folder structure like this:

|- policies/
   |- require-tag-and-its-value/
      |- policy.json
      |- assign.testRG_testazurepolicy.json
|- initiatives/
   |- initiative1/
      |- policyset.json
      |- assign.testRG_testazurepolicy.json

policies

Info

  • The policy.json file contains the policy definition, and the assign.<name>.json file specifies how the policy is applied.
policy.json

Info

  • The id value specifies where you are going to define the policy.
policy.json
{
    "id": "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000/providers/Microsoft.Authorization/policyDefinitions/requite-tag-and-its-value",
    "type": "Microsoft.Authorization/policyDefinitions",
    "name": "requite-tag-and-its-value",
    "properties": {
        "displayName": "Require a tag and its value",
        "policyType": "Custom",
        "mode": "Indexed",
        "description": "This policy requires a specific tag and its value.",
        "metadata": {
            "category": "Tags"
        },
        "parameters": {
            "tagName": {
                "type": "String",
                "metadata": {
                    "displayName": "Tag Name",
                    "description": "Name of the tag, such as 'environment'"
                }
            },
            "tagValue": {
                "type": "String",
                "metadata": {
                    "displayName": "Tag Value",
                    "description": "Value of the tag, such as 'production'"
                }
            }
        }
        },
        "policyRule": {
            "if": {
                "not": {
                    "field": "[concat('tags[', parameters('tagName'), ']')]",
                    "equals": "[parameters('tagValue')]"
                    }
                },
            "then": {
                "effect": "deny"
            }
        }
    }
assign.testRG_testazurepolicy.json

Info

  • Change the id and scope values in the assign.<name>.json file to match your Azure subscription and resource group.
  • id specifies where you are going to deploy the assignment.
  • id and name are related, name can not be any value, it should be the same as the last part of the id. You can generete a new GUID and use it as name with (1..24 | %{ '{0:x}' -f (Get-Random -Max 16) }) -join ''
  • name and id are related.
  • The policyDefinitionId value should match the id value in the policy.json file.
assign.testRG_testazurepolicy.json
{
    "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-testazurepolicy/providers/Microsoft.Authorization/policyAssignments/599a2c3a1a3b1f8b8e547b3e",
    "type": "Microsoft.Authorization/policyAssignments",
    "name": "599a2c3a1a3b1f8b8e547b3e",     
    "properties": {
        "description": "This policy audits the presence of a specific tag and its value.",
        "displayName": "Require a tag and its value",
        "parameters": {
            "tagName": {
              "value": "environment"
            },
            "tagValue": {
              "value": "production"
            }
          },
          "nonComplianceMessages": [
            {
              "message": "This resource is not compliant with the policy. Please apply the required tag and its value."
            }
          ],
          "enforcementMode": "Default",
          "policyDefinitionId": "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000/providers/Microsoft.Authorization/policyDefinitions/requite-tag-and-its-value",
          "scope": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-testazurepolicy"
    }    
}

initiatives

Info

  • The policyset.json file contains the policy definition, and the assign.<name>.json file specifies how the initiative is applied.
policyset.json

Info

  • The id value specifies where you are going to define the initiative.
  • The policyDefinitions array contains the policy definitions that are part of the initiative.
  • The parameters object defines the parameters that can be passed to the policies within the initiative.
  • The policyDefinitionId value should match the id value in the policy.json file of the policy.
policyset.json
{
    "id": "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000/providers/Microsoft.Authorization/policySetDefinitions/initiative1",
    "type": "Microsoft.Authorization/policySetDefinitions",
    "name": "initiative1",
    "properties": {
        "displayName": "Initiative 1",
        "description": "This initiative contains a set of policies for testing.",
        "metadata": {
            "category": "Test"
        },
        "parameters": {
            "tagName": {
                "type": "String",
                "metadata": {
                    "displayName": "Tag Name",
                    "description": "Name of the tag, such as 'environment'"
                }
            },
            "tagValue": {
                "type": "String",
                "metadata": {
                    "displayName": "Tag Value",
                    "description": "Value of the tag, such as 'production'"
                }
            }
        },
        "policyDefinitions": [
            {
                "policyDefinitionId": "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000/providers/Microsoft.Authorization/policyDefinitions/requite-tag-and-its-value",
                "parameters": {
                    "tagName": {
                        "value": "[parameters('tagName')]"
                    },
                    "tagValue": {
                        "value": "[parameters('tagValue')]"
                    },
                    "effect": {
                        "value": "Deny"
                    }
                }
            }
        ]
    }
}
assign.testRG_testazurepolicyset.json
assign.testRG_testazurepolicyset.json
{
    "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-testazurepolicy/providers/Microsoft.Authorization/policyAssignments/ada0f4a34b09cf6ad704cc62",
    "type": "Microsoft.Authorization/policyAssignments",
    "name": "ada0f4a34b09cf6ad704cc62",     
    "properties": {
        "description": "This initiative audits the presence of a specific tag and its value.",
        "displayName": "Require a tag and its value",
        "parameters": {
            "tagName": {
              "value": "environment"
            },
            "tagValue": {
              "value": "production"
            }
          },
          "nonComplianceMessages": [
            {
              "message": "This resource is not compliant with the policy. Please apply the required tag and its value."
            }
          ],
          "enforcementMode": "Default",
          "policyDefinitionId": "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000/providers/Microsoft.Authorization/policySetDefinitions/requite-tag-and-its-value",
          "scope": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-testazurepolicy"
    }    
}

Conclusion

By incorporating the Manage Azure Policy action into your GitHub workflows, you can seamlessly enforce policies, maintain compliance, and ensure the robustness of your Azure resources, although it has its drawbacks, it is one more step compared to a portal. Later we will see the deployment with a more robust tool: EPAC

Learn more about Azure Policies and explore the action on the GitHub Marketplace.