首页 > 解决方案 > 重新实现 uniqueString() 哈希 ARM 函数

问题描述

ARM 中的uniqueString函数是一个返回 13 个字符的哈希函数。例如,执行下图所示的小脚本中的函数richard变为b6oys6fwmheio.

有谁知道这是如何实现的,以便可以在代码中重新实现它?

当一个人在门户中创建和命名事物时,我会非常方便,然后在稍后通过 ARM 部署时对其进行更新。

用于执行函数的 ARM 脚本

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [],
  "outputs": {
    "uniqueName": {
      "value": "[uniqueString('richard')]",
      "type": "string"
    }
  }
}

仅仅使用标准的哈希算法和一个非常幼稚的实现并不能真正让你接近,如this fiddle所示。因此,获得一些实现的细节会非常好。

标签: azurehashcryptographyazure-resource-managerazure-deployment

解决方案


一个不优雅的解决方案(我不是 PS 开发人员 :)):

param($text)

$tempPath = (New-TemporaryFile).FullName;
@'
{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "text": {
            "type": "string"
        }
    },
    "resources": [],
    "outputs": {
        "uniqueName": {
            "value": "[uniqueString(parameters('text'))]",
            "type": "string"
        }
    }
}
'@ > $tempPath;

$result = New-AzDeployment -Location "westeurope" -TemplateFile $tempPath -TemplateParameterObject @{ text = $text };
return $result.Outputs.uniqueName.value;

推荐阅读