You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pulumi为Azure Web App新增应用设置且保留原有设置?

在Pulumi Azure Native中为Azure Web App新增应用设置且保留原有设置的解决方法

问题背景

使用Pulumi Azure Native开发IaC时,需要为Azure Web App新增应用设置(如Application Insights密钥、存储账户名称),但直接使用WebAppApplicationSettings会替换全部现有设置,不符合增量更新需求。尝试通过list_web_app_application_settings_output获取现有设置再合并时,执行pulumi up出现404资源不存在错误。

错误原因

list_web_app_application_settings_output属于Pulumi的invoke操作,在pulumi up的预览阶段就会尝试调用Azure API,但此时Web App还未被创建,因此返回资源不存在的错误。即使添加depends_on也无法阻止预览阶段的invoke执行。

可行解决方案

方式一:合并现有设置与新设置(支持增量更新)

通过处理预览阶段的空值问题,确保Web App创建完成后再合并设置,既保留原有设置,又新增或覆盖指定设置:

from pulumi import Output, ResourceOptions
from pulumi_azure_native import web

# 创建Web App(可包含初始应用设置)
web_app = web.WebApp(
    'my-web-app-test123',
    resource_group_name='my-resource-group',
    server_farm_id='<你的应用服务计划ID>',
    # 可选:初始应用设置
    site_config=web.SiteConfigArgs(
        app_settings=[web.NameValuePairArgs(name='InitialSetting', value='initial-value')]
    )
)

# 获取现有设置,处理预览阶段的空值情况
current_settings = web.list_web_app_application_settings_output(
    name=web_app.name,
    resource_group_name='my-resource-group',
    opts=ResourceOptions(depends_on=[web_app])
).properties.apply(lambda props: props if props is not None else {})

# 定义需要新增/更新的设置
new_settings = {'mySetting': '123456', 'BlobStorageAccount': 'my-storage-account'}

# 合并现有设置与新设置(新设置覆盖同名旧设置,其余保留)
merged_settings = Output.all(current=current_settings, new=new_settings).apply(
    lambda args: {**args['current'], **args['new']}
)

# 应用合并后的设置
web.WebAppApplicationSettings(
    'my-web-app-settings',
    name=web_app.name,
    resource_group_name='my-resource-group',
    properties=merged_settings,
    opts=ResourceOptions(depends_on=[web_app])
)

方式二:使用ignore_changes保护手动添加的设置

如果Web App上有手动添加的应用设置,不希望被Pulumi代码覆盖,可以通过ignore_changes选项指定忽略对整个properties的变更,仅确保代码中定义的设置存在:

from pulumi import ResourceOptions
from pulumi_azure_native import web

web_app = web.WebApp(
    'my-web-app-test123',
    resource_group_name='my-resource-group',
    server_farm_id='<你的应用服务计划ID>'
)

# 仅管理指定的新设置,原有手动添加的设置不受影响
web.WebAppApplicationSettings(
    'my-web-app-settings',
    name=web_app.name,
    resource_group_name='my-resource-group',
    properties={'mySetting': '123456'},
    opts=ResourceOptions(
        depends_on=[web_app],
        ignore_changes=['properties']
    )
)

注意:此方式下,代码中删除设置不会自动移除Web App上的对应项,需手动处理。

内容的提问来源于stack exchange,提问作者frisko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:24:21