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

在Azure Pipeline Python任务中动态替换SQL占位符为Pipeline变量

解决Azure Pipeline Python任务中动态替换SQL文件内Pipeline变量的问题

问题根源

Azure Pipeline的变量替换是在任务执行前完成的,Python代码运行时拼接出的$(variable)字符串只是静态文本,不会再被Pipeline解析为实际变量值,所以直接替换成这种格式无法生效。

解决方案1:通过环境变量在Python中直接读取Pipeline变量

Azure Pipeline会自动将定义的变量注入到任务的环境变量中(变量名转为大写,空格/特殊字符替换为下划线),Python可以直接从环境变量中获取对应值完成替换。

代码修改示例

import re
import os

with open(file_path, "r", encoding='utf-8') as f:
    sql_statement = f.read()

# 定义匹配标识的正则,捕获标识内的变量名
pattern = r"\[\|>([^\]]+)<\|\]"

# 使用回调函数动态替换匹配内容
def replace_match(match):
    var_name = match.group(1)
    # 转换为Pipeline注入的环境变量格式(小写转大写,特殊字符转下划线)
    env_var_name = var_name.upper().replace("-", "_").replace(".", "_")
    # 从环境变量取值,变量不存在时返回原标识内容作为 fallback
    return os.environ.get(env_var_name, match.group(0))

# 执行全局替换
updated_sql = re.sub(pattern, replace_match, sql_statement)

# 后续处理逻辑(比如写入文件或直接执行SQL)

注意事项

  • 如果是秘密变量,需要在Pipeline变量设置中勾选「Allow access to this variable from scripts」,否则无法注入到环境变量。
  • 环境变量转换规则:原变量名的小写字母转大写,空格、.、-等特殊字符替换为_,例如database.location-1会转为DATABASE_LOCATION_1。

解决方案2:在Python任务前用脚本预替换SQL文件

如果不想修改Python代码,可以在Python任务之前添加Shell/PowerShell任务,提前将SQL文件中的标识替换为Pipeline可解析的格式,让Pipeline自动完成变量替换。

Bash任务示例(Linux/macOS)

# 将SQL中的[|>xxx<|]替换为$(xxx),让Pipeline自动解析变量
sed -i 's/\[\|>\([^]]*\)<\|\]/$\(\1\)/g' your_sql_file.sql

执行该任务后,再让Python读取处理后的your_sql_file.sql即可。

PowerShell任务示例(Windows)

$content = Get-Content -Path "your_sql_file.sql" -Encoding UTF8
# PowerShell中$需要用$$转义,确保生成$(xxx)格式
$updatedContent = $content -replace '\[\|>([^]]+)<\|\]', '$$($1)'
Set-Content -Path "your_sql_file.sql" -Value $updatedContent -Encoding UTF8

内容的提问来源于stack exchange,提问作者wil-qua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:27:41