Замена динамических c переменных с использованием содержимого REGEX в качестве переменной в Azure CD Pipeline Powershell Task - PullRequest
1 голос
/ 28 апреля 2020

Я пишу пользовательскую задачу Powershell Azure CD Pipeline (для VM), где мой web.config должен быть заменен переменными конвейера. У меня есть пример файла конфигурации, как с WebService и AuditService , определенные в моих Azure переменных конвейера CD.

<client>
      <endpoint address="__WebService__" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="WebServiceClient.ServiceSoap" name="NLSService" />
      <endpoint address="__AuditService__" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Audit" contract="AuditApiService.Audit" name="AuditService" />
    </client>

У меня есть сценарий powershell как

$zipfileName = "$(System.DefaultWorkingDirectory)\_WebService-CI\drop\Service.zip"
$fileToEdit = "web.config"
$reg = [regex] '__(.*?)__'


[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem");
# Open zip and find the particular file (assumes only one inside the Zip file)
$zip =  [System.IO.Compression.ZipFile]::Open($zipfileName,"Update")
$configFile = $zip.Entries.Where({$_.name -like $fileToEdit})

# Read the contents of the file
$desiredFile = [System.IO.StreamReader]($configFile).Open()
$text = $desiredFile.ReadToEnd()
$desiredFile.Close()
$desiredFile.Dispose()


$text = $text -replace $reg, $(${1}) -join "`r`n"
    #update file with new content
$desiredFile = [System.IO.StreamWriter]($configFile).Open()
$desiredFile.BaseStream.SetLength(0)

# Insert the $text to the file and close
$desiredFile.Write($text)
$desiredFile.Flush()
$desiredFile.Close()

# Write the changes and close the zip file
$zip.Dispose()

Итак, как я могу динамически заменять содержимое Regex внутри "__" и обрабатывать это содержимое как переменную, которая должна смотреть на переменные конвейера и заменять ее в строке:

$text = $text -replace $reg, $(${1}) -join " r n"

Ответы [ 2 ]

1 голос
/ 28 апреля 2020

Если вы не можете использовать Replace Tokens или Преобразовать файл Web.config , вот что:

В зависимости от того, что web.config файл содержит:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For ...
  -->
<configuration>
..
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="checkVatBinding" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="__WebService__" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="WebServiceClient.ServiceSoap" name="NLSService" />
      <endpoint address="__AuditService__" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Audit" contract="AuditApiService.Audit" name="AuditService" />
    </client>
  </system.serviceModel>
</configuration>

Вы можете попробовать следующее:

# Get all the file in a single var in spite of an array    
$data = Get-Content "D:\temp\web.config" -raw
$reg = [Regex]::new( '__(.*?)__', [System.Text.RegularExpressions.RegexOptions]::Singleline)
# Here are the vars with the final values
$WebService = "http://Aurillac.fr"
$AuditService = "http://Cantal.fr"
# Here is how to replace
$reg.replace($data, {param ($p);return (Get-Variable -Name $p.groups[1]).Value})

Пояснения:

  • -raw в Get-Content позволяет получить все символы в одиночная строка

  • Я использую класс .NET RegEx с опцией Singleline, чтобы разрешить поиск по переводу строки возврата по кариозу (возможно, не обязательно)

  • Я использую метод Regex Replace с методом MatchEvaluator Delegate, переведенным в PowerShell Scriptblock, чтобы получить переменную с именем, перехваченным RegEx.

Это дает:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For ...
  -->
<configuration>
..
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="checkVatBinding" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://Aurillac.fr" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="WebServiceClient.ServiceSoap" name="NLSService" />
      <endpoint address="http://Cantal.fr" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Audit" contract="AuditApiService.Audit" name="AuditService" />
    </client>
  </system.serviceModel>
</configuration>
0 голосов
/ 28 апреля 2020

Есть ли причина, по которой вы не можете использовать задачу «Заменить жетоны» из магазина? Это мой go -to для замены значений в конфигурационных файлах.

https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens

...