Angular 6 application hosted on Azure Storage Static website

A few days ago Microsoft announced a new public preview feature for Azure Storage called Static website. It enables you to host a static web app using Azure Storage which is multiple times cheaper then a traditional required Web App. Reason enough to give it a try.

Create a Storage account

To use the Static website feature we need a general purpose V2 Storage Account. You can either manually create the resource within the Azure Portal or by using the following ARM Template:

Enable Static website feature

Unfortunately we can’t enable the Static website feature using an ARM Template (thanks to Gaurav Mantri) because it is not part of the Storage Resource Provider API. So we have to manually enable it after we’ve provisioned the Storage Account.

We can do that within our previous created Storage Account: Select Static website (preview) to configure a container for static website hosting:

enablestaticwebsite

Since our example applicaton will have an index.html,  we can leave the index document name field as it is.

Note: If you have to automate this process, it is still possible to enable this feature using the Azure Storage Services REST API.

After we save our changes we get the primary endpoint URL of our site:

spaurl.png

Create an Angular Single Page Application

We use the Angular CLI to scaffold an Angular sample applicaton that already has routing enabled. The name of our app will be spastore:

ng new spastore --routing

We also create a new component named subcomponent to demonstrate the routing capability:

ng g component subcomponent

And configure the routing module accordingly:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SubcomponentComponent } from './subcomponent/subcomponent.component';

const routes: Routes = [
  { path: 'subcomponent', component: SubcomponentComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Note that we use the HashLocationStrategy oppsed to the default PathLocationStrategy because the later will result in 404 errors. This is because we can’t define a rewrite URL for our static website and Azure will try to resolve the specified resource – e. g.:
https://spastore.z6.web.core.windows.net/subcomponent

The HashLocationStrategy represents its state in the hash fragment of the browser’s URL. So this will be the new route for our subcomponent:
https://spastore.z6.web.core.windows.net/#/subcomponent

Finally we add the router outlet to the app.component.html which displays our component and add a router link:


  <a>Subcomponent</a>

Now it’s time to compile the application and get a production build. Once again we use the Angular CLI:

ng build --prod

The build artefacts are stored within the dist folder and are ready to publish. We can do that by clicking on the $web link within the Static website (preview) blade. Then we have to click on the Upload button and select all files within the artefact (dist) folder:

angularupload

If we browse to the URL we can see our Angular App up and running and also the routing is working as expected:

angulardemo.png

You can test the site here: https://spastore.z6.web.core.windows.net

The source code including the ARM Template and the Angular sample application can be found in my GitHub repository.

Update:

You can actualy use the PathLocationStrategy by setting the error page to index.html (thanks to @nthonyChu). The first try to serve a URL like https://spastore.z6.web.core.windows.net/subcomponent will fail since it is not a valid resource. Then the path will get passed to the error page which is our index.html (page returns content with 404 status code). However, this is hack. I still recommend using the HashLocationStrategy until a rewrite mechanism is in place.

Find outdated Azure ARM QuickStart Templates on GitHub

In my previous post Determine latest API version for a resource provider I showed you how to retrieve the latest API version for a specific resource provider using the Get-AzureRmResourceProviderLatestApiVersion cmdlet. In this post I will use the cmdlet to find any outdated resource provider within an ARM template. Also, we will analyze the Azure quickstart templates on GitHub!

To analyze an ARM template we have to convert the JavaScript Object Notation (JSON) to a custom PowerShell object that has a property for each field in the JSON.
We will use the following lean template for testing purpose (download):

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts",
            "name": "myuniquestorageaccountname",
            "apiVersion": "2016-01-01",
            "location": "West Europe",
            "sku": {
                "name": "Standard_LRS"
            },
            "kind": "Storage"
        }
    ]
}

The first thing we have to do is to load the file using the Get-Content cmdlet and pipe the result to the ConvertFrom-Json cmdlet. To retrieve the resources we further pipe the result to the Select-Object cmdlet:


Get-Content leanArmTemplate.json |
        ConvertFrom-Json |
        Select-Object -ExpandProperty resources

This will give us all necessary information like the resource provider and the used API version:

type       : Microsoft.Storage/storageAccounts
name       : myuniquestorageaccountname
apiVersion : 2016-01-01
location   : West Europe
sku        : @{name=Standard_LRS}
kind       : Storage

Now finally to analyze the template, we have to iterate over each resource and retrieve the latest API version using the previous mentioned Get-AzureRmResourceProviderLatestApiVersion cmdlet. To get a handy output we create a new PsCustomObject containing the resource type, the used and latest API Version and a flag that specifies whether the used API version is the latest:

Get-Content leanArmTemplate.json |
        ConvertFrom-Json |
        Select-Object -ExpandProperty resources |
         ForEach-Object {
            $latestApiVersion = Get-AzureRmResourceProviderLatestApiVersion -Type $_.type
            [PsCustomObject]@{
                Type = $_.type
                UsedApiVersion = $_.apiVersion
                LatestVersion = $latestApiVersion
                Latest = $_.apiVersion -eq $latestApiVersion
            }
        }

This is the output:

Type                              UsedApiVersion LatestVersion Latest
----                              -------------- ------------- ------
Microsoft.Storage/storageAccounts 2016-01-01     2018-02-01     False

In this example, the used API for the resource provider Microsoft.Storage/storageAccounts is not up to date.

For the sake of convenience I wrapped the code into a Get-OutdatedResourceProvider cmdlet and added some special treatment to handle nested resources:

function Get-OutdatedResourceProvider
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Path,

        [switch]$IncludePreview
    )
    Get-Content $Path |
        ConvertFrom-Json |
        Select-Object -ExpandProperty resources |
        ForEach-Object {
        $latestApiVersion = Get-AzureRmResourceProviderLatestApiVersion -Type $_.type
        [PsCustomObject]@{
            Type = $_.type
            UsedApiVersion = $_.apiVersion
            LatestVersion = $latestApiVersion
            Latest = $_.apiVersion -eq $latestApiVersion
        }

        # a resource may include sub resources
        foreach ($subResource in $_.resources)
        {
            $latestApiVersion = Get-AzureRmResourceProviderLatestApiVersion -Type ('{0}/{1}' -f $_.type, $subResource.type)
            [PsCustomObject]@{
                Type = '{0}/{1}' -f $_.type, $subResource.type
                UsedApiVersion = $_.apiVersion
                LatestVersion = $_.apiVersion -eq $latestApiVersion
            }
        }
    }
}

🕵️‍♂️🕵️‍♂️🕵️‍♂️ Now it’s time to analyze some templates  🕵️‍♂️🕵️‍♂️🕵️‍♂️.

Lets clone the whole azure-quickstart-templates Git repository:

git clone https://github.com/Azure/azure-quickstart-templates.git

Then we can filter all ARM templates using the Get-ChildItem cmdlet:

$armTemplates = Get-ChildItem 'azure-quickstart-templates' -Filter 'azuredeploy.json' -Recurse

To analyze them we iterate over each template and pass it to the above created Get-OutdatedResourceProvider cmdlet. Because there might be some invalid templates, we try to parse the JSON first and filter all valid templates:

$invalidTemplates = @()
$analyzedTemplates = $armTemplates |
    ForEach-Object {
    $template = $_
    try
    {
        $null = $template | Get-Content | ConvertFrom-Json
        Get-OutdatedResourceProvider -Path $template.FullName
    }
    catch
    {
        $invalidTemplates += $template
    }
}

Finally we gather and output some metrics:

$validAnalyzes = $analyzedTemplates | Where-Object LatestVersion
$uptodateproviderCount = $validAnalyzes | Where-Object LatestVersion -eq TRUE | Measure-Object | Select-Object -ExpandProperty Count
$outdatedproviderCount = $validAnalyzes | Where-Object LatestVersion -ne TRUE | Measure-Object | Select-Object -ExpandProperty Count

Write-Host "Found $($armTemplates.Count) ARM templates in the Azure quickstart repository ($($invalidTemplates.Count) of them are invalid).
They are using $($analyzedTemplates.Count) resource providers. I was able to determine the latest version for $($validAnalyzes.count) resource provider. $uptodateproviderCount of them are using the latest API version whereas $outdatedproviderCount are using an outdated API." -ForegroundColor Cyan

Here is the output:

Found 675 ARM templates in the Azure quickstart repository (3 of them are invalid).
They are using 3873 resource providers. I was able to determine the latest version for 3288 resource provider. 18 of them are using the latest API version whereas 3270 are using an outdated API.

Note: There is no need to always use the latest API version. You should consider upgrading only if you encounter issues with the resource provider or if you want to use new features that are not part of the currently used API.

You can download the complete script and run it for yourself here.

Determine latest API version for a resource provider

Azure Resource Manager templates are great to deploy one or more resources to a resource group.

A mandatory part of an ARM template is the resources section which defines the resource types that are deployed or updated. Here is an example:

"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "2016-01-01",
"location": "[parameters('location')]",
"sku": {
	"name": "Standard_LRS"
},
"kind": "Storage",
"properties": {}

The name of a resource type has the following format: {resource-provider}/{resource-type}. In this example Microsoft.Storage/storageAccounts. The apiVersion specifies the version of the API that is used to deploy / manage the resource.

A resource provider offers a set of operations to deploy and manage resources using a REST API. If a resource provider adds new features, it releases a new version of the API. Therefore, if you have to utilize new features you may have to use the latest API Version. To determine the latest version of a resource type you can use the following Get-AzureRmResourceProviderLatestApiVersion cmdlet:

function Get-AzureRmResourceProviderLatestApiVersion
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([string])]
    Param
    (
        [Parameter(ParameterSetName = 'Full', Mandatory = $true, Position = 0)]
        [string]$Type,

        [Parameter(ParameterSetName = 'ProviderAndType', Mandatory = $true, Position = 0)]
        [string]$ResourceProvider,

        [Parameter(ParameterSetName = 'ProviderAndType', Mandatory = $true, Position = 1)]
        [string]$ResourceType,

        [switch]$IncludePreview
    )

    # retrieving the resource providers is time consuming therefore we store
    # them in a script variable to accelerate subsequent requests.
    if (-not $script:resourceProvider)
    {
        $script:resourceProvider = Get-AzureRmResourceProvider   
    }

    if ($PSCmdlet.ParameterSetName -eq 'Full')
    {
        $ResourceProvider = ($Type -replace "\/.*")
        $ResourceType = ($Type -replace ".*?\/(.+)", '$1')
    }
    
    $provider = $script:resourceProvider | 
        Where-Object {
        $_.ProviderNamespace -eq $ResourceProvider -and 
        $_.ResourceTypes.ResourceTypeName -eq $ResourceType
    }

    if ($IncludePreview)
    {
        $provider.ResourceTypes.ApiVersions[0]
    }
    else
    {
        $provider.ResourceTypes.ApiVersions | Where-Object {
            $_ -notmatch '-preview'
        } | Select-Object -First 1
    }
}

You can now determine the latest API Version using either the full type:

Get-AzureRmResourceProviderLatestApiVersion -Type Microsoft.Storage/storageAccounts

Or by passing the Resource Provider and Resource Type:

Get-AzureRmResourceProviderLatestApiVersion -ResourceProvider Microsoft.Storage -ResourceType storageAccounts

Finally, to include preview versions you can append the -IncludePreview switch:

Get-AzureRmResourceProviderLatestApiVersion -Type Microsoft.Storage/storageAccounts -IncludePreview

You can download the script from my GitHub repository.

Additional information: Resource providers and types

Using Azure Key Vault in ASP.NET Core 2.0 with the options pattern

The best way to store secrets in your app is not to store secrets in your app

Almost every web application needs some kind of secrets like a SQL Database connection string or the primary key of a Storage Account in order to communicate with external services.

Certainly we don’t store these secrets within our source code since this would expose them to every developer that has access to the code. In Azure we could store the secrets within the Application Settings in the Azure Portal:

secret.PNG

But if a secret is used in multiple application and we need to change it (e. g. regenerate a storage account key) we would have to do that in multiple places. A better place to store secrets in Azure is the Key Vault.

Instead of storing each secret within our app we store them in the Key Vault and configure our app to access the secrets in the vault. Now we have a single place where we can manage our secrets.

Lets take a look how we can access those secrets in an ASP.NET Core 2.0 web application without introducing a dependency to Key Vault in the class that uses it. To create a vault, store secrets to it and create a service principal for the access policy see Get started with Azure Key Vault.

Our secret is stored in a class called ValueSettings:

public sealed class ValueSettings
{
	public string TestSecret { get; set; }
}

There is a ValuesController with one HttpGet method that returns our secret:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly ValueSettings _valueSettings;

    public ValuesController(IOptions<ValueSettings> valueSettings)
    {
        _valueSettings = valueSettings.Value;
    }

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(_valueSettings.TestSecret);
    }
}

As you can see in line 6 the controller uses the options pattern to inject the actual settings. The controller doesn’t know where the secret is comming from and doesn’t have any dependencies to Azure Key Vault.

Now lets take a look how we need to configure our application for that. First we need to store the vault settings in our appsettings.json:

{
  "KeyVault": {
    "Vault": "https://myvault.vault.azure.net/",
    "ClientId": "myclientid",
    "ClientSecret": "myclientsecret"
  }
}

We also have a class that represents these settings:

public class KeyVaultSettings
{
    public string Vault { get; set; }
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
}

Now to configure the key vault we use the AddAzureKeyVault extension method in the Programm.cs:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false)
                    .AddEnvironmentVariables();

                var builtConfig = config.Build();
                var settings = builtConfig.GetSection("KeyVault").Get();

                config.AddAzureKeyVault(
                    settings.Vault, settings.ClientId, settings.ClientSecret);

            })
            .UseStartup()
            .Build();
}

And finally this is how our Startup looks like:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;   
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(Configuration);

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

You can download the complete example from my GitHub repository.

Determine whats wrong with your Azure Web / API App deployment

Sometimes a deployment goes wrong and instead of the actual app you get a message like this:

An error occurred while starting the application.
.NET Core 4.6.26020.03 X86 v4.0.0.0 | Microsoft.AspNetCore.Hosting version 2.0.1-rtm-125 | Microsoft Windows 10.0.14393 | Need help?

To see whats going wrong we have to enable logging:

  • Go to the Kudu environment (https://YOURSITE.scm.azurewebsites.net)
  • On the top menu, select Debug console -> PowerShell
  • Navigate to site -> wwwroot and open the web.config
  • Set the stdoutLogEnabled attribute to true and save the file. Example:
    
    
  • Create a folder named logs next to the web.config using mkdir logs

Now if you try to browse your site again, you should see a log file within the previously created directory containing additional information:

kudu