Azure Terraform Configuration for Snapshot-based Scan

The Qualys Terraform configuration for Azure deploys the resources required for Qualys CSPM (TotalCloud) and, optionally, FlexScan (Zero-touch Snapshot-based Scan). CSPM is always deployed. FlexScan is deployed only when the deploy_flexscan flag is set to true.

Use this topic to prepare your Azure Service Account subscription before you register it as a Service Account for snapshot-based scanning. For the end-to-end workflow, refer to Configure Azure Snapshot-based Scan Using Terraform and FlexScan APIs.

Overview

The configuration contains the following modules:

Module Description Deployed
cspm Creates the Qualys service principal and grants tenant-level read roles for asset inventory. Always
flexscan Registers the required resource providers on the service subscription, creates the snapshot scanner role, and grants snapshot access on the target scope. When deploy_flexscan = true

Architecture

The following diagram shows the role definitions, role assignments, and resources that the configuration creates.

Tenant Root Management Group (resolved from az account)
 │
 ├── Role Definition: qualys_cspm_role               ← CSPM: read management group hierarchy
 ├── Role Definition: qualys_snapshot_scanner_role   ← FlexScan: discover and snapshot VMs
 │
 ├── Role Assignment: qualys-cspm-read-only SP → Reader
 ├── Role Assignment: qualys-cspm-read-only SP → qualys_cspm_role
 │
 └── FlexScan target scope(s)  ← tenant root MG by default,
     │                            or target_management_groups / target_subscriptions
     ├── Role Assignment: qualys-cspm-read-only SP → qualys_snapshot_scanner_role
     └── Role Assignment: qualys-cspm-read-only SP → Key Vault Crypto User

Azure Subscription (var.subscription_id)
 └── Resource Group: qualys-snapshot-scanner  (var.resource_group)
      └── Managed Identity: qualys-flexscan-identity  (shared by scanner VMs and Function App)
           Roles at resource group: Contributor, Storage Blob Data Contributor,
                                    Key Vault Crypto User, Key Vault Secrets User

File Structure

azure/terraform/
├── main.tf                     # Root module — invokes cspm + flexscan, cross-module role assignments
├── variables.tf                # Root variable definitions
├── outputs.tf                  # Root outputs
├── provider.tf                 # Provider and version constraints
├── terraform.tfvars.example    # Example variable values (copy to terraform.tfvars)
├── sync_terraform_state.sh     # One-time migration script (state rm + import) — bash/Git Bash/WSL
├── sync_terraform_state.ps1    # Same migration script — native PowerShell (Windows)
├── cspm/
│   ├── main.tf                 # CSPM resources
│   ├── variables.tf
│   └── outputs.tf
└── flexscan/
    ├── main.tf                 # FlexScan resources
    ├── variables.tf
    ├── outputs.tf
    └── policies/
        ├── targetAccountPermissions.json         # Actions for qualys_snapshot_scanner_role
        ├── serviceAccountResourceProviders.json  # Resource providers to register (service subscription)
        └── targetAccountResourceProviders.json   # Resource providers to register (target accounts)

Prerequisites

  • The Qualys Terraform package for Azure (terraform.zip). Contact Qualys Support or your Technical Account Manager (TAM) to obtain the package.
  • Terraform version 1.3.0 or later.
  • Azure credentials configured through a service principal, a managed identity, or az login.

    The Azure CLI is required only for authentication. It is not required while terraform apply runs.

  • The Azure identity that runs Terraform must have permissions to:
    • Create Microsoft Entra ID (Azure AD) applications and service principals.
    • Create and manage custom role definitions at management group scope.
    • Create and manage user-assigned managed identities.
    • Create resource groups and register resource providers.
    • Create role assignments at subscription and management group scope.

Variables

Deployment Flags

Variable Type Default Description
deploy_flexscan bool true Deploys the FlexScan snapshot-based scan resources. CSPM is always deployed. If you initially deployed CSPM only, you can later set this flag to true and apply the configuration again.

FlexScan Variables

Variable Type Default Description
subscription_id string "" (uses the active az account) Azure subscription ID where the CSPM service principal is created and the FlexScan resources are deployed. Required when deploy_flexscan = true.
location string "" Azure region, for example, eastus. Required when deploy_flexscan = true.
target_management_groups list(string) [] Management group IDs to which the FlexScan target role assignment is scoped. If empty, the tenant root management group (tenant-wide) is used.
target_subscriptions list(string) [] Subscription IDs to which the FlexScan target role assignment is scoped. If empty, the tenant root management group (tenant-wide) is used.

Deployment Scenarios

CSPM Only

# terraform.tfvars
deploy_flexscan = false

CSPM and FlexScan

# terraform.tfvars
deploy_flexscan = true
subscription_id = "<your_subscription_id>"
location        = "eastus"

FlexScan with a Scoped Target Role

By default, the FlexScan target role assignments are applied at the tenant root management group. To limit them to specific management groups or subscriptions, set one or both of the following lists:

# Scope to management groups
target_management_groups = ["MG1", "MG2"]

# Scope to subscriptions
target_subscriptions = ["sub1", "sub2"]

Deploy the Configuration

Perform the following steps to deploy CSPM and FlexScan:

  1. Extract the Terraform package and navigate to the azure/terraform folder.
  2. Copy the example variables file:
    cp terraform.tfvars.example terraform.tfvars
  3. Edit terraform.tfvars. At a minimum, set subscription_id and location.
    • For CSPM only, set deploy_flexscan = false.
    • For CSPM and FlexScan, set deploy_flexscan = true.
  4. Initialize, review, and apply the configuration:
    terraform init
    terraform plan -var-file="terraform.tfvars"
    terraform apply -var-file="terraform.tfvars"

Scope the FlexScan Target Role and Key Vault Crypto User Assignments

By default, the FlexScan target role (qualys_snapshot_scanner_role) and the Key Vault Crypto User role are assigned at the tenant root management group (tenant-wide). To limit the assignments, set one or both lists. You can use both lists together.

# terraform.tfvars
target_management_groups = ["mg-platform", "mg-workloads"]
target_subscriptions     = ["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"]

The qualys_snapshot_scanner_role definition is still created at the tenant root management group so that it remains assignable at any child scope. Only the role assignments are narrowed.

Update Permissions

To update the permissions, modify the appropriate JSON file in the flexscan/policies/ folder and run terraform apply again. Terraform updates the role definition in place.

Migrate from a Previous Deployment

If this configuration was previously applied using the null_resource and Azure CLI pattern, run the migration script once before you run terraform apply. The script removes the old null_resource state entries without triggering destroy provisioners, and imports all existing Azure resources under their new native Terraform addresses.

macOS, Linux, Git Bash, or WSL

bash sync_terraform_state.sh
# Then verify:
terraform plan -var-file="terraform.tfvars"
# Expected: no changes

Windows (native PowerShell)

./sync_terraform_state.ps1
# Then verify:
terraform plan -var-file="terraform.tfvars"
# Expected: no changes

Both scripts perform the same actions. Native PowerShell and cmd.exe cannot run sync_terraform_state.sh directly. Use sync_terraform_state.ps1, or run the .sh script from Git Bash or WSL using bash sync_terraform_state.sh. This also works from a PowerShell prompt if the Git for Windows bash.exe is on your PATH.

Import Pre-existing Resources

If any resource was created outside Terraform, import it before you apply the configuration to avoid conflicts.

Resource group

terraform import 'module.flexscan[0].azurerm_resource_group.flexscan[0]' \
  /subscriptions/<sub-id>/resourceGroups/<rg-name>

Managed identity

terraform import 'module.flexscan[0].azurerm_user_assigned_identity.flexscan_identity[0]' \
  /subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/qualys-flexscan-identity

Custom role definitions

# Get the role definition resource ID first:
ROLE_DEF_ID=$(az role definition list --name "qualys_cspm_role" --query "[0].id" -o tsv)
MG_SCOPE="/providers/Microsoft.Management/managementGroups/<tenant-id>"

terraform import 'module.cspm.azurerm_role_definition.custom_role' \
  "${ROLE_DEF_ID}|${MG_SCOPE}"

ROLE_DEF_ID=$(az role definition list --name "qualys_snapshot_scanner_role" --query "[0].id" -o tsv)
terraform import 'module.flexscan[0].azurerm_role_definition.flexscan_target_role[0]' \
  "${ROLE_DEF_ID}|${MG_SCOPE}"

Troubleshooting

Error Cause Resolution
AADSTS50173 (grant expired or token revoked) The cached Azure CLI credentials are stale. Run az logout, then az login --tenant <tenant-id>, and run Terraform again.
AuthorizationFailed on role definition The caller does not have Microsoft.Authorization/roleDefinitions/write at management group scope. Assign the Owner or User Access Administrator role at the management group.
RoleDefinitionWithSameNameExists The custom role exists outside the Terraform state. Run sync_terraform_state.sh (or sync_terraform_state.ps1 on Windows), or import the role manually.
PrincipalNotFound Identity replication is delayed after creation. Wait approximately 30 seconds and apply the configuration again.
InvalidAssignableScopes The tenant ID is incorrect, or the caller does not have access to the root management group. Verify the tenant ID using az account show --query tenantId -o tsv.
ResourceNotFound on provider registration The provider namespace casing does not match. Check the namespace spelling in serviceAccountResourceProviders.json.

Connector Credentials

  • If a new App Registration is created, its credentials are required to create the connector.
  • The credentials associated with the service subscription can be used to create a connector for the target subscription.

References