Update 2023-01-05 - As suggested by other answers, there's an easier way now - just reference the Azure.Deployments.Expression
nuget package which contains all of the Arm functions and then use the following convenience wrapper:
using Azure.Deployments.Expression.Expressions;
using Newtonsoft.Json.Linq;
public static class ArmFunctions
{
public static string? UniqueString(params string[] values)
{
var parameters = values.Select(
arg => new FunctionArgument(
JToken.FromObject(arg)
)
).ToArray();
var result = ExpressionBuiltInFunctions.Functions
.EvaluateFunction("uniqueString", parameters, null);
return result.Value<string>();
}
}
// "zcztcwvu6iyg6"
var unique = ArmFunctions.UniqueString("tyeth");
Original answer for posterity:
I've been researching this myself on and off for a few years now, and I've finally hit paydirt...
// "zcztcwvu6iyg6"
var unique = ArmUniqueString("tyeth");
My ArmUniqueString
function is a wrapper around some dlls that are distributed with the Azure Stack Hub Development Kit which is basically a virtual machine image that contains the Azure server-side platform that you can run locally...
private static string ArmUniqueString(string originalString)
{
var assembly = Assembly.GetAssembly(
typeof(Microsoft.WindowsAzure.ResourceStack.Frontdoor.Templates.Engines.TemplateEngine)
);
var functions = assembly.GetType(
"Microsoft.WindowsAzure.ResourceStack.Frontdoor.Templates.Expressions.TemplateExpressionBuiltInFunctions"
);
var uniqueString = functions.GetMethod(
"UniqueString",
BindingFlags.Static | BindingFlags.NonPublic
);
var parameters = new object[] {
"uniqueString",
new JToken[] {
(JToken)originalString
}
};
var result = uniqueString.Invoke(null, parameters).ToString();
return result;
}
You'll need to download the Azure Stack Hub Development Kit and unpack it to get the dlls:
- Download the Azure Stack Hub Development Kit - warning: it's about 22Gb!
- Run the installer to unpack a 55Gb *.vhdx
- Mount the *.vhdx, or expand / unpack it locally
- Inside the *.vhdx, find this file and unzip it somewhere:
CloudBuilder\CloudDeployment\NuGetStore\Microsoft.AzureStack.Setup.Services.ResourceManager.5.20.1335.300.nupkg
- The
content\Website\bin
folder inside the *.nupkg
contains the necessary dlls
To use them, add an assembly reference to Microsoft.WindowsAzure.ResourceStack.Frontdoor.Templates.dll
(it has some dependencies on other files in the bin folder) and that contains the TemplateExpressionBuiltInFunctions
class. The code above just uses reflection to invoke the private UniqueString
function from that assembly, with a little bit of work to marshal the parameters into appropriate JToken
types.
If you wanted to dig into the implementation details you could probably run a decompiler against the assembly to find out what it's doing under the covers...
Note - credits go to this blog article for pointing me in the right direction:
https://the.agilesql.club/2017/12/azure-arm-template-function-internals/