2 Writing your first ARM template

This chapter covers

  • Writing your first ARM template
  • Using VS Code to write and validate templates
  • Deploying a template using the Azure portal
  • Creating a visual representation of your template

With the theory covered, it’s time to write your first ARM template. While writing ARM templates may seem like a tough job at first, you’ll get the hang of it soon enough. Experience shows that it takes most people one or two days of practice to get familiar with the syntax.

Getting started is easier when you use the right tools for the job. ARM templates are written as JSON documents, so a powerful text editor is recommended. For ARM templates specifically, Visual Studio Code (VS Code) is the best choice. VS Code is not only a powerful text editor, but there is an extension that supports writing ARM templates. This chapter will help you set up VS Code and the extension.

When writing ARM templates, you need to be at least somewhat familiar with the infrastructure you want to create. For example, in this chapter, you will deploy an Azure storage account. Storage accounts are, amongst other things, used for storing files, often referred to as binary large objects (BLOBs). In Azure, the storage account is called a resource type, of which you can create instances. When you create an instance of a storage account, that storage account is called a resource. A storage account is one of many resource types available in Microsoft Azure.

One reference you can use when writing ARM templates is the Microsoft Docs website. The Azure templates section contains a list of all resource types you can deploy using the Azure Resource Manager, and it’s available at https://docs.microsoft.com/azure/templates. Besides listing all the resource types, you can find the allowed properties for each resource type, whether they are mandatory or not, and the type of each property. In this chapter, you’ll learn how to use that reference for storage accounts.

To help you prepare for the remainder of this chapter, the next section explains JSON and how to configure your working environment by installing VS Code and the ARM Tools extension for VS Code.

2.1 Working with JSON files

As you learned in chapter 1, ARM templates are JSON files that describe the infrastructure you need in a formal format. JSON stands for JavaScript Object Notation, and it’s a structured but lightweight text format for describing information. This section will briefly introduce JSON—if you already know JSON, you can skip ahead to section 2.1.1.

A valid JSON file or snippet has to evaluate to a value. The following example shows a valid JSON object that explains its own syntax.

{
    "string": "Text is started and ended using double quotes",
    "thisIsANumberProperty": 4,
    "thisIsABooleanProperty": true,
    "thisIsANotSetOrMissingProperty": null,
    "thisIsAnArray": [
        "Square brackets are used for arrays",
        "Curly braces are used for objects",
        "Property names are quoted, as they are also of type string"
    ]
}

A value can be of any of the following six types: string, number, Boolean, null, array, or object. Four of these six are primitive data types: string (text), number (integer or decimal), boolean (true or false), and null (nothing). Null is used for an empty or non-existing value and is not the same as the value zero. Besides these primitive types, JSON has support for arrays and objects. An array is an unordered list of elements, whereas an object is a collection of name/value pairs, and such a pair is often called a property.

This should be enough of an introduction to JSON for this book, which discusses ARM templates at length. If you want to dive deeper into JSON, you can look at the formal JSON specification at www.json.org. There you’ll also find illustrations that describe the makeup of JSON in more detail, as well as links to libraries for working with JSON in many programming languages.

2.1.1 Installing the ARM templates extension in VS Code

When you start working with ARM templates or JSON files in general, you’ll find that a good text editor is indispensable. For ARM templates, VS Code is highly recommended, not only because it has built-in support for editing JSON, but also because it has extensions that support writing ARM templates. You can download VS Code from https://code.visualstudio.com if you do not have it installed yet.

After installing and starting VS Code, the window in figure 2.1 should be displayed. Here you see VS Code’s default editing window that is used throughout this chapter.

Figure 2.1 VS Code; the arrow points out the icon for managing extensions

Before you get started, you should install the ARM template extension. To do this, follow these steps:

  1. Click on the Extensions icon (marked with an arrow in figure 2.1) to navigate to the extensions view.

  2. In the search box that appears, search for “Azure Resource Manager”.

  3. Select the extension named Azure Resource Manager (ARM) Tools, published by Microsoft. It may appear confusing that the version number is lower than 1 (0.15.5 at the time of writing), but this is perfectly fine.

  4. In the window that opens on the right, click Install.

You should now have both VS Code and the ARM template extension installed. It is time to start writing your first ARM template from scratch.

2.2 Writing ARM templates in VS Code

Let’s imagine you’re employed by a small company that works with large amounts of data, such as images or video files. These files consume a lot of storage, and you are running out of on-premises storage. As your company is already using some Azure capabilities, you are responsible for creating an Azure storage account where you and your colleagues can store more files in the future. To prepare for future changes and leverage the benefits of IaC, you decide to complete this task using an ARM template.

To start writing that template, first open VS Code. A welcome screen will open. Press Ctrl-N to open a new file. To ensure that the ARM Tools extension starts, save the file under the name azuredeploy.json. You can use any filename with an extension of .json, and the ARM Tools extension should start.

Fixing extension problems

Sometimes the ARM Tools extension does not start properly when it has just been installed in VS Code. To solve this problem, save your file, close and reopen your ARM template JSON file, and the extension will initialize properly.

Start writing your first ARM template by typing arm! at the beginning of the file. This notation is a shortcut that triggers the ARM Tools extension in VS Code. When you press Enter, the extension will insert a predefined piece of code called a snippet. In this case, you should see a snippet like this:

{
    "$schema": "https:/ /schema.management.azure.com/schemas/
         2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {},
    "functions": [],
    "variables": {},
    "resources": [],
    "outputs": {}
}

Every ARM template must be a valid JSON object. This snippet contains all the top-level properties that are available for you to use.

The first property of this object, called $schema, is always a reference to the JSON Schema for ARM templates. JSON Schema is a formal notation for describing the structure of the content in this file. The specified URL is valid, and you can copy it into your browser to read the specification, but JSON Schemas are difficult to read. They are only used by tools to validate JSON files against the specified schema. Specifying the JSON Schema is mandatory in ARM templates, but you don’t need to understand its details. The date you see as part of the URL serves as the version number, which may change as newer versions of the schema become available.

The second property specifies what is called the contentVersion. Here you can use a four-part version number for the template. This version is not used by ARM in any way, and if you choose to version your templates, you can follow any system you like. The contentVersion property is optional.

After these two properties, the five properties that make up the main template follow. For now, we will not use the parameters, functions, variables, and outputs properties, so you can remove these four lines to keep your first template simple and easy to understand. This leaves you with an empty shell to which you can add your first Azure resource.

2.2.1 Adding a resource

In most ARM templates, the resources property makes up the majority of the template. The resources property is an array, which allows you to specify any number of resources within a single template. Each resource is declared as a JSON object.

To declare a resource, navigate your cursor between the two square brackets that make up the still-empty resources array, and press Enter to create some whitespace. ARM templates are not whitespace-sensitive, and this includes line breaks. Whitespace can be anywhere that it is convenient for readability.

Note When typing in VS Code, you can at all times press the Ctrl-. (Ctrl and a period) key combination to invoke VS Code autocomplete and see context-based suggestions.

Next, type arm-storage and watch how the ARM Tools extension pops up with a list of snippet suggestions. While you type, the list will continue to filter, showing only snippets that match what you have typed so far. When “arm-storage” is at the top, press the Tab key to accept the snippet and insert the ARM template snippet for creating a storage account. This snippet contains all the mandatory properties for creating an Azure storage account.

Observe how the extension automatically highlights all the properties for which a value is required. First, it selects the value for the new resource’s name property in all locations where it appears. Give your resource a more meaningful name and press Tab again. The cursor will move to the next property.

In this case, updating the other properties is unnecessary, so keep pressing Tab until the cursor stops moving through them. With all the properties filled in, let’s explore them in turn.

  • name—Every Azure resource has a mandatory name. The naming rules are different for every type of resource, and most names must be globally unique.

  • type—This property specifies the type of resource you want to create. The resource type consists of multiple parts separated by slashes. In chapter 3, you’ll learn more about the makeup of resource types.

  • apiVersion—This property specifies which version of the resource type you want to use.

The combination of the resource type and API version determines which other properties are available to describe the resource. You can find these in the documentation at https://docs.microsoft.com/azure/templates (see figure 2.2). Look up Storage > Storage Accounts in the tree on the left. Next, in the drop-down list at the top, select the correct version of the resource or leave it at the default of Latest. The remainder of the page shows an example resource declaration followed by documentation for every property. If you have followed along with this example, your ARM template should now look like listing 2.1.

Figure 2.2 Finding resource properties using the ARM template reference

Listing 2.1 Your first ARM template

{
    "$schema": "https:/ /schema.management.azure.com/schemas/2019-04-
         01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
        {
            "name": "storage20201227",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2021-04-01",
            "tags": {
                "displayName": "storage20201227"
            },
            "location": "[resourceGroup().location]",
            "kind": "StorageV2",
            "sku": {
                "name": "Premium_LRS",
                "tier": "Premium"
            }
        }   
 
    ]
}

Congratulations! That’s it. You have just successfully created your first ARM template, ready for deployment. But before you deploy it, let’s first explore VS Code and see how it can help you write templates a bit more.

2.2.2 Leveraging IntelliSense in VS Code

So far you have used code snippets in VS Code to write a template quickly and have most of it generated automatically. But these code snippets only generate the required properties. When you need to configure optional properties, you have to add them manually. When you’re adding these properties, the ARM Tools extension helps by popping up suggestions.

For storage accounts, it is possible to enforce HTTPS while connecting to the storage account. Using HTTPS is a general recommendation in our field, so let’s enable this on our resource by setting the supportsHttpsTrafficOnly property to true. This property has to be nested in another object, called properties.

Note Many Azure resources have most or all of their extra properties grouped within another object. This object is then used as the value for a property called properties.

To make this change, scroll down to the bottom of your template and add a new property at the end of the resource: add a comma, and start typing properties. As soon as you have typed the p, the suggestion for properties should already pop up. Just pressing Tab will complete the entry. Continue by typing a colon and then “This is a mistake”. Once you have done this, hover over properties with your mouse, and your editor will show something like figure 2.3.

Figure 2.3 A validation error in VS Code

In figure 2.3, you can see that the editor not only automatically completes the entries you are making, but it also continuously validates the template and provides you with feedback when there are any errors. In this case, the error is that the properties property should not be of type string, but of type object. Replacing the text and the enclosing quotes with curly brackets, {}, removes the error.

Within the curly brackets, press Enter and start typing supportsHttpsTrafficOnly to invoke autocomplete again, and add the property. The value of this property should be true.

After making these changes, your template should look like the following listing.

Listing 2.2 Complete ARM template

{
    "$schema": "https:/ /schema.management.azure.com/schemas/2019-04-
         01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
        {
            "name": "storage20201227",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "tags": {
                "displayName": "storage20201227"
            },
            "location": "[resourceGroup().location]",
            "kind": "StorageV2",
            "sku": {
                "name": "Premium_LRS",
                "tier": "Premium"
            },
            "properties": {
                "supportsHttpsTrafficOnly": true
            }
        }   
 
    ]
}

You’ve now completed an ARM template for deploying a storage account in Azure. But writing templates doesn’t deliver value unless you deploy them. So let’s go and deploy this template!

2.3 Deploying an ARM template

There are quite a few ways of deploying an ARM template, and chapter 4 will discuss their pros and cons in detail. For now, you can deploy your template manually from the Azure portal.

First, navigate to the Azure portal (https://portal.azure.com) and log in. As soon as you have logged in, click the Create a Resource button. This will open a new view with a search bar at the top. Here, search for “Template Deployment (deploy using custom templates)” and select it. This type of resource allows you to deploy the ARM template you created in the previous section. Once it’s selected, click the Create button to proceed—this should open a new view very similar to figure 2.4.

Figure 2.4 Creating a custom deployment in the Azure portal

In this view, you can open an online editor by clicking Build Your Own Template in the Editor. Once the editor is open, copy your template into the online editor and click Save. Saving closes the editor, and you’ll see a new view where you can select or create the resource group to which you want to deploy the template. Create a new resource group with a name that’s easy to remember.

Note In Azure, every resource is part of a resource group, which is a logical grouping of resources. You can decide what a logical grouping of resources is, based on the requirements of your work. Chapter 4 will discuss resource groups and other ways of grouping your resources into a hierarchy.

To start the deployment of your template, click the Review + Create button. The Azure Resource Manager will first validate your template. Validation is performed on the structure, syntax, validity of names and properties, and much more. Once the validation is complete, click the button again, now titled Create.

Within a few seconds of starting the deployment, the portal will navigate to a new blade (a new view in the Azure portal) where you can see your template’s deployment status. Storage accounts provision quite quickly, and within a minute you should see a message telling you that your deployment is complete. You can now click Go to Resource and work with the storage account in Azure.

Managing costs in Azure

You may want to try and test ARM templates or snippets published in this book. Please note that creating ARM deployments does create actual resources in the Azure cloud for which you may be charged. It’s a good idea to remove resources from Azure that you are not actually using, to reduce costs.

You have now successfully deployed your first ARM template into Azure. It may not feel like much of an improvement over manual deployments yet, but that’s because you have just deployed one resource so far. If you wanted, you could deploy tens or even hundreds of resources using the same steps, taking no extra time. In the remainder of this book, you’ll learn how to reuse your ARM templates to improve the speed of deployments.

Another benefit of deploying resources using ARM templates is that ARM allows you to view a list of all your recent deployments and how they went. The next section discusses monitoring deployments that way.

2.4 Monitoring template deployments

In the previous section, you used the Azure portal for deploying an ARM template, which provides good visibility into how your deployment is going. When you deploy using other means, progress reports might be missing or unclear, or might not provide enough information for troubleshooting. For this reason, monitoring the progress of deployments is one reason you might keep returning to the Azure portal, even when practicing IaC.

You can use the list of deployments in the Azure portal to monitor the status of your running or previously run deployments. You can find this list by navigating to any resource group in the portal and selecting the Deployments blade on the left (see figure 2.5).

Figure 2.5 For each resource group, recent deployments are listed in the Deployments blade.

The Deployment blade shows your most recent 800 deployments. Clicking the name of any deployment allows you to drill down to a list of all resources created, updated, or deleted. And if your deployment failed, this overview also displays any errors encountered, grouped by the resources involved.

Now that you have written and deployed a template once, it is time to pick up the pace a bit and play with deploying pre-existing templates. In the next section, you’ll learn how to find example templates on the Microsoft Docs website and deploy them directly to your Azure environment.

2.5 Finding example templates

If you’re working with VS Code and the ARM Tools extension, writing ARM templates from scratch will becomes easier over time. Still, it might be helpful to start out by editing examples to fit your own needs, instead of writing templates from scratch.

The Microsoft Docs website (https://docs.microsoft.com/azure/templates) contains full documentation of all the resources you can describe using IaC. This is a good source of documentation and examples. Another source of many examples is the Azure Quickstart Templates GitHub repository at https://github.com/Azure/azure-quickstart-templates. Microsoft owns this repository and continuously updates it with new and updated examples. The repository contains hundreds of folders, each detailing a single example, as shown in figure 2.6.

Figure 2.6 Quickstart ARM templates on GitHub

Every example is in a separate folder with a descriptive name, and each folder contains a file called azuredeploy.json that contains the ARM template itself. Each example also contains a description and provides a button to deploy it directly to Azure. Clicking this button sets up a new Template Deployment, as you did when working along with section 2.3.

Each example also features a Visualize button, which opens a visualization of the template to show the Azure resources that are in the template.

The next section explores an extra benefit of IaC: other tools that can also parse and work with ARM templates.

2.6 Visualizing templates

You have created and deployed your first ARM template, and while you have only deployed a single resource yourself, you have probably already speculated that ARM templates can rapidly increase in size. And yes, ARM templates for real-world Azure environments can be hundreds or even thousands of lines of JSON long. Visualizing your ARM template can help you get a better overview of its content and can remove the need to draw these images manually as part of your documentation efforts.

The Azure portal provides an easy way to visualize the content of a resource group. Navigate to the resource group and click Resource Visualizer to get an overview of the contents of your resource group (see figure 2.7). This doesn’t, however, visualize your template. If you want to visualize an ARM template, you can use the ARMVIZ website.

Figure 2.7 Visualizing the content of a resource group

ARMVIZ is an easy-to-use online tool for visualizing ARM templates. It is also the tool used by Microsoft itself for its examples on GitHub. To use ARMVIZ to visualize your own ARM templates, navigate to http://armviz.io to start the tool. By default, a graphic model of a random template is generated, as shown in figure 2.8. Here you see each resource’s name, an icon representing the resource’s type, and lines representing the dependencies between resources.

Figure 2.8 A visual representation of an ARM template

If you click the view-source button (marked with an arrow in figure 2.8), you can see the ARM template that is the diagram’s source. The template is opened in an online editor where you can edit the template in place or paste in any template of your own. Using the other button on the left (the eye button), you can switch back to the visual representation.

The ARM Template Viewer, a VS Code extension written by Ben Coleman, does the same thing within your VS Code environment. Once it’s installed, the extension appears as an eye icon in the upper-right corner of VS Code when you open an ARM template file. When you click the eye icon, the screen changes into a split view, and any change you make to the ARM template is immediately reflected in the visual representation.

Summary

  • ARM templates are written as JSON documents.

  • VS Code is a text editor, and an extension is available that supports writing ARM templates.

  • ARM templates may be composed largely of the resources property, which is an array that specifies any number of resources within a single template.

  • Templates can be deployed manually by using the Azure portal.

  • During deployment, the Azure Resource Manager validates the template, including structure, syntax, names, properties, and more.

  • Azure portal allows you to monitor the progress of your deployments.

  • It can be helpful to edit existing ARM templates when you’re starting to learn to write them. The Azure Quickstart Templates GitHub repository is a good source of quality examples.

  • Azure portal provides a resource visualizer that provides a visual representation of your resource group, so you can see a visual representation of the resources described in a resource group.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset