使用 ARM 模板通过复制另一个数据库来创建数据库,前提是目标数据库尚不存在

Use an ARM template to create a database by copying another, only if the target database does not already exist

我正在使用 ARM 模板配置 Azure SQL 数据库。我想说 如果 这个数据库还不存在,应该通过复制另一个固定的数据库来创建它。但是如果我想要的数据库确实已经存在,它应该单独存在。

'only do something if the current state is not the desired state' 的功能是 Incremental 模式下部署的标准功能。但似乎这与 CopycreateMode 不相符。

我的模板 JSON 看起来像这样(不要介意没有参数化,这是一个例子):

{
  "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [
    {
      "type": "Microsoft.Sql/servers/databases",
      "name": "[myservername/mydatabasename]",
      "apiVersion": "2014-04-01-preview",
      "location": "[UK South]",
      "properties": {
        "createMode": "Copy",
        "sourceDatabaseId": "[redacted]/myservername/databases/mysourcedatabase",
      }
    }
  ]
}

如预期的那样第一次部署成功。但是如果重复同样的部署,会得到错误:

New-AzureRmResourceGroupDeployment : 11:51:49 - Resource Microsoft.Sql/servers/databases 'myservername/mydatabasename' failed with message '{
  "code": "BadRequest",
  "message": "The destination database name 'mydatabasename' already exists on the server 'myservername'.",
  "target": null,
  "details": [],
  "innererror": []
}'

如果我使用createModeDefault,那么我可以重复部署,是幂等的,但是我不能指定初始创建应该是通过复制mysourcedatabase

没有用 conditionresourceId 做可怕的事情,我有什么办法可以说 "create-by-copying or do nothing" 吗?

不,即使使用 conditionsresourceId(),您也无法做到这一点,至少在没有一些技巧的情况下是这样。最简单的方法 - 使用外部实体来决定是否需要此部署并传入适当的参数。