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] + "]"