如何将带环境变量的Azure DevOps步骤移至模板并保留大小写敏感
实现方法
要将测试步骤移至Azure DevOps模板并保留环境变量的大小写敏感性,可按以下步骤操作:
1. 创建模板文件
创建一个YAML模板(例如test-step-template.yml),通过object类型参数接收环境变量——YAML本身对键名大小写敏感,object类型参数能完整保留传入的键值对大小写:
parameters: # 定义object参数,默认包含原有测试环境变量 testEnvironmentVariables: ASPNETCORE_ENVIRONMENT: 'test' Case_sensitive_environment_variable_key: 'This is the value' steps: - task: DotNetCoreCLI@2 displayName: Run tests inputs: command: 'test' # 直接引用参数中的环境变量对象,保留大小写 env: ${{ parameters.testEnvironmentVariables }}
2. 在主管道中调用模板
主管道调用模板时,可传入自定义的环境变量(覆盖默认值或添加新变量),键名的大小写会被完整保留:
steps: - template: test-step-template.yml parameters: testEnvironmentVariables: # 覆盖默认变量值 ASPNETCORE_ENVIRONMENT: 'custom-test-env' # 保留原有大小写的键并更新值 Case_sensitive_environment_variable_key: 'Updated sensitive value' # 添加新的大小写敏感变量 New_Case_Sensitive_Key: 'New custom value'
可选:合并默认与自定义变量
如果希望模板保留默认环境变量,同时允许用户添加/覆盖指定变量,可拆分参数并使用Azure DevOps的merge函数合并对象:
模板文件(合并版)
parameters: # 用户传入的自定义环境变量,默认空对象 customEnvironmentVariables: {} steps: - task: DotNetCoreCLI@2 displayName: Run tests inputs: command: 'test' # 合并默认变量与用户自定义变量,自定义变量会覆盖同名默认变量 env: ${{ merge( { 'ASPNETCORE_ENVIRONMENT': 'test', 'Case_sensitive_environment_variable_key': 'This is the value' }, parameters.customEnvironmentVariables ) }}
主管道调用(合并版)
steps: - template: test-step-template.yml parameters: customEnvironmentVariables: # 仅覆盖需要修改的变量 ASPNETCORE_ENVIRONMENT: 'staging-test' # 添加新变量 App_Specific_Key: 'App value'
内容的提问来源于stack exchange,提问作者Patrik Mihalčin
相关产品推荐
相关产品推荐

