Azure Bicep - Object reference not set to an instance - azure

I'm trying to create a simple App Service Plan with the below code.
param Location string = 'eastus'
resource appServicePlan1 'Microsoft.Web/serverfarms#2020-12-01' = {
name: 'myasp'
location: Location
sku: {
name: 'S1'
capacity: 1
}
}
Below is the Azure CLI command that I'm using to execute the above Bicep script
az deployment group create --name deploy1 --resource-group az-devops-eus-dev-rg1 --template-file main.bicep
Below is the screenshot
All this was working earlier. I'm using the latest version of Bicep (v0.9.1) which is available as of today.
Any pointers on why this is occurring now would be much appreciated.

Just had this issue in a MS workshop. We solved it by adding a empty properties-element to the appServicePlan. Ex.
param Location string = 'eastus'
resource appServicePlan1 'Microsoft.Web/serverfarms#2020-12-01' = {
name: 'myasp'
location: Location
properties: {}
sku: {
name: 'S1'
capacity: 1
}
}

Related

Azure B2C tenant deployment fails in Europe. Why?

I have this bicep file that deploys an Azure B2C tenant in location: 'Australia'
resource b2cDirectory 'Microsoft.AzureActiveDirectory/b2cDirectories#2021-04-01' = {
location: 'Australia'
name: 'tenantname1.onmicrosoft.com'
sku: {
name: 'PremiumP2'
tier: 'A0'
}
properties: {
createTenantProperties: {
countryCode: 'AU'
displayName: 'tenantname1 B1Cd223'
}
}
tags: {
Department: 'Dev'
}
}
This works fine. but it doesn't work for location: 'Europe' even though they say they support it.
This is the error I'm getting when I try to deploy this in location: 'Europe'.
Is this a temporary thing or am I missing something?
I tried in my environment and got below results:
Initially, I got same error in my environment.
{"status":"Failed","error":{"code":"Deployment Failed", "message":"Atleast one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-deployment-operations for usage details.","details":[{"code":"InternalSer verError", "message":"{\r\n"error"; {\r\n" "code":
"ResourceDeploymentFailure",\r\n"message": "The response for resou rce had empty or invalid content."\r\n }\r\n}"}]}}_
I tried with some changes in bicep code as below :
test.bicep:
resource b2cDirectory 'Microsoft.AzureActiveDirectory/b2cDirectories#2021-04-01' = {
location: 'europe'
name: 'demotenant326.onmicrosoft.com'
sku: {
name: 'Standard'
tier: 'A0'
}
properties: {
createTenantProperties: {
countryCode: 'DE'
displayName: 'demo1tenantv B1Cd223'
}
}
tags: {
Department: 'pro'
}
}
In the above bicep file I changed sku, country code = 'DE' indicates **Germany**and it deploys an Azure B2C tenant with location: 'europe' successfully.
Console:
New-AzResourceGroupDeployment -TemplateFile test.bicep -ResourceGroupName <your resource grp>
WARNING: /home/venkatesan/test.bicep(2,15) : Warning no-hardcoded-location: A resource location should not use a hard-coded string or variable value. Please use a parameter value, an expression, or the string 'global'. Found: 'europe' [https://aka.ms/bicep/linter/no-hardcoded-location]
DeploymentName : test
ResourceGroupName : <your resource grp>
ProvisioningState : Succeeded
Timestamp : 2/17/2023 8:08:56 AM
Mode : Incremental
TemplateLink :
Parameters :
Outputs :
DeploymentDebugLogLevel :
Reference:
Region availability and data residency - Azure AD B2C | Microsoft Learn

Bicep template for Azure SQL Serverless database

Is Azure SQL Serverless database implementation supported using Bicep? I haven't seen any Bicep examples of it on Web. Most of the examples are using ARM only and the reverse engineering of ARM to Bicep is not working for me. It is just giving internal server error with no more details. Does someone have any working example of it which can be used as a reference? Appreciate your help in advance!
Here is bicep file for reference.
param servername string = 'mysqlserver-1036050389'
param location string = 'centralus'
resource servername_resource 'Microsoft.Sql/servers#2022-05-01-preview' = {
name: servername
location: location
properties: {
administratorLogin: 'azureuser'
administratorLoginPassword: 'Bigambs123457'
version: '12.0'
publicNetworkAccess: 'Enabled'
restrictOutboundNetworkAccess: 'Disabled'
}
}
resource servername_mySampleDatabase 'Microsoft.Sql/servers/databases#2022-05-01-preview' = {
parent: servername_resource
name: 'mySampleDatabase'
location: location
sku: {
name: 'GP_S_Gen5'
tier: 'GeneralPurpose'
family: 'Gen5'
capacity: 2
}
kind: 'v12.0,user,vcore,serverless'
properties: {
collation: 'SQL_Latin1_General_CP1_CI_AS'
maxSizeBytes: 34359738368
catalogCollation: 'SQL_Latin1_General_CP1_CI_AS'
zoneRedundant: false
readScale: 'Disabled'
autoPauseDelay: 60
requestedBackupStorageRedundancy: 'Geo'
minCapacity: 2
isLedgerOn: false
}
}

Azure Bicep giving InvalidTemplateDeployment error for Azure App Service Plan deployment

I'm trying to create App Service Plan using Bicep. I've created a full blown bicep script for the development infra and it is working fine. But for production when I'm executing the app Service plan module, I'm receiving the below error. I've almost spent a day for troubleshooting this issue. The module was also having bicep for deploying and configuring App Services. But for troubleshooting I've removed it. Kindly help me in identifying this issue.
Main file
#allowed([
'aladdin'
])
#description('Environment Name')
param environmentPrefix string
#allowed([
'uat'
'prod'
])
#description('Environment Type')
param environmentType string
#allowed([
'P1V3'
'P2V3'
])
#description('App Services Plan SKU')
param appServicePlanSku string
var appRgName = 'rg-${environmentPrefix}-${environmentType}-ne-app01'
var appServicePlanName = 'asp-${environmentPrefix}-${environmentType}-ne-app01'
resource appResourceGroup 'Microsoft.Resources/resourceGroups#2021-04-01' = {
name: appRgName
location: location
tags: {
environmentType: environmentType
environmentPrefix: environmentPrefix
role: 'Azure PAAS resources'
}
}
module appServicePlan 'appServicePlan.bicep' = {
scope: appResourceGroup
name: 'appServicePlanModule'
params: {
appServicePlanName: appServicePlanName
appServicePlanSku: appServicePlanSku
location: location
}
}
Module
param appServicePlanSku string
param appServicePlanName string
param location string
resource appServicePlan 'Microsoft.Web/serverfarms#2022-03-01' = {
name: appServicePlanName
location: location
sku: {
name: appServicePlanSku
capacity: 1
}
kind: 'windows'
}
Execucted using PowerShell
New-AzSubscriptionDeployment `
-Name Production `
-Location northeurope `
-TemplateParameterFile "$biceptemplate\main.parameters.json" `
-TemplateFile "$biceptemplate\main.bicep" `
-environmentPrefix 'aladdin' `
-verbose
Error: Code=InvalidTemplateDeployment; Message=The template deployment 'Production' is not valid according to the validation procedure. The tracking id is ....
Try this for your module:
param appServicePlanSku string
param appServicePlanName string
param location string
resource appServicePlan 'Microsoft.Web/serverfarms#2022-03-01' = {
name: appServicePlanName
location: location
sku: {
name: appServicePlanSku
capacity: 1
}
kind: 'windows'
properties: {}
}
Supplying an empty properties object on the resource. It shouldn't be required but seems like it is in this case and bicep didn't flag it. (issue here)

How can I create a resource group and add a key vault to it using Bicep?

I'm trying to create a resource group and add a key vault to it.
However, I'm not able to set the new resource group as a target resource group for the key vault.
How can I have the key vault assigned to the newly created resource group without creating a second Bicep module for it?
var loc = 'westus'
// outputs the newly created resource group
module rgCreate 'test.rg.bicep' = {
scope: subscription()
name: 'rgCreate'
params: {
rgLocation: loc
}
}
resource keyVault 'Microsoft.KeyVault/vaults#2021-10-01' = {
name: 'Test'
location: loc
properties: {
enabledForTemplateDeployment: true
sku: {
family: 'A'
name: 'standard'
}
tenantId: tenant().tenantId
}
}
This is the workflow I'm aiming at:
First, if the resource group does not exist, you can't have targetScope = 'resourceGroup' in the main.bicep file. The command az deployment group create will fail:
{"code": "ResourceGroupNotFound", "message": "Resource group '' could not be found."}
You could always trigger the deployment form another resource that already exists (Not sure if it s a good idea tho).
An approach could be to have you main.bicep invoking two modules: one for resource group creation, one for resource creation:
// =========== rg.bicep ===========
// Setting target scope
targetScope = 'subscription'
param name string
param location string
// Creating resource group
resource rg 'Microsoft.Resources/resourceGroups#2021-01-01' = {
name: name
location: location
}
// =========== resources.bicep ===========
param location string = resourceGroup().location
param keyVaultName string
...
//Deploying key vault
resource keyVault 'Microsoft.KeyVault/vaults#2021-10-01' = {
name: keyVaultName
location: location
properties: {
enabledForTemplateDeployment: true
sku: {
family: 'A'
name: 'standard'
}
tenantId: tenant().tenantId
}
}
// Deploying other resources
...
// =========== main.bicep ===========
// Setting target scope
targetScope = 'subscription'
// Parameters
param rgName string = 'test-rg'
param rgLocation string = 'westus'
param keyVaultName string
...
// Creating resource group
module rgModule 'rg.bicep' = {
scope: subscription()
name: '${rgName}-create'
params:{
name: rgName
location: rgLocation
}
}
// Deploying resources in the newly created resource
module resources 'resources.bicep' = {
name: '${rgName}-resources-deployment'
scope: resourceGroup(rgName)
dependsOn: [ rgModule ]
params: {
location: rgLocation
keyVaultName: keyVaultName
...
}
}
To be honest, you could just run az group create command before deploying your template it will make things simpler.

Azure Bicep - Role assignment - Principal does not exist in the directory

I've created a Bicep template. In it I create a user-assigned identity and reference it in other resources like this
var identityName = 'mid-dd-test'
var roleName = 'TestRole'
var roleDescription = 'Some test'
var roleScopes = [
resourceGroup().id
]
var resolvedActions = [
'Microsoft.Resources/subscriptions/resourcegroups/*'
'Microsoft.Compute/sshPublicKeys/*'
]
var permittedDataActions = []
resource userId 'Microsoft.ManagedIdentity/userAssignedIdentities#2018-11-30' = {
name: identityName
location: resourceGroup().location
}
resource roleDef 'Microsoft.Authorization/roleDefinitions#2018-01-01-preview' = {
name: guid(subscription().id, 'bicep', 'dsadsd')
properties: {
roleName: roleName
description: roleDescription
type: 'customRole'
assignableScopes: roleScopes
permissions: [
{
actions: resolvedActions
dataActions: permittedDataActions
}
]
}
}
resource roles 'Microsoft.Authorization/roleAssignments#2018-09-01-preview' = {
name: guid(subscription().id, 'bicep-roleassignments', 'dsddsd')
properties: {
principalId: userId.properties.principalId
roleDefinitionId: roleDef.id
}
}
Whenever I deploy this I need 2 runs. The first run ends in the error message:
Principal XXX does not exist in the directory YYY
where XXX would be a principal id the user-assigned identity has and YYY is my tenant id. If I now look into the portal the identity is created and XXX is the correct id.
So when I now simply re-run the deployment it works.
I consider it a bug in dependsOn which should relate to ARM templates and not Bicep. I could not find any place where I can report ARM template issues to Microsoft.
I'm asking to assure that I do not miss something else here.
Edit: Added complete working sample which shows the bug. To use it, copy the script content into a test.bicep locally. Then create a resource group (lets call it "rg-test"), ensure that your local POSH context is set correctly and execute the following line in the folder where you stored the bicep in:
New-AzResourceGroupDeployment -Name deploy -Mode Incremental -TemplateFile .\test.bicep -ResourceGroupName rg-test
In the role assignment, you need to specify the principalType to ServicePrincipal and also use an api version greater or equal than: 2018-09-01-preview.
When you create a service principal, it is created in an Azure AD. It takes some time for the service principal to be replicated globally. By setting the principalType to ServicePrincipal, it tells the ARM API t0 wait for the replication.
resource roles 'Microsoft.Authorization/roleAssignments#2018-09-01-preview' = {
name: guid(subscription().id, 'bicep-roleassignments', 'dsddsd')
properties: {
principalId: userId.properties.principalId
roleDefinitionId: roleDef.id
principalType: 'ServicePrincipal'
}
}
You need to reference a newly created identity inside identity property of the target resource. dependsOn is redundant because bicep creates resources in the correct order based on actual usage:
resource userId 'Microsoft.ManagedIdentity/userAssignedIdentities#2018-11-30' = {
name: 'myidentity'
location: resourceGroup().location
}
resource appService 'Microsoft.Web/sites#2021-02-01' = {
name: 'appserviceName'
location: resourceGroup().location
properties: {
//...
}
identity: {
type: 'UserAssigned'
userAssignedIdentities: {
'/subscriptions/{your_subscription_id}/resourceGroups/${resourceGroup().name}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/${userId.name}': {}
}
}
}
The documentation doesn't recommend to use dependsOn without as strong reason:
In most cases, you can use a symbolic name to imply the
dependency between resources. If you find yourself setting explicit
dependencies, you should consider if there's a way to remove it.
So bicep does not require the dependsOn segment if referencing the property correctly.
Need to reference the properties.principalId of the userId in the resource block.
So would look like:
userId.properties.principalId
Here's a quickstart that calls out in a working example how this would work.

Resources