0

I read an SQL statement from a .sql-file within an Azure Pipeline Python task, using:

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

In this .sql-file, there is the name of a database that is written with a special start identifier and end identifier: [|>[database_location_1]<|].

Using regex, I find all occurences of this specific identifiers:

pattern = r"\[\|>[^\]]*<\|\]"

matches = re.findall(pattern, sql_statement)
for match in matches:
   print(match)

Now the goal is to replace the database name within the identifiers with an Azure Pipeline variable that has been set previously in "Pipelines - Library - Variables" and has the same variable name as the database (here: database_location_1).

I want to set this replacement dynmaically, because there are several database locations as variables in Azure Pipelines (e.g. database_location_1, database_location_2, etc.).

Normally, you would access an Azure Pipeline variable with the following syntax: "$(variable)", but if you try to concatenate the database_name that has been read before with the syntax dynamic_var = "$(" + match[3:-3] + ")", then Azure Pipelines does not recognize it as Azure Pipelines variable, so that data = data.replace(match, dynamic_var) does not return the desired outcome, because dynamic_var is not equal to the Azure Pipelines variable value.

Different Python string concatenation all lead to the same result:

substitute_string_v1 = "\"$(%s)\"" % match[3:-3]
substitute_string_v2 = "$(%s)" % match[3:-3]
substitute_string_v3 = "$(" + match[3:-3] + ")"
substitute_string_v4 = "$[" + match[3:-3] + "]"  
Anthon
  • 69,918
  • 32
  • 186
  • 246
wil-qua
  • 1
  • 1
  • Non-secret variables are accessible as environment variables within scripts. Does that help? – Daniel Mann Jul 10 '23 at 13:10
  • This sounds a lot like the dynamic variable that I successfully had put in my Azure Pipelines, by using PowerShell commands, and then calling Python inside of the PowerShell task itself. Could you perhaps elaborate the task above in a simple Azure Pipelines Yaml example? – Adji_PA Aug 18 '23 at 10:21

0 Answers0