Skip to content

Instantly share code, notes, and snippets.

@noelbundick
Last active January 12, 2019 22:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noelbundick/6ecc76393a9825e88e7702e98f2045ef to your computer and use it in GitHub Desktop.
Save noelbundick/6ecc76393a9825e88e7702e98f2045ef to your computer and use it in GitHub Desktop.
Azure Function w/ User Assigned Identity

Azure utility functions

What is this?

It's an ARM template and an Azure Function App (https://github.com/noelbundick/azure-utilities) that I use as a base for doing interesting things in Azure. Ex: Start a VM from a Chrome bookmark, spin up Azure Container Instances as Azure DevOps build agents on-demand, etc. Cleanup resource groups on a timer trigger, etc.

It uses User Assigned Identity so I don't have to juggle certs or Service Principal credentials

Note: there's some other "global infra" stuff in this template and I couldn't be bothered to clean it up. I know this exact template works, so you get bonus content!

Why did you make it?

I've long had Functions that use a Service Principal to make Azure calls. I wanted to use User Assigned Identity so that I never have to worry about secrets.

I also wanted to wire up the Microsoft.Azure.Services.AppAuthentication with the fluent Azure SDK

How does it work?

I forked & inlined the AppAuthentication library because it doesn't support this scenario yet. Keep an eye on these issues:

The ARM template deploys a User Assigned Identity and an Azure Function that has the identity assigned. It also sets the AzureServicesAuthConnectionString to reference the AppId of the created identity.

How do I use it?

Run this:

BASENAME=noel

# Get your user objectId (for KeyVault - unnecessary for this example, but like I said, I didn't clean up the template)
OID=$(az ad user show --upn $(az account show --query 'user.name' -o tsv) --query objectId -o tsv)

# Deploy some stuff! This will create a Function App & User Assigned Identity named "{baseName}-utility"
az group create -n infra -l westus2
az group deployment create -g infra --template-file ./azuredeploy.json --parameters baseName=$BASENAME userObjectId=$OID

# Give your new User Assigned Identity permissions so it can do things in your subscription (turn on VMs, clean up storage blobs, whatever)
IDENTITY_OID=$(az identity show -n "$BASENAME-utility" -g infra --query principalId -o tsv) 
az role assignment create --role Contributor --assignee-object-id $IDENTITY_OID

# Use azure-functions-core-tools to deploy the function into the provisioned app
# You could configure source deployment straight from the repo if you wanted, but I don't have working code for that off the top of my head - so here's something that definitely works
git clone https://github.com/noelbundick/azure-utilities
cd azure-utilities/src/Acanthamoeba.Functions
dotnet publish -c Release
cd bin/Release/netcoreapp2.1/publish
zip -r Acanthamoeba.Functions.zip *
az functionapp deployment source config-zip --src Acanthamoeba.Functions.zip -n "$BASENAME-utility" -g infra
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"baseName": {
"type": "string",
"defaultValue": "[resourceGroup().name]"
},
"userObjectId": {
"type": "string"
}
},
"variables": {
"acrName": "[parameters('baseName')]",
"functionappName": "[concat(parameters('baseName'), '-utility')]",
"identityName": "[concat(parameters('baseName'), '-utility')]",
"insightsName": "[concat(parameters('baseName'), '-utility')]",
"kvName": "[parameters('baseName')]",
"storageName": "[toLower(parameters('baseName'))]"
},
"resources": [
{
"type": "Microsoft.KeyVault/vaults",
"apiVersion": "2018-02-14",
"name": "[variables('kvName')]",
"location": "[resourceGroup().location]",
"properties": {
"sku": {
"family": "A",
"name": "standard"
},
"accessPolicies": [
{
"objectId": "[parameters('userObjectId')]",
"tenantId": "[subscription().tenantId]",
"permissions": {
"secrets": [
"backup",
"delete",
"get",
"list",
"purge",
"recover",
"restore",
"set"
]
}
}
],
"enableSoftDelete": true,
"enabledForDeployment": true,
"enabledForDiskEncryption": true,
"enabledForTemplateDeployment": true,
"tenantId": "[subscription().tenantId]"
}
},
{
"type": "Microsoft.ContainerRegistry/registries",
"apiVersion": "2017-10-01",
"name": "[variables('acrName')]",
"location": "[resourceGroup().location]",
"sku": {
"name": "Basic"
},
"properties": {
"adminUserEnabled": true
}
},
{
"name": "[variables('insightsName')]",
"apiVersion": "2015-05-01",
"type": "Microsoft.Insights/components",
"location": "West US 2",
"tags": {
"[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', variables('functionappName'))]": "Resource"
},
"properties": {
"ApplicationId": "[variables('functionappName')]"
}
},
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2018-07-01",
"name": "[variables('storageName')]",
"location": "[resourceGroup().location]",
"kind": "StorageV2",
"sku": {
"name": "Standard_LRS"
},
"properties": {
"encryption": {
"keySource": "Microsoft.Storage",
"services": {
"blob": {
"enabled": true
},
"file": {
"enabled": true
}
}
},
"supportsHttpsTrafficOnly": true
}
},
{
"type": "Microsoft.ManagedIdentity/userAssignedIdentities",
"name": "[variables('identityName')]",
"apiVersion": "2015-08-31-preview",
"location": "[resourceGroup().location]"
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2018-02-01",
"name": "[variables('functionappName')]",
"location": "[resourceGroup().location]",
"kind": "functionapp",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', variables('storageName'))]",
"[resourceId('Microsoft.Insights/components', variables('insightsName'))]",
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]"
],
"properties": {
"name": "[variables('functionAppName')]",
"reserved": false,
"clientAffinityEnabled": false,
"siteConfig": {
"appSettings": [
{
"name": "FUNCTIONS_WORKER_RUNTIME",
"value": "dotnet"
},
{
"name": "AzureWebJobsStorage",
"value": "[concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageName')), '2018-02-01').keys[0].value)]"
},
{
"name": "FUNCTIONS_EXTENSION_VERSION",
"value": "~2"
},
{
"name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
"value": "[concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageName')), '2018-02-01').keys[0].value)]"
},
{
"name": "WEBSITE_CONTENTSHARE",
"value": "[toLower(variables('functionAppName'))]"
},
{
"name": "APPINSIGHTS_INSTRUMENTATIONKEY",
"value": "[reference(resourceId('Microsoft.Insights/components/', variables('insightsName')), '2015-05-01').InstrumentationKey]"
},
{
"name": "AzureServicesAuthConnectionString",
"value": "[concat('RunAs=App;AppId=', reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName')), '2015-08-31-preview').clientId, ';')]"
}
]
}
},
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]": {}
}
}
}
],
"outputs": {
"utilityIdentityId": {
"type": "string",
"value": "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]"
},
"functionappName": {
"type": "string",
"value": "[variables('functionappName')]"
}
}
}
MIT License
Copyright (c) 2018 Noel Bundick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment