获取在Bicep模块中创建时的函数应用默认主机密钥

huangapple go评论70阅读模式
英文:

Get Function App Default Host Key When Created in Bicep Module

问题

我之前创建了可工作的 Bicep 模板,用于创建一个函数应用程序,然后仅在函数应用程序直接作为主模板中的资源创建时使用密钥,而不是在模块内部创建。

这次,我有一个"主" Bicep 模板,调用一个 Bicep 模块来创建一个函数应用程序。然后在主模板中,我需要将函数应用程序的密钥传递给另一个模块,该模块将其存储为一个名为 "apim" 的机密值。

ChatGPT 建议如下:

// 创建函数应用程序
module functionApp 'br:azcontreg.azurecr.io/bicep/modules/functionapp:v23.01.17.01' = {
  name: 'functionApp'
  params: {
    functionAppName: functionAppName
    appServicePlanName: appServicePlanName
    appServicePlanResourceGroup: appServicePlanResourceGroup
    storageAccountName: storageAccountName
    storageAccountResourceGroup: storageAccountResourceGroup
  }
}

// 检索函数应用程序的密钥
output functionAppKeys object = listKeys(functionApp.outputs.id, '2019-08-01')

// 创建 API 管理的命名值
module apimNamedValue 'br:azcontreg.azurecr.io/bicep/modules/apimnamedvalue:v23.01.17.01' = {
  name: 'apimNamedValue'
  scope: resourceGroup('rg-apim-${subscription().displayName}')
  dependsOn: [
    functionApp
    keyVault
  ]
  params: {
    name: '${functionApp.outputs.appServiceName}-key'
    secret: true
    value: functionAppKeys.keys[0].value
    environment: environment
  }
}

问题是,这会导致以下编译错误:

此表达式正在用作函数 "listKeys" 的参数,该函数要求在部署开始时可以计算的值。可以在开始时计算的 functionApp 的属性包括 "name"。bicep(BCP181)

负责创建函数应用程序的模块包含以下内容:

resource appService 'Microsoft.Web/sites@2021-03-01' = {
    name: name
    kind: appKind
    location: location
    tags: tags
    identity: {
        type: !empty(identityName) ? 'SystemAssigned, UserAssigned' : 'SystemAssigned'
        userAssignedIdentities: !empty(identityName) ? { 
            '${appServiceIdentity.id}': {}
        } : null
    }
    properties: {
        httpsOnly: true
        reserved: false
        serverFarmId: appServicePlan.id
        virtualNetworkSubnetId: !empty(vnetName) && !empty(vnetSubnetName) ? vnetSubnet.id : null
    }

    resource appServiceAppSettings 'config' = {
        name: 'appsettings'
        properties: appSettingsInternal
    }

    resource appServiceSlotConfigNames 'config' = {
        name: 'slotConfigNames'
        properties: {
            appSettingNames: deploymentSlotSettingNames
        }
    }

    resource appServiceWeb 'config' = {
        name: 'web'
        properties: {
            alwaysOn: alwaysOn
            ftpsState: 'FtpsOnly'
            healthCheckPath: healthCheckPath
            ipSecurityRestrictions: ipSecurityRestrictions
            use32BitWorkerProcess: use32BitProcess
            vnetRouteAllEnabled: vnetRouteAll
        }
    }
}
output appServiceId string = appService.id

这是从主.bicep 中调用的:

module functionApp 'br:crbicepregistryprod001.azurecr.io/bicep/modules/appservice:v23.04.13.01' = {
  name: 'functionApp'
  params: {
    name: functionAppName
    appServicePlanScope: functionAppServicePlanEnv.rg
    appServicePlanName: functionAppServicePlanEnv.name
    appKind: 'functionapp'
    vnetName: 'vnet-${environment}-uksouth'
    vnetSubnetName: functionAppServicePlanEnv.subnet
    ipSecurityRestrictions: functionAppIpSecurityRestrictions
    appSettings: functionAppSettings
    enableSlot: false
    alwaysOn: true
    healthCheckPath: '/health'
  }
  dependsOn: [
    appInsights
    keyVault
  ]
}

后来,主.bicep 使用以下方式调用新模块:

module apimNamedValue 'br:crbicepregistryprod001.azurecr.io/bicep/modules/apimnamedvalueforlistkeys:v23.06.13.02' = {
  name: 'apimNamedValue'
  scope: resourceGroup('rg-apim-${subscription().displayName}')
  dependsOn: [
    functionApp
    keyVault
  ]
  params: {
    name: '${functionApp.outputs.appServiceName}-key'
    secret: true
    resourceId: functionApp.outputs.appServiceId
    environment: environment
  }
}

用于使用 listKeys 获取密钥的新模块如下所示:

@description('要部署的NamedValue的名称')
param name string

@description('要在listkeys函数中使用的资源 ID')
param resourceId string

@description('用于listkeys函数的 API 版本')
param apiVersion string = '2022-09-01'

@description('指定值是否为机密。默认为 false')
param secret bool = false

@description('指定值是否为密钥保管库引用。还意味着值是机密的。默认为 false')
param keyVaultReference bool = false

@description('要部署到的 APIM 环境')
@allowed([
    'dev'
    'int'
    'act'
    'prod'
])
param environment string = 'dev'

var apimName = {
    dev: 'apim-dev-002'
    int: 'apim-int-001'
    act: 'apim-act-001'
    prod: 'apim-prod-002'
}[environment]

var value = listKeys(resourceId, apiVersion)
resource apim 'Microsoft.ApiManagement/service@2021-08-01' existing = {
    name: apimName

    resource apimNamedValue 'namedValues' = {
        name: name
        properties: {
            displayName: name
            secret: secret || keyVaultReference
            keyVault: keyVaultReference ? {
                secretIdentifier: value
            } : null
            value: !keyVaultReference ? value : null
        }
    }
}

output namedValueId string = apim::apimNamedValue.id
output namedValueName string = apim

<details>
<summary>英文:</summary>

I have previously created working bicep templates that create a function app and later use the keys but only where the function app is created as a resource directly within the main template - rather than within a module.

This time, I have a &quot;main&quot; bicep template that calls a bicep module to create a function app. Later in the main template, I need to pass the function app&#39;s key to another module that stores as a secret apim named value.

ChatGPT suggested the following:

````json  
// Create the Function App
module functionApp &#39;br:azcontreg.azurecr.io/bicep/modules/functionapp:v23.01.17.01&#39; = {
  name: &#39;functionApp&#39;
  params: {
    functionAppName: functionAppName
    appServicePlanName: appServicePlanName
    appServicePlanResourceGroup: appServicePlanResourceGroup
    storageAccountName: storageAccountName
    storageAccountResourceGroup: storageAccountResourceGroup
  }
}

// Retrieve the Function App keys
output functionAppKeys object = listKeys(functionApp.outputs.id, &#39;2019-08-01&#39;)

// Create the API Management named value
module apimNamedValue &#39;br:azcontreg.azurecr.io/bicep/modules/apimnamedvalue:v23.01.17.01&#39; = {
  name: &#39;apimNamedValue&#39;
  scope: resourceGroup(&#39;rg-apim-${subscription().displayName}&#39;)
  dependsOn: [
    functionApp
    keyVault
  ]
  params: {
    name: &#39;${functionApp.outputs.appServiceName}-key&#39;
    secret: true
    value: functionAppKeys.keys[0].value
    environment: environment
  }
}

Problem is, this gives the following compile error:

> This expression is being used in an argument of the function
> "listKeys", which requires a value that can be calculated at the start
> of the deployment. Properties of functionApp which can be calculated
> at the start include "name".bicep(BCP181)

The module that provisions the function app contains the following:

resource appService &#39;Microsoft.Web/sites@2021-03-01&#39; = {
name: name
kind: appKind
location: location
tags: tags
identity: {
type: !empty(identityName) ? &#39;SystemAssigned, UserAssigned&#39; : &#39;SystemAssigned&#39;
userAssignedIdentities: !empty(identityName) ? { 
&#39;${appServiceIdentity.id}&#39;: {}
} : null
}
properties: {
httpsOnly: true
reserved: false
serverFarmId: appServicePlan.id
virtualNetworkSubnetId: !empty(vnetName) &amp;&amp; !empty(vnetSubnetName) ? vnetSubnet.id : null
}
resource appServiceAppSettings &#39;config&#39; = {
name: &#39;appsettings&#39;
properties: appSettingsInternal
}
resource appServiceSlotConfigNames &#39;config&#39; = {
name: &#39;slotConfigNames&#39;
properties: {
appSettingNames: deploymentSlotSettingNames
}
}
resource appServiceWeb &#39;config&#39; = {
name: &#39;web&#39;
properties: {
alwaysOn: alwaysOn
ftpsState: &#39;FtpsOnly&#39;
healthCheckPath: healthCheckPath
ipSecurityRestrictions: ipSecurityRestrictions
use32BitWorkerProcess: use32BitProcess
vnetRouteAllEnabled: vnetRouteAll
}
}
}
output appServiceId string = appService.id

This is called from the main.bicep with the following:

module functionApp &#39;br:crbicepregistryprod001.azurecr.io/bicep/modules/appservice:v23.04.13.01&#39; = {
name: &#39;functionApp&#39;
params: {
name: functionAppName
appServicePlanScope: functionAppServicePlanEnv.rg
appServicePlanName: functionAppServicePlanEnv.name
appKind: &#39;functionapp&#39;
vnetName: &#39;vnet-${environment}-uksouth&#39;
vnetSubnetName: functionAppServicePlanEnv.subnet
ipSecurityRestrictions: functionAppIpSecurityRestrictions
appSettings: functionAppSettings
enableSlot: false
alwaysOn: true
healthCheckPath: &#39;/health&#39;
}
dependsOn: [
appInsights
keyVault
]
}

Main.bicep later calls the new module with the following:

module apimNamedValue &#39;br:crbicepregistryprod001.azurecr.io/bicep/modules/apimnamedvalueforlistkeys:v23.06.13.02&#39; = {
name: &#39;apimNamedValue&#39;
scope: resourceGroup(&#39;rg-apim-${subscription().displayName}&#39;)
dependsOn: [
functionApp
keyVault
]
params: {
name: &#39;${functionApp.outputs.appServiceName}-key&#39;
secret: true
resourceId: functionApp.outputs.appServiceId
environment: environment
}
}

The new module to obtain the key using listKeys is as follows:

@description(&#39;Name of the NamedValue to deploy&#39;)
param name string
@description(&#39;Resource Id to be used in the listkeys function&#39;)
param resourceId string
@description(&#39;Used in listkeys function&#39;)
param apiVersion string = &#39;2022-09-01&#39;
@description(&#39;Specify if the value is secret. Defaults to false&#39;)
param secret bool = false
@description(&#39;Specify if the value is a key vault reference. Also implies value is secret. Defaults to false&#39;)
param keyVaultReference bool = false
@description(&#39;APIM environment to deploy to&#39;)
@allowed([
&#39;dev&#39;
&#39;int&#39;
&#39;act&#39;
&#39;prod&#39;
])
param environment string = &#39;dev&#39;
var apimName = {
dev: &#39;apim-dev-002&#39;
int: &#39;apim-int-001&#39;
act: &#39;apim-act-001&#39;
prod: &#39;apim-prod-002&#39;
}[environment]
var value = listKeys(resourceId, apiVersion)
resource apim &#39;Microsoft.ApiManagement/service@2021-08-01&#39; existing = {
name: apimName
resource apimNamedValue &#39;namedValues&#39; = {
name: name
properties: {
displayName: name
secret: secret || keyVaultReference
keyVault: keyVaultReference ? {
secretIdentifier: value
} : null
value: !keyVaultReference ? value : null
}
}
}
output namedValueId string = apim::apimNamedValue.id
output namedValueName string = apim::apimNamedValue.name
output namedValueNameFormatted string = &#39;{{${apim::apimNamedValue.name}}}&#39;

If I drill into the resource group deployment in the Azure portal I see:

获取在Bicep模块中创建时的函数应用默认主机密钥

If I then click the error details link, I see:

{
&quot;code&quot;: &quot;BadRequest&quot;,
&quot;message&quot;: &quot;&quot;
}

I guess the error state is “Not Found” because the module is running in the scope of the apim’s resource group but it’s trying to access the key of the function app which is in a different resource group?

答案1

得分: 1

传递密钥/机密可能会很棘手,特别是当一切都模块化时。

我会考虑创建一个新的模块变体 br:azcontreg.azurecr.io/bicep/modules/apimnamedvaluefromkey,该模块接受额外的两个参数,用于资源ID和API版本。然后,您可以将 listkeys 移入该模块,它不会遭受名称计算错误,因为它已经抽象化了。

英文:

Passing around keys/secrets can be tricky, especially when everything modularised.

I'd be tempted to create a new module variant br:azcontreg.azurecr.io/bicep/modules/apimnamedvaluefromkey that takes an extra 2 parameters for the resourceid and api version. Then you can move the listkeys into that module and it won't suffer the name calculation error as it's abstracted.

答案2

得分: 1

已通过将函数应用程序密钥存储在相同资源组的密钥保管库中解决。然后,apim命名值引用了密钥保管库的秘密。

以下是对初始apim命名值模块的调用。

module apimNamedValue 'br:regname.azurecr.io/bicep/modules/apimnamedvalue:v23.05.04.01' = {
name: 'apimNamedValue'
scope: resourceGroup('rg-apim-${subscription().displayName}')
dependsOn: [
functionApp
keyVault
]
params: {
name: '${functionApp.outputs.appServiceName}-key'
secret: true
keyVaultReference: true
value: '${keyVault.outputs.keyVaultId}/secrets/${secretName}/'
environment: environment
}
}
英文:

Solved by storing the function app key in a key vault of the same resource group. The apim named value then referenced the key vault secret.

Below is the call to the initial apim named value module.

module apimNamedValue &#39;br:regname.azurecr.io/bicep/modules/apimnamedvalue:v23.05.04.01&#39; = {
name: &#39;apimNamedValue&#39;
scope: resourceGroup(&#39;rg-apim-${subscription().displayName}&#39;)
dependsOn: [
functionApp
keyVault
]
params: {
name: &#39;${functionApp.outputs.appServiceName}-key&#39;
secret: true
keyVaultReference: true
value: &#39;${keyVault.outputs.keyVaultId}/secrets/${secretName}/&#39;
environment: environment
}
}

huangapple
  • 本文由 发表于 2023年6月13日 18:22:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76463916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定