Azure, IaC, Pulumi, Security

Securing Shared Pulumi State in Azure

Introduction

Welcome to this blog post on securing Pulumi state in Azure, in the fast-evolving world of cloud infrastructure, ensuring the security of your code and sensitive information is paramount. Pulumi, a powerful Infrastructure as Code (IaC) platform, allows developers to express their infrastructure needs using familiar programming languages. As teams embrace Pulumi to manage their Azure resources, the need to safeguard the state files containing critical information becomes crucial.

In this blog post, we will explore an approach to securing Pulumi state files using Azure Storage Accounts, Azure Key Vault and Azure AD.

Before we begin configuring Pulumi state files, ensure you have the following pre-requisites in place:

  • Azure CLI: Make sure you have the latest Azure CLI installed (2.53.1 at the time of writing). The Azure CLI provides a powerful and user-friendly interface to interact with Azure resources.
  • Pulumi: Make sure you have the latest Pulumi installed (3.90.1 at the time of writing) to leverage the most recent features and improvements provided by the Pulumi platform.
  • Azure AD Permissions: To configure the Azure AD Groups, you need sufficient permissions within Azure Active Directory. Ensure that you have appropriate permissions, such as being assigned as an “User Access Administrator” on the Azure subscription where you’ll be deploying resources as well as permissions to deploy into the subscription e.g. “Contributor”.
  • PowerShell: Make sure you have PowerShell installed (7.3.9 at the time of writing)

NOTE: All the commands used were ran from a PowerShell 7 terminal on Windows

Some useful links:

Setup Azure Infrastructure

In this section, we will walk you through the process of creating an Azure Storage Account and an Azure Key Vault along with configuring access roles and permissions with Azure AD.

First of all login to Azure with the Azure CLI and set the subscription that you are going to deploy to.

az login
az account set -s "<name of subscription>"

We will start with declaring some variables needed the configuration such as storage name, key vault name, resource group, etc. (Don’t forget storage account and key vault names need to be globally unique)

$location="westeurope"
$stateResourceGroup="rg-pulumi-state-dev-euw"
$storageName="stpulumistoredevweu"
$storageContainerName="iacstate"
$storageSku="Standard_ZRS"
$storageDeleteRetention=7
$keyVaultName="kv-pulumisecrets-dev-euw"
$keyName="pulumisecret"

To organize and manage our Azure resources effectively, we’ll create a dedicated resource group. This container will house all the resources related to our Pulumi deployments, allowing for easy management.

az group create --location $location --name $stateResourceGroup

The next step is setting up an Azure Storage Account to store your Pulumi state files securely. The Storage Account will ensure durability and redundancy for your infrastructure state, while following good practices for access control and encryption.

az storage account create --name $storageName --resource-group $stateResourceGroup --location $location --sku $storageSku --min-tls-version TLS1_2 --https-only true --allow-shared-key-access false --allow-blob-public-access false --require-infrastructure-encryption

This may seem like quite a long command but this is configuring the account and additional security properties i.e.

  • min-tls-version: Specifies the minimum Transport Layer Security (TLS) version required for secure communication with the storage account
  • https-only: true, Enables HTTPS-only access for the storage account. This ensures that all data access and management operations are encrypted over HTTPS
  • allow-shared-key-access: false, Disables the use of the account key (shared key) for access to the storage account and use Azure AD for access, this is recommended for improved security
  • allow-blob-public-access: false, Disables public access to containers and blobs in the storage account. This setting ensures that containers and blobs cannot be accessed anonymously
  • require-infrastructure-encryption: Requires the storage service to encrypt all data at rest using Azure Storage Service Encryption (SSE). This is good practice for data security and as we will no doubt be storing secrets in our state its a good option to turn on

To prevent accidental deletions of your Pulumi state files, it’s a good idea to update the retention period for both containers and blobs. Enabling delete retention ensures data remains accessible for a specified duration, acting as a safety net against data loss.

Let’s update the retention period to reinforce the security of your Pulumi state files and maintain the integrity of your cloud infrastructure.

az storage account blob-service-properties update -n $storageName -g $stateResourceGroup --enable-delete-retention --delete-retention-days $storageDeleteRetention --enable-container-delete-retention --container-delete-retention-days $storageDeleteRetention
  • enable-delete-retention: Enable delete retention
  • delete-retention-days: Indicates the number of days that the deleted blob should be retained
  • enable-container-delete-retention: Enable container delete retention
  • container-delete-retention-days: Indicates the number of days that the deleted container should be retained

With our Azure Storage Account settings optimised for enhanced protection, it’s time to create the container where we’ll store our Pulumi state files. To further bolster security, we’ll configure the container with Azure AD authentication.

az storage container create --name $storageContainerName --account-name $storageName --auth-mode login

Having set up our Azure Storage Account, the next critical step is to create the Azure Key Vault to use as Pulumi’s secrets provider.

az keyvault create --name $keyVaultName --resource-group $stateResourceGroup --location $location

To encrypt values within our Pulumi state file securely, we’ll generate an encryption key in Azure Key Vault.

az keyvault key create --name $keyName --kty RSA --size 4096 --vault-name $keyVaultName

Next we will enable RBAC so that we can grant permissions to the same group of users given access to the Storage Account.

az keyvault update --name $keyVaultName --enable-rbac-authorization

Full PowerShell with comments

$location="westeurope"
$stateResourceGroup="rg-pulumi-state-dev-euw"
$storageName="stpulumistoredevweu"
$storageContainerName="iacstate"
$storageSku="Standard_ZRS"
$storageDeleteRetention=7
$keyVaultName="kv-pulumisecrets-dev-euw"
$keyName="pulumisecret"

# Create Resource Group
az group create --location $location --name $stateResourceGroup

# Create Secure Storage Account
az storage account create --name $storageName --resource-group $stateResourceGroup --location $location --sku $storageSku --min-tls-version TLS1_2 --https-only true --allow-shared-key-access false --allow-blob-public-access false --require-infrastructure-encryption
az storage account blob-service-properties update -n $storageName -g $stateResourceGroup --enable-delete-retention true --delete-retention-days $storageDeleteRetention --enable-container-delete-retention --container-delete-retention-days $storageDeleteRetention
az storage container create --name $storageContainerName --account-name $storageName --auth-mode login

# Create Key Vault
az keyvault create --name $keyVaultName --resource-group $stateResourceGroup --location $location

# Create Key
az keyvault key create --name $keyName --kty RSA --size 4096 --vault-name $keyVaultName

# Enable RBAC
az keyvault update --name $keyVaultName --enable-rbac-authorization

Azure AD Group and Role Assignment

With our resources properly configured, it’s time to grant access by adding an Azure AD group. We have two options to achieve this:

  1. Azure Portal: You can create an AD group directly in the Azure Portal. Refer to the “How to manage groups” tutorial on Microsoft Learn for step-by-step guidance.
  2. Azure CLI: Alternatively, you can use the Azure CLI to create the AD group programmatically. This approach provides automation and consistency in managing groups. Use the Azure CLI commands to create the AD group and assign it to the necessary resources.

For this guide we’ll be using the Azure CLI

$adGroup="PulumiUsers"
$adGroupId=$(az ad group create --display-name $adGroup --mail-nickname $adGroup --query id -o tsv)

or if the AD group already exists

$adGroup="PulumiUsers"
$adGroupId=$(az ad group show -g $adGroup --query id -o tsv)

To grant the necessary permissions on the Storage Account, we will assign the “Storage Blob Data Contributor” role to the Azure AD group. This role provides the group members with the required access to manage blobs within the Storage Account.

$storageId=$(az storage account show -n $storageName --query id -o tsv)
az role assignment create --role 'Storage Blob Data Contributor' --assignee-object-id $adGroupId --assignee-principal-type Group --scope $storageId

To grant the necessary permissions on the Key Vault, we will assign the “Key Vault Crypto User” role to the Azure AD group. This role allows group members to perform cryptographic operations using keys within the Key Vault.

$keyVaultId=$(az keyvault show --name $keyVaultName --query id -o tsv)
az role assignment create --role 'Key Vault Crypto User' --assignee-object-id $adGroupId --assignee-principal-type Group --scope $keyVaultId

You will now need to add users to the Azure AD group in order to grant access to the Key Vault and Storage Account resources to securely manage secrets and Pulumi state files.

Configuring Local Development

To configure your local development environment, login to Azure using the Azure CLI and if needed set the subscription where the storage account and key vault were created, if you are not already logged in

az login
az account set -s "<name of subscription>"

Now we need to configure a couple of environment variables for Pulumi in order to use the Azure Key Vault and Storage Account.

$storageContainerName="iacstate"
$keyVaultName="kv-pulumisecrets-dev-euw"
$env:AZURE_KEYVAULT_AUTH_VIA_CLI=$true
$env:AZURE_STORAGE_ACCOUNT="stpulumistoredevweu"

pulumi login --cloud-url azblob://$storageContainerName

After logging in to Pulumi, it’s now time to create a new stack. As I am a C# developer I am going to use azure-csharp.

pulumi new azure-csharp --secrets-provider azurekeyvault://$keyvaultName.vault.azure.net/keys/pulumisecret

Other pulumi languages are also supported e.g. azure-typescript, azure-python, etc..

When you run the command pulumi new, the Pulumi CLI will prompt you to provide the following information:

  • Project Name e.g. pulumi-demo
  • Project Description e.g. Simple App in C#
  • Stack Name e.g. Dev
  • Azure Native Location e.g. WestEurope

TIP: if you have a current stack it can be updated to use the Azure Key Vault as a secrets provider e.g.

pulumi stack change-secrets-provider azurekeyvault://$keyvaultName.vault.azure.net/keys/pulumisecret

With your secure shared state store in place, you’re all set to begin building your infrastructure. By adding this configuration to source control, your team members can collaborate seamlessly. They’ll be able to build and run the infrastructure effortlessly, provided they have the necessary prerequisites installed and are part of the designated Azure AD group.

Running pulumi up with the basic generated code builds a Resource Group and an Azure Storage Account with random values to make them unique

The state file is also populated and will secrets encrypted e.g. primaryStorageKey

Note: The generated code for the Azure Storage Account uses the defaults and as such lacks some essential security options, for example the defaults include TLS 1.0, Blobs are publicly accessible and unsecure transfer is enabled.

To bolster the security of your Azure Storage Account (if you are keeping it), add the following properties to your configuration:

AllowBlobPublicAccess = false,
EnableHttpsTrafficOnly = true,
MinimumTlsVersion = "TLS1_2"

Deployment

With our infrastructure fully defined and tested, it’s time to deploy it in a repeatable and automated manner. Let’s explore how to set up the deployment process using Azure Pipelines.

To get started, we’ll need the Pulumi extension, the “Pulumi Azure Pipelines Task,” which can be found on the Visual Studio Marketplace.

To grant the necessary access to the shared state, we must add the build agent service principal to the designated Azure AD group.

$buildAgentSPName="<build agent service principal name>"
$buildAgentSPId=$(az ad sp list --display-name $buildAgentSPName --query [0].id -o tsv)
az ad group member add -g $adGroup --member-id $buildAgentSPId

Now let’s see what an Azure Pipeline looks like using the Pulumi task.

Azure Pipelines Example

trigger: none
pr: none
pool:
  vmImage: 'ubuntu-latest'
variables:
  subscription: '<Subscription Name>'
  storageName: 'stpulumistoredevweu'
  storageContainerName: 'iacstate'
steps:
- task: Pulumi@1
  displayName: 'Pulumi Preview'
  inputs:
    loginArgs: --cloud-url azblob://$(storageContainerName)
    azureSubscription: $(subscription)
    command: 'preview'
    cwd: '$(Build.SourcesDirectory)'
    createStack: true
    stack: 'organization/pulumi-demo/dev'
  env:
    AZURE_STORAGE_ACCOUNT: $(storageName)
- task: Pulumi@1
  displayName: 'Pulumi Up'
  inputs:
    loginArgs: --cloud-url azblob://$(storageContainerName)
    args: --yes
    azureSubscription: $(subscription)
    command: 'up'
    cwd: '$(Build.SourcesDirectory)'
    createStack: true
    stack: 'organization/pulumi-demo/dev'
  env:
    AZURE_STORAGE_ACCOUNT: $(storageName)

Conclusion

Throughout this process, we’ve demonstrated a straightforward and effective approach to secure your Pulumi state files in Azure, ensuring the safe deployment of your infrastructure.

By leveraging Azure Storage Accounts and Key Vault, and integrating Azure AD for access control, we’ve fortified the confidentiality and integrity of your critical resources.

Now, you’re well-equipped to embark on your Infrastructure as Code (IaC) journey with confidence and security.

Happy IaCing! 🚀😊

Azure, Bicep, IaC, Pulumi

Deploying Feature Flags to Azure App Configuration

Introduction

In the world of Development, feature flags have become an indispensable tool for enabling Continuous Deployment and A/B testing. Azure App Configuration provides a centralised and scalable solution for managing application settings. In this blog post, we’ll explore how to deploy feature flags to Azure App Configuration using Infrastructure as Code (IaC) tools like Bicep and Pulumi, enhancing the control and flexibility of your deployment process.

Prerequisites

Before we dive into the deployment process, make sure you have:

  1. An Azure subscription
  2. An existing Azure App Configuration Service
  3. Basic knowledge of Azure App Configuration and feature flags concepts
  4. Bicep (0.20.4) and/or Pulumi CLI (3.79.0) installed
  5. Basic knowledge and understanding of Bicep and/or Pulumi concepts
  6. Azure CLI (2.51.0) installed

Documentation

Bicep App Configuration and Key Values

Pulumi App Configuration and Key Values

Step 1: Deploy Feature Flags

As we already have we have our App Configuration, let’s deploy a feature flag. For example, let’s create some flags named “newFeature” and “newFeature2” with both disabled. Here’s how you can do it:

Bicep

Create a .bicepparam file to store the configuration in e.g. features-dev.bicepparam

using 'features.bicep'
param configStoreName = 'appcs-myapp-dev-weu'
param featureFlags = [
  {
    name: 'newFeature'
    label: 'myteam'
    value: {
      id: 'newFeature'
      description: 'the new feature'
      enabled: false
    }
    tags: { 
      mytag: 'a feature tag'
    }
  }
  {
    name: 'newFeature2'
    label: 'myteam'
    value: {
      id: 'newFeature2'
      description: 'Another new feature'
      enabled: false
    }
    tags: {}
  }
]

And a Bicep file e.g. features.bicep to configure the Azure App Configuration feature flags

param configStoreName string
param featureFlags array

resource configStoreResource 'Microsoft.AppConfiguration/configurationStores@2023-03-01' existing = {
  name: configStoreName
}

resource configStoreKeyValue 'Microsoft.AppConfiguration/configurationStores/keyValues@2023-03-01' = [for entry in featureFlags: {
  parent: configStoreResource
  name: '.appconfig.featureflag~2F${entry.name}$${entry.label}'
  properties: {
    value: string(entry.value)
    contentType: 'application/vnd.microsoft.appconfig.ff+json;charset=utf-8'
    tags: entry.tags
  }
}]

Deploy using the Azure CLI

az deployment group create --name "flags-deploy" --resource-group rg-myapp-dev-weu --template-file features.bicep --parameters features-dev.bicepparam

Pulumi

Pulumi supports a number of languages but we will show TypeScript and C# examples for this post.

When creating a Pulumi project a stack is created and by default the stack is called dev and so a pulumi configuration file is created for that stack e.g. pulumi.dev.yaml. We can add our configuration for the feature flags in this configuration file.

encryptionsalt: v1:8c8dl9MgfYM=:v1:b+PWTv408Trh7uT6:1FlnAGfspnMZjosvoqvA+AjaGhWu2Q==
config:
  azure-native:location: WestEurope
  storeName: "appcs-myapp-dev-weu"
  resourceGroupName: "rg-myapp-dev-weu"
  featureFlags:
    - name: "newFeature"
      label: "myteam"
      value:
        id: "newFeature"
        description: "the new feature"
        enabled: false
      tags: 
        mytag: "a feature tag"
    - name: "newFeature2"
      label: "myteam"
      value: 
        id: "newFeature2"
        description: "Another new feature"
        enabled: false
      tags: {}

Typescript

import * as pulumi from "@pulumi/pulumi";
import * as appconfiguration from "@pulumi/azure-native/appconfiguration";

const config = new pulumi.Config();
const featureFlags = config.requireObject<any>("featureFlags");
const storeName = config.require("storeName")
const resourceGroupName = config.require("resourceGroupName")

featureFlags.forEach((entry: { name: string; label: string; tags: any; value: Object; }) => {
    new appconfiguration.KeyValue(`keyValue${entry.name}`, {
        configStoreName: storeName,
        keyValueName: `.appconfig.featureflag~2F${entry.name}$${entry.label}`,
        resourceGroupName: resourceGroupName,
        tags: entry.tags,
        contentType: "application/vnd.microsoft.appconfig.ff+json;charset=utf-8",
        value: JSON.stringify(entry.value)
    });
});

C#

using System.Collections.Generic;
using System.Dynamic;
using System.Text.Json;
using Pulumi;
using Pulumi.AzureNative.AppConfiguration;

return await Deployment.RunAsync(() =>
{
    Config config = new();
    var featureFlags = config.RequireObject<IReadOnlyList<ExpandoObject>>("featureFlags");
    var storeName = config.Require("storeName");
    var resourceGroupName = config.Require("resourceGroupName");
    
    foreach (dynamic entry in featureFlags) 
    {        
        new KeyValue($"keyValue{entry.name}", new()
        {
            ConfigStoreName = storeName,
            KeyValueName = $".appconfig.featureflag~2F{entry.name}${entry.label}",
            ResourceGroupName = resourceGroupName,
            ContentType = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8",
            Tags = JsonSerializer.Deserialize<IReadOnlyDictionary<string, string>>(entry.tags, new JsonSerializerOptions { 
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            }),
            Value = JsonSerializer.Serialize(entry.value, new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            })
        });
    }
});

Deploy using the Pulumi CLI

pulumi up

Step 2: Update Feature Flags

As the feature flags are now in code changing or adding a feature flag means updating the appropriate configuration file and then re-deploying either by a CLI as above or by a continuous deployment pipeline.

Conclusion

Deploying feature flags to Azure App Configuration using IaC (e.g. Bicep or Pulumi) enhances the reproducibility and scalability of your deployment process. Infrastructure as Code allows you to version and track changes effectively in source control. By following the steps outlined in this blog post, you can seamlessly integrate feature flags into your continuous deployment pipeline, enabling efficient feature rollout and experimentation.

Remember that these code snippets are just the beginning. As your application and feature flag requirements evolve, you can further customize and extend these configurations to suit your needs as well as run them in pipelines such as Azure Pipelines, GitHub Actions, etc..

Happy IaCing!!