Exercise - Use Azure Resource Manager functions to create expressions

Completed

In this exercise, you create an expression by using Azure Resource Manager (ARM) template functions. The expression creates a unique name for each resource group by combining a prefix input with a hash of the resource group ID. It results in Azure storage account names like dev2hu6sbtr5 and staging5his8hgr67.

In this exercise, you use the Azure Resource Manager Tools for Visual Studio Code. Be sure to install this extension in Visual Studio Code.

Note

This exercise is optional. If you want to complete this exercise, you'll need to create an Azure subscription before you begin. If you don't have an Azure account or you don't want to create one at this time, you can read through the instructions so you understand the information that's being presented.

Note

In this unit, you use Azure Cloud Shell as a terminal. You can access Cloud Shell through the Azure portal or the Cloud Shell sign-in. You don't have to install anything on your PC or laptop to use it.

Note

You need to use a resource group to complete the steps in this exercise. You can use a resource group that you already created, or you can create a new resource group specifically for this exercise. If you choose to create a new resource group, that will make it easier to clean up any resources that you create as you complete the exercise. If you don't have an existing resource group or you want to create a new one specifically for this exercise, you can follow the steps in Use the Azure portal and Azure Resource Manager to manage resource groups to create a resource group by using the Azure portal, or you can follow the steps in Manage Azure resource groups by using Azure CLI to create a resource group by using the the Azure CLI.

Note

Throughout this exercise, replace myResourceGroupName in the examples with the name of an existing resource group, or the name of the resource group that you created for this exercise.

Create the ARM template file

In the previous module, you created an ARM template that deployed a storage account. You added parameters and an output to this file. Here, you start with that file, but the output is removed to reduce the overhead.

  1. Open Visual Studio Code and create a file called azuredeploy.json. If you have this file from the previous module, you can use that file.

  2. Replace the contents of the file with the following code:

    {
        "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
           "storageName": {
               "type": "string",
               "minLength": 3,
               "maxLength": 24
           },
            "storageSKU": {
                "type": "string",
                "defaultValue": "Standard_LRS",
                "allowedValues": [
                    "Standard_LRS",
                    "Standard_GRS",
                    "Standard_RAGRS",
                    "Standard_ZRS",
                    "Premium_LRS",
                    "Premium_ZRS",
                    "Standard_GZRS",
                    "Standard_RAGZRS"
                ]
            }
       },
        "functions": [],
        "variables": {},
        "resources": [{
            "name": "[parameters('storageName')]",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "tags": {
                "displayName": "[parameters('storageName')]"
            },
            "location": "[resourceGroup().location]",
            "kind": "StorageV2",
            "sku": {
             "name": "[parameters('storageSKU')]"
           }
        }],
         "outputs": {}
    }
    
  3. If you didn't complete the previous module, take a moment to review this file. Note the storageName parameter. This parameter is used to pass in a unique name for the storage account.

Create an expression to set a unique storage account name

Instead of passing in the name of the storage account, change the parameter to take a prefix for the storage account name. This parameter is passed to the concat function in your expression.

  1. In the parameters section, change storageName to storagePrefix.

  2. Change value of the maxLength: attribute of the storagePrefix parameter to 11. The maximum length for a storage account name is 24 characters, so you want to be sure the added hash from the function you create doesn't cause the name to be longer than 24.

  3. Create the expression to set the unique storage account name. In the resources section, change the values of the name: and displayName: attributes from "[parameters('storageName')]" to "[toLower(concat(parameters('storagePrefix'),uniqueString(resourceGroup().id)))]". You learned about this expression in the previous unit. The file should now look like this file:

    {
        "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
           "storagePrefix": {
               "type": "string",
               "minLength": 3,
               "maxLength": 11
           },
            "storageSKU": {
                "type": "string",
                "defaultValue": "Standard_LRS",
                "allowedValues": [
                    "Standard_LRS",
                    "Standard_GRS",
                    "Standard_RAGRS",
                    "Standard_ZRS",
                    "Premium_LRS",
                    "Premium_ZRS",
                    "Standard_GZRS",
                    "Standard_RAGZRS"
                ]
            }
       },
        "functions": [],
        "variables": {},
        "resources": [{
            "name": "[toLower(concat(parameters('storagePrefix'),uniqueString(resourceGroup().id)))]",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "tags": {
                "displayName": "[toLower(concat(parameters('storagePrefix'),uniqueString(resourceGroup().id)))]"
            },
            "location": "[resourceGroup().location]",
            "kind": "StorageV2",
            "sku": {
             "name": "[parameters('storageSKU')]"
           }
        }],
        "outputs": {}
    }
    

Deploy the ARM template to Azure

To deploy this template to Azure, you need to sign in to your Azure account from the Visual Studio Code terminal. Be sure you have the Azure CLI tools installed.

  1. Open a terminal window by using the Terminal menu.

  2. If the drop-down menu on the right side of the terminal window says bash, you have the right shell to work from. You can skip to the next section.

    A screenshot that shows the Visual Studio Code terminal window with bash in the drop-down menu.

  3. If you don't have the right shell, select Select Default Shell in the drop-down menu.

  4. Select bash:

    Screenshot that shows the select shell list in the Visual Studio Code terminal window.

  5. Select + in the terminal to create a new terminal with bash as the shell.

Sign in to Azure

  1. From the terminal in Visual Studio Code, run the following command to sign in to Azure. Running this command opens a browser that allows you to sign in to your account:

    az login
    
  2. After you're signed in, you see a list of the subscriptions associated with the account in the terminal.

  3. Set the default subscription for all the Azure CLI commands you run in this session. Replace My Subscription with the name of the Azure subscription you want to use for this exercise.

    az account set --subscription "My Subscription"
    

Set the default resource group

Run az configure to set the default resource group name. Doing so allows you to omit that parameter from the rest of the Azure CLI commands in this exercise. Replace myResourceGroupName with the name of an existing resource group, or the name of the resource group that you created for this exercise.

```azurecli
az configure --defaults group="myResourceGroupName"
```

Deploy the template to Azure

You learned about the deployment commands in the previous module. Here, we're using the Azure CLI az deployment group create command.

  • Deploy the template by using Azure CLI commands in the Visual Studio Code terminal. Remember to replace {your-prefix} with a different string. For example, you could use storage.

    templateFile="azuredeploy.json"
    today=$(date +"%d-%b-%Y")
    DeploymentName="addfunction-"$today
    
    az deployment group create \
      --name $DeploymentName \
      --template-file $templateFile \
      --parameters storagePrefix={your-prefix}
    

    In the first section of this code, you set Azure CLI variables for the path to the template file that you want to deploy and the name of the deployment. You then used the az deployment group create command to deploy the template to Azure.

    You should see the message Running... in the terminal.

To deploy this template to Azure, you need to sign in to your Azure account from the Visual Studio Code terminal. Be sure you have the Azure PowerShell tools installed.

  1. Open a terminal window by using the Terminal menu.

  2. If the drop-down menu on the right side of the terminal window says pwsh, you have the right shell to work from. You can skip to the next section.

    A screenshot that shows the Visual Studio Code terminal window with pwsh in the drop-down menu.

  3. If you don't have the right shell, select Select Default Shell in the drop-down menu.

  4. Select pwsh.

    Screenshot that shows the select shell list in the Visual Studio Code terminal window.

  5. Select + in the terminal to create a new terminal with pwsh as the shell.

Sign in to Azure by using Azure PowerShell

  1. From the terminal in Visual Studio Code, run the following command to sign in to Azure. When you run this command, you're prompted to open a browser to a URL that allows you to sign in to your account. Use the code that's in the prompt.

    Connect-AzAccount
    
  2. After you're signed in, you see a list of the subscriptions associated with the account in the terminal.

    Set the default subscription for all the Azure CLI commands you run in this session.

  3. Get the subscription ID. The command lists your subscriptions and their IDs. The subscription ID is the second column. Look for the subscription you want to use and copy the second column. It looks something like this: aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e.

    Get-AzSubscription
    
  4. Change your active subscription to the subscription you chose in the previous step. Be sure to replace {Your subscription ID} with the ID you copied.

    $context = Get-AzSubscription -SubscriptionId {Your subscription ID}
    Set-AzContext $context
    
  5. Set the default resource group. Doing so allows you to omit that parameter from the rest of the Azure PowerShell commands in this exercise.

    Set-AzDefault -ResourceGroupName myResourceGroupName
    

Deploy the template to Azure

You learned about the deployment commands in the previous module. Here, we're using the Azure PowerShell New-AzResourceGroupDeployment command.

  • Deploy the template by using Azure PowerShell commands in the Visual Studio Code terminal. Remember to replace {your-prefix} with a different string. For example, you could use storage.

    $templateFile = "azuredeploy.json"
    $today=Get-Date -Format "MM-dd-yyyy"
    $deploymentName="addfunction-"+"$today"
    New-AzResourceGroupDeployment `
      -Name $deploymentName `
      -TemplateFile $templateFile `
      -storagePrefix {your-prefix}
    

In the first section of this code, you set Azure PowerShell variables for the path to the template file that you want to deploy and the name of the deployment. You then used the New-AzResourceGroupDeployment command to deploy the template to Azure.

Check your deployment

When the deployment finishes, go to the Azure portal and make sure you're in the correct subscription. To check the subscription, select your avatar in the upper-right corner of the page. Select Switch directory. In the list, select the appropriate directory.

  1. In the left pane, select Resource groups.

  2. Select myResourceGroupName.

  3. In the Overview section, you see that one deployment succeeded:

    Screenshot of the Azure portal that shows the resource group overview. The Deployments section shows that one deployment succeeded.

  4. Select 1 Succeeded to see the details of the deployment:

    Screenshot of the Azure portal that shows deployments. One deployment is listed and has a status of Succeeded.

  5. Select addfunction to see what resources were deployed:

    Screenshot of the Azure portal that shows that the storage account deployed.

  6. Leave the page open in your browser so you can check on deployments again later in the module.