Cloud App Analyzer Azure onboarding script

This topic explains how to use an Azure shell script to automate the onboarding of a resource (subscription or management group) into the Cloud App Analyzerapplication. Each step of the script is outlined to help users understand its purpose and functionality.

This script enables you to onboard an Azure resource into Cloud App Analyzerefficiently. It performs tasks such as retrieving the Azure tenant ID, creating a service principal, assigning roles, and deploying necessary resources.

Script Sections

1. Retrieve Azure Tenant ID

Copy
out=$(az account show)
az_tenant=$(echo "$out" | jq -r '.tenantId')            

Purpose: Fetches the current Azure tenant ID, essential for identifying the Azure account in use. This ID is referenced in subsequent steps.

2. Display Target Resource Information

Copy
echo "Preparing to onboard the target resource [$TARGET_RESOURCE] of the Azure tenant ID [$az_tenant]"                

Purpose: Provides context and logs the target resource and tenant ID for easy tracking and audit purposes.

3. Create Service Principal for Prevasio Application

Copy
echo "Onboard Prevasio CSPM application"
az ad sp create --id $APP_ID 2>/dev/null                

Purpose: Attempts to create a service principal for the Prevasio CSPM application, allowing it to interact with Azure resources.

4. Assign Roles to the Target Resource

Copy
roles=('Log Analytics Reader' 'AcrPull' 'AcrPush' 'Key Vault Reader' 'Azure Kubernetes Service Cluster User Role')
for role in "${roles[@]}"; do
    echo "Assign role [$role] to the target [$TARGET_RESOURCE]"
    az role assignment create --role "$role" --assignee $APP_ID --scope TARGET_RESOURCE >/dev/null
    if [ $? -ne 0 ]; then
            echo "ERROR: The target resource [$TARGET_RESOURCE] wasn't found or the user has no permission to work with it"
            exit 1
    fi
done                

Purpose: Assigns a set of predefined roles to the Prevasio CSPM application, granting it necessary permissions on the target resource.

5. Deploy Code to the Subscription

Copy
deploy_code_to_subscription() {
    # Block for onboarding a specific Azure subscription
}                

Purpose: Handles resource deployment and role assignments for a specific Azure subscription. Includes conditional logic for resource group creation or reuse based on hash values.

6. Key steps inside the function

Determine if resource group should be dropped:

Copy
should_drop_rg=true
    prevasio_hash="${HASHES[$1]}"
    if [ -z "$prevasio_hash" ]; then
        should_drop_rg=false
        prevasio_hash=$(echo $RANDOM | md5sum | head -c 5)
    elif [ "$prevasio_md5" == "$CURRENT_PREVASIO_RESOURCES_MD5" ]; then
        echo "The current onboarding is up to date. Skipping the resources creation."
        return
fi                

Purpose: Check whether a new resource group should be created or the existing one reused based on the hash values ($HASHES and $MD5S).

Set the Azure subscription:

Copy
    az account set --subscription $1                

If needed, delete existing resource group and Key Vault:

Copy
if $should_drop_rg ; then
    echo "Deleting resource group prevasio-$prevasio_hash-resource-group in $1 subscription..."
    az group delete --name prevasio-$prevasio_hash-resource-group --yes > /dev/null
    az keyvault purge --name prevasio-$prevasio_hash-keyvault --location $REGION > /dev/null
fi                

Purpose: If a previous onboarding exists, the old resource group and Key Vault are deleted to avoid conflicts.

Create new resources:

Copy
    az group create --name prevasio-$prevasio_hash-resource-group --location $REGION
    az deployment group create --resource-group prevasio-$prevasio_hash-resource-group --template-file template.json --parameters parameters.json            

Create new custom role:

Copy
echo "Assigning roles to application  in $1 subscription..."
    echo '{
            "Name": "Prevasio Application Role ('$prevasio_hash')",
            "IsCustom": true,
            "Description": "Allows to create EventGrid subscriptions for ACR registries events.",
            "Actions": [
              "Microsoft.EventGrid/eventSubscriptions/read",
              "Microsoft.ContainerRegistry/registries/read",
              "Microsoft.EventGrid/eventSubscriptions/write",
              "Microsoft.Web/sites/functions/write"
            ],
            "NotActions": [],
            "DataActions": [],
            "NotDataActions": [],
            "AssignableScopes": [
              "/subscriptions/'$1'"
            ]
          }' > ./role_def.json
    role_creation_response=$(az role definition create --role-definition role_def.json)

Assign new custom role:

Copy
generated_role_name=$(echo $role_creation_response | jq -r '.name')
az role assignment create --assignee $(az ad sp list --display-name prevasio-$prevasio_hash-application --query [].id --output tsv) --role $generated_role_name --scope /subscriptions/$1 > /dev/null

Notify Prevasio API of the onboarding:

Copy
    response=$(curl -X POST "$(echo $INPUT | jq -r '.url')/onboard" ...                

7. Create New Resources and Assign Roles

Copy
                    az group create --name prevasio-$prevasio_hash-resource-group --location $REGION
                    az deployment group create --resource-group prevasio-$prevasio_hash-resource-group --template-file template.json --parameters parameters.json                

Purpose: Creates new resource groups and deploys the required resources, then assigns the Contributor role to the Prevasio service principal.

8. Download and Unpack Application Sources

Copy
mkdir prevasio-onboarding
cd prevasio-onboarding
wget -O sources.zip $SOURCES_URL
unzip sources.zip                

Purpose: Downloads and unpacks application source files, preparing for deployment.

9. Deploy to Target Resource (Subscription or Management Group)

Copy
if [[ $TARGET_RESOURCE == /subscriptions/* ]]; then
    deploy_code_to_subscription $TARGET_ID
elif [[ $TARGET_RESOURCE == /providers/Microsoft.Management/managementGroups/* ]]; then
    subscriptions_json=$(az account management-group subscription show-sub-under-mg --name $TARGET_ID)
    for subscription in $(echo "${subscriptions_json}" | jq -r '.[].name'); do
        deploy_code_to_subscription $subscription
    done
fi                

Purpose: Based on the target resource type, deploys code either to a single subscription or iterates through subscriptions within a management group.

10. Notify Prevasio API of Onboarding Completion

Copy
response=$(curl -X POST "$(echo $INPUT | jq -r '.url')/onboard" ...                

Purpose: Notifies the Prevasio API, indicating that the onboarding process has completed successfully.

Summary

The Azure onboarding script automates provisioning, role assignment, and reporting for Prevasio CSPM. This script is essential for setting up resources and roles in a streamlined and controlled manner, ultimately enhancing security posture through automation.