Categories
Azure Azure DevOps

Getting started with Azure Bicep

Bicep is a new language from Microsoft that allows you to easily specify your Azure infrastructure as code.

It’s an improvement on writing Azure Resource Manager (ARM) templates directly by better supporting features such as type safety and code modularity and reuse.

That said, Bicep still has a very close relationship with ARM templates. In fact, it’s an abstraction over ARM templates with templates written using Bicep able to be transpiled back to ARM templates. And if you have a bunch of existing ARM templates, they can be transpiled and converted into Bicep files.

Let’s now take a look at how you can get started using Bicep.

Preparing your environment

There’s a few things you’ll want to install in order to start using Bicep.

First you’ll want to download Visual Studio Code (free) and install the Bicep extension (also free). This will give you an editor in which to write your Bicep files, and the extension adds handy features such as Intellisense code suggestions and template validation to ensure the correct syntax.

You’ll also need to install the Bicep command line interface (CLI). The easiest, cross-platform way to do this is by installing the Azure command line interface. But if you’re after an alternative, see this list.

Become a Bicep guru

Dive deeper into Bicep with our getting started with Bicep course on Udemy today!

Writing your first Bicep file

Open Visual Studio Code, and create a new file called HelloWorld.bicep. In it, paste the following code:

resource appConfig 'Microsoft.AppConfiguration/[email protected]' = {
  name: 'bicepDemoAppConfig'
  location: 'westus2'
  sku: {
    name: 'standard'
  }
}

In this template, we’re creating an App Configuration service in Azure. Lets breakdown the template:

appConfig provides a local resource name for use within the template if you need to refer to this resource as a dependency, or from within another resource.

Microsoft.AppConfiguration/[email protected] refers to the resource type and the values that can be configured. See this Microsoft documentation for a full list of resource types.

As such, name, location and sku are all values that can be set for the resource type.

Next steps

To learn how to deploy this template, or to find out about more advanced Bicep topics including for loops, conditional statements and modularised templates check out our Udemy course on getting started with Bicep.

Categories
Azure

How to create an Azure app service with a database

Need to deploy your app to an Azure app service, and rely on a database such as Postgres or Azure SQL?

Microsoft is now previewing a new blade in the Azure portal that lets you quickly spin up an Azure app service with an associated database.

Supported database engines for the preview are Postgres or serverless Azure SQL server.

To get started using the new blade, click here or search the Azure Marketplace for “web app database”.

The blade – currently in preview – is fairly basic compared to the normal app service blade, but allows you to specify the app name, runtime and database engine. You can also set the server name and database name.

By default it’ll spin up an app service using the Premium V2 tier, but you can scale this down (or up if required) once the service is created using the regular Azure scale up settings.

The database connection information will automatically be set as environment variables for your app service.

Categories
Azure

Creating your first Azure Resource Manager (ARM) template

If you’re manually creating infrastructure for your next app in Azure, you should consider using an Azure Resource Manager (ARM) template.

An ARM template is essentially a JSON file that describes the infrastructure you want to create in the Azure cloud. It can be run as many times as you like to spin up identically-configured environments.

Create the template

The first step when using an ARM template is to create the template file. If you’d rather start with an example template, Microsoft has an entire Github repo with some templates that you can clone.

The base template – normally called azuredeploy.json – is made up of the following structure:

{
  “$schema”: “https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#”,
  “ContentVersion”: “1.0.0.0”,
  “Resources”: []
}

The elements can be described as follows:

  • $schema: Refers to the properties that can be used within the template. If you were to load the URL in your web browser, it would return the elements and a description of each that you can use within your template. When uploading a template, these get validated to ensure you haven’t made any mistakes.
  • contentVersion: This is an internal version number for you to use to reference the current template. It should be in the format X.X.X.X, with X being any integer. You should only change this value in your template when a significant change is made.
  • resources: This is an array that will contain a description of all the Azure resources that your app or service needs. For now it’s empty.

Add resources to the template

As mentioned above, within the resources section of the template you need to describe the Azure services that you wish to provision. Each Azure service has a set of properties that can be set, with some mandatory. By default, a resource requires:

  • type: The type is a string that refers to a namespace of the resource provider and the name of the type of resource that you wish to provision. For example, Microsoft.DocumentDB/DatabaseAccounts implies you want to create a DatabaseAccount from the Microsoft.DocumentDB namespace
  • apiVersion: Similar to the template $schema version, each Azure resource type also publishes versions of their schema. This property allows you to specify which schema or version of the resource type you’d like to use and is mandatory
  • name: The human-readable string name that you’d like the resource to be called

While not mandatory, a location element is normally provided as well to specify the location where you want the resource to reside (eg. Australia East).

Luckily Microsoft publishes a full list of properties for each resource type. But if you’re still not sure, for most resources you can manually create the resource using the Azure Portal and go to the “Export Template” tab for the resource, and Microsoft will generate a template for you.

For this tutorial, let’s create a simple functions app. Add the following to your resources section in your azuredeploy.json file:

   "resources": [
        {
            "type": "Microsoft.Web/sites",
            "apiVersion": "2018-02-01",
            "name": "[parameters('siteName')]",
            "kind": "functionapp,linux",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            ],
            "properties": {
                "name": "[parameters('siteName')]",
                "siteConfig": {
                     "appSettings": [
                        {
                            "name": "FUNCTIONS_WORKER_RUNTIME",
                            "value": "python"
                        },
                        {
                            "name": "FUNCTIONS_EXTENSION_VERSION",
                            "value": "~2"
                        }
                    ]
                },
                "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
                "clientAffinityEnabled": false
            }
        },
        {
            "type": "Microsoft.Web/serverfarms",
            "apiVersion": "2018-02-01",
            "name": "[variables('hostingPlanName')]",
            "location": "[parameters('location')]",
            "kind": "linux",
            "properties":{
                "reserved": false
            },
            "sku": {
                "Tier": "Dynamic",
                "Name": "Y1"
            }
        }
    ]

The above creates a Linux App Service hosting plan. It uses the consumption function tier (Y1) and isn’t a reserved plan.

The template also creates a function app (Microsoft.Web/sites) that dependsOn the hosting plan.

If you look closely, you might notice that some elements refer to variables and parameters. Let’s dive deeper into what they are.

What are parameters?

Parameters allow you to specify a value each time you deploy a template. For example, if you had a template and wanted to create a production and staging environment with it, you could create a environment parameter that would allow you to specify staging or production in resource names without modifying the template file each time.

If you didn’t use a parameter, you’d need to change the hard-coded string value in your azuredeploy.json file each time you wanted to change to a new environment.

Similarly if you wanted to be able to deploy your template to a different Azure location quickly, you could specify a location parameter. Then you could deploy to any Azure region by simply providing a new location parameter value – with no change to the template file required.

Within the template file, parameters sit in a top-level parameters element as follows:

{
  “$schema”: “https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#”,
  “ContentVersion”: “1.0.0.0”,
  “Resources”: [],
  “Parameters”: {
    “hostingPlanName”: {
      “type”: “string”,
      “DefaultValue”: “”,
      “Metadata”: {
           “Description”: “The name to give your hosting plan”
      }
   }
}

Parameters support a number of elements, but the most common include:

  • type: The type of value provided (eg. String)
  • defaultValue: A default value to use if one isn’t provided when the template is deployed
  • metadata.description: A description of what the parameter represents

Parameters can be set when deploying using the Azure CLI or PowerShell. Here’s an example of how you would provide a location parameter using the Azure CLI:

az group deployment create \
  —-name mytemplatename \
  —-resource-group yourResourceGroup \
  —-templateFile $templateFile \
  —-parameters environment=staging

Referencing the parameter is done using the following syntax – you can see a full example in the template we defined earlier with resources:

"location": "[parameters('location')]"

What are variables?

While parameters allow you to specify values when deploying a template, variables allow you to reuse values internally within your template file without duplication. For instance, if you had a value that you use in 3 different resources (such as a location or in the example above the hostingPlanName) that you didn’t want to expose to those running your template you could use a variable.

Like parameters, variables are also top-level elements. They’re simpler to specify, as you don’t need to provide descriptions, types and default values. They look like this:

{
  “$schema”: “https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#”,
  “ContentVersion”: “1.0.0.0”,
  “Resources”: [],
  “Variables”: {
     “HostingPlanName”: “yourHostingPlanName”
  }
}

You can then reference the variable within your resource definitions using the following syntax as seen in the resources section in the template we created earlier:

"name": "[variables('hostingPlanName')]"

Summary

In this post, you’ve learnt about how a template is structured, and what each element means. Stay tuned for our next post on deploying your template.

Categories
Azure

Managed identities and Azure App Service staging slots

If you’re using an Azure App Service on a tier that offers staging slots (standard and above) then you might want to consider what happens when you swap a slot.

If you’ve configured a slot then you’ll want to swap deployments at a minimum between a production and pre-production environment. Microsoft cover in depth what happens when you commence a swap, but what they don’t cover is what happens to any managed identities that you have setup for the app service.

In short, managed identities are tied to the slot in which you first create or assign them, and do not change when you initiate a swap between two or more slots.

You might recall that for an App Service you can have both a system-assigned or a user-assigned identity. These are configured to allow your App Service to access other Azure resources, without the need for sharing secrets and passwords.

When swapping slots, both system and user-assigned identities remain tied to the slot. They don’t swap – so if you need to change these, you’ll need to intervene separately.

Once you’ve generated or assigned an identity, don’t forget to then add it to any Azure resources your app needs access to.

Also keep in mind the lifecycle of a managed identity. User assigned identities won’t be removed whenever you delete a slot. On the other hand, system assigned identities will be deleted as soon as you delete a slot. Depending on your situation, you may prefer one of these approaches.

Categories
Azure

Azure Availability Zones vs Availability Sets

A common question for newcomers to Microsoft’s Azure platform is what’s the difference between an availability zone and an availability set?

An availability zone is a unique physical location within one Azure region, and provides high-availability for your application and infrastructure. Each zone is independent and has physically isolated power, cooling, and networking from other zones within the same region.

Different Azure services have varying levels of support for availability zones. Some will automatically replicate between zones, while others will require you to choose the zone to connect to.

Availability zones aren’t available within all Azure regions – in fact, currently there are only 10 regions across the United States, Asia and Europe that support availability zones:

  • Central US
  • East US
  • East US 2
  • West US 2
  • North Europe
  • UK South
  • West Europe
  • France Central
  • Japan East
  • Southeast Asia

On the other hand, an availability set is a concept that only applies to virtual machines. A set allows you to isolate virtual machine (VM) resources from one another when deployed, meaning your VMs will run across multiple machines and racks. This will help to avoid a hardware failure bringing down your entire application, and also means that outages from Microsoft updates won’t cause your application issues.

Unlike an availability zone which applies at the data centre level, an availability set only applies within the same data centre.

Categories
Azure

Using Cloudflare with Azure Blob Storage

If you’re storing files in Azure Storage, you’ll likely soon find that the cost of bandwidth will soon become one of the more expensive items in your Azure bill. By using a content delivery network (CDN), you can improve performance for those accessing your files from around the world, while also reducing the bandwidth costs incurred on Azure.

Microsoft offers its own Azure CDN solution, or you can use Akamai or Verizon. However, for the purposes of this tutorial we’ll be using Cloudflare – a third-party vendor who offers a free tier that should meet most people’s needs. Cloudflare can cache files based on the caching headers you apply when you upload files to blob storage, or you can apply default caching values. As a side note, Cloudflare also offers other services such as DDoS protection and edge workers.

Note that you’lll need to have your own domain name for this to work – you need to associate a custom domain name with the blob storage account. To use Cloudflare services, you also need to point your domain to Cloudflare’s name servers.

Setup Cloudflare
If you have a Cloudflare account already, you can skip this section. Otherwise, create an account at Cloudflare. The free account will be fine for this tutorial.

Once your account has been created, click “Add a site” and follow the instructions to verify and add your domain to Cloudflare. If you want to use a sub domain (eg. cdn.example.com) for the Blob Storage custom domain, this should be the root domain (eg. example.com).

This will also require changing your domain’s nameservers, so you’ll require admin permissions with your DNS registrar.

Getting started
If you haven’t already done so, create an Azure Storage resource by clicking “Create a resource” in the Azure Portal. Search for “storage account”, and choose the Microsoft service by clicking “Create”. Fill in the settings as required for your storage account.

Once your account has been provisioned, head to the “Storage accounts” tab and choose the account you want to setup.

Create a custom domain
The first step in setting up Cloudflare with Blob Storage is to map it to a custom domain name that you own (such as example.com). In the Azure Portal for your storage account, go to “Custom domain” under the “Blob service” tab.

You should see some Microsoft instructions about configuring a CNAME record with your DNS provider, which should now be Cloudflare. Follow these steps first, by logging into your Cloudflare account and adding the CNAME record to validate your ownership of the domain with Microsoft. Note that this will be the URL that people will see and use when accessing your content, so CNAMEs such as cdn.example.com or static.example.com are commonly used.

In Cloudflare, make sure the proxy status for your domain or subdomain is set to DNS only. If proxied is enabled, verification with Microsoft will fail.

Once you’ve added the required record to your domain name, enter the URL in the text field below in the Azure Portal. Click “Save”, and if the DNS changes have propogated (this can take up to 24-48 hours depending on your provider and configuration) then the custom domain should be added successfully. Otherwise, try again later once the changes have propegated.

Enable the Cloudflare proxy
Once you’ve verified your domain, you can enable caching on Cloudflare. Go back to your domain or subdomain in the DNS tab, and click the cloud icon until it’s orange and “Proxied” shows.

Then go to “Caching” and set the “Caching level” to standard.

Finally, by default Cloudflare will only cache certain types of files. If you’re serving predominantly static HTML or CSS files, this might be OK but if you’re sending other content types such as JSON you’ll need to add a page rule so that the files are cached.

Go to the “Page Rules” tab, and choose “Create Page Rule”. Enter the domain/subdomain you’re using for blob storage (eg cdn.example.com) and then click “Add a setting”. Choose “Cache Level” and select “Cache Everything”. This will now cache everything served on this domain, using either the Cloudflare defaults or the cache-control headers applied to the individual files.

Upload files to Blob Storage with cache-control headers set
Now, upload some files to your blob storage account in the Azure Portal. Depending on how you upload the files, you’ll need to set the cache-control headers. The .NET SDK has built-in support, or you can use these instructions to use PowerShell.

Conclusion
By enabling Cloudflare for your domain, you’re now saving money each month on bandwidth costs (Cloudflare will only request resources once the cached copy expires) and protecting yourself from a variety of security attacks.

Categories
Azure Azure Functions

Using Azure Functions with Rider

Previously we’ve written about how to get started with Azure Functions using JetBrains Rider – but that’s now an outdated article, as the Azure plugin now offers seamless integration with the Microsoft Functions tooling. Gone are the days of manually updating project configuration files.

What you’ll need

In order to follow along, you’ll need to make sure you:

Getting started

First you’ll want to install the Azure Toolkit for Rider. Open Rider then navigate to Preferences (JetBrains Rider > Preferences on a Mac) and Plugins.

In the Plugins screen, go to the Marketplace tab  and search for “Azure Toolkit for Rider”. Click install.

This will now allow you to manage and deploy a whole bunch of Azure services from within Rider, such as App Services and SQL databases.

Let’s open a new Functions app. Now that you’ve installed the Azure Toolkit, a new template for AzureFunctions has been added to your new project window. From within Rider, click File > New and choose Azure Functions from underneath the .NET Core section.

Enter a solution name, project name and choose a directory and language, and then click Create. If you’re using this as a test project, you can probably leave these values as is.

Running the Functions app

And that’s almost all there is to using Functions apps in Rider now! The toolkit will automatically detect that it’s a function app, and provide the necessary scaffolding to allow you to run and debug the app.

Gone are the days of hacking the project settings and configuration to make it work – it’s a seamless experience now.

To verify that the config is correct, click the run configuration in the top right-hand side of Rider, and edit the configurations. You should see a default Azure Functions host configuration, complete with all the settings required to run a functions app. You can see in this example that the function will run on port 7071, and pause on error.

Even better, is that if you don’t have the required Functions command line tools to run the app (which Rider relies on behind the scenes) then you’ll even get prompted to install them – which Rider will do automatically on your behalf. You’ll also get prompted if your tools are out of date.

And that’s how easy it is now to get started using Azure Functions in Rider!

Categories
Azure Azure Functions

Building Azure Functions in the Rider IDE

Many people now use Rider as their integrated development environment editor for .NET. However, when it comes to using it for developing Azure Functions, the out-of-the-box experience is (currently) less than ideal.

I say currently, because in the next update to the Azure Toolkit plugin for Rider Functions support has been added. This’ll make running and debugging function apps a breeze.

Until then though, here’s how you can run a functions app from Rider.

How to run Azure functions in Rider

First, you’ll need to install the function CLI (see creating an Azure function for the Mac).

Then, open your functions app in Rider by selecting the project or solution.

Create a Properties folder in the root directory if you don’t have one already, and then inside of that create a new JSON file called launchSettings.json.

Inside the JSON file, place the following object:

{  "profiles": {    "functions": {      "commandName": "Executable",      "executablePath": "func",      "commandLineArgs": "start --port 7071 --pause-on-error"    }  }}

You should see Rider now refresh, and add the configuration profile to your configurations with a little rocket icon. Click run, and your function app should start running within Rider.

Note that debugging is a little tricker for now. On Windows, once your function app is running you can go “Run” > “Attach to process” and choose your function app to listen to. But on a Mac, this has had mixed results.

Categories
Azure

Azure App Configuration vs App Settings

For a long time now, App Settings have been the way to configure your app’s settings such as environment variables and connection strings for Azure App Services.

In February 2019, Microsoft announced a new service called App Configuration – which, currently in preview – allows you to easily centralise your app settings across multiple resources.

Want to secure your Azure DevOps application secrets in Key Vault? Find out how in  our short e-book guide on Amazon

Why is App Settings a problem?

App Settings are great – if you only need those settings for one resource (eg. an app service). But if you’re working with, say, a microservice that might be made up of many resources including an app service and maybe a functions app that all share similar configurations, keeping track of what settings were made where can quickly become problematic.

Amongst other things, there’s no easy way to do things like point-in-time replays of settings, so you can see what changed or keep the settings the same if you need to rebuild or deploy a specific version of your app.

What does App Configuration offer that App Settings doesn’t?

App Configuration is a fully managed service that offers the ability to store all your app configuration values in one location, with the ability to compare settings at specific times and with specific labels.

Operating in a similar fashion to Key Vault, it’s a separate resource from your app service (although you can configure it immediately by going to the new preview tab in your app services), and there are a number of SDKs available to integrate with it for .NET core,  .NET and Java.

You can think of App Configuration as a counterpart to Key Vault for properties that don’t need to be stored as secrets. Connection strings would likely still go in Key Vault, but properties that aren’t secrets should be stored in App Configuration.

First you’ll need to setup a connection string which you can find under the “Settings” → “Access Keys” section of your App Configuration resource. Then, within App Configuration, you set a number of key value pairs, which you can then access in a similar fashion to the way you get environment variables in App Settings:

var configBuilder = new ConfigurationBuilder();configBuilder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("YourKeyNameFromAppConfiguration"));var config = configBuilder.Build();

You can also import and export settings easily, and can use JSON, YAML or a Properties file. You can also export the settings for a specific time and date.

At present, because the service is in preview there are no additional charges. Microsoft hasn’t yet stated its intentions for charging for this service, but given the similarities with Key Vault (which is a paid service) it’s easy to see how a similar model could apply if they decided.

Categories
Azure Azure Functions

Which Azure Functions runtime am I using?

Microsoft currently support two versions of the Azure Functions runtime – version 1 and version 2. This post will look at the main changes between the two versions, and show you how you can check which runtime you’re using.

What are the key differences between versions?

Version 1 of the runtime was introduced back in 2016, when functions were first announced. At launch it supported JavaScript, C#, Python and PHP.

In late September 2018 Microsoft made the Functions 2 runtime generally available and with it bought a number of significant development, deployment and performance improvements including the ability to use the runtime anywhere – on a Mac or Linux machine too! It’s worth noting that as of March 2019, Python support for Functions 2 is still in preview.

There were significant under the hood changes made to improve performance – and .NET Core 2.1 support was added, alongside a move to .NET Core powering the functions host process instead of .NET.

Big changes were made to the way that bindings work – as part of 2.0 they became extensions instead of being bundled into the runtime itself (aside from HTTP and timer support which are deemed core to the experience). This means that some bindings didn’t make it over yet to the new 2.0 runtime – your mileage may vary, but the Microsoft bindings docs have a clearer comparison between the two.

There are also a bunch of new integrations with Functions 2 – for instance, Application Insights is supported with minimal configuration required, while you can easily use deployment centre to add code from other sources such as Github repos into your functions app.

How can I tell what runtime I’m using?

If you’re running a functions app on a Mac or Linux machine – there’s a fair chance you’re using the 2.0 runtime, as that’s what the functions command line tools support. You can verify this by opening the host.json file within the root directory of your app, which should look something like this:

{    "version": "2.0",    "extensions": {      "http": {        "routePrefix": ""      }    } }

The version field directly references the version of the functions runtime you’re using. If it says 2.0, you’re using version 2 – if it’s 1 or missing completely, you’re on the first version of the runtime.

Similarly, you can also view the runtime for your app through the Azure Portal – open your app in the portal, then navigate to “Function app settings” where you’ll see the below “Runtime version” setting.