Skip to content

Instantly share code, notes, and snippets.

@fgauna12
Created February 16, 2022 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgauna12/fe4db1d71fd4e146a91435059b62f6a8 to your computer and use it in GitHub Desktop.
Save fgauna12/fe4db1d71fd4e146a91435059b62f6a8 to your computer and use it in GitHub Desktop.
Finds all tokens in a string when surrounded by curly brackets. Values are substituted from environment variables. Perfect for CI/CD pipelines.
<#
.SYNOPSIS
Replace tokens in a file with values from environment variables.
.DESCRIPTION
Finds tokens in a given file and replace them with values from environment variables. It is best used to replace configuration values in a release pipeline.
Tokens are found when enclosed with curly brackets. For eample: {{ foo }}
.EXAMPLE
$env:URL="http://localhost:8080"
$env:USERNAME="admin"
$env:PASSWORD="Test123"
config.template.json:
{
"url": "{{URL}}",
"username": "{{ USERNAME }}",
"password": "{{PASSWORD}}"
}
. ./Find-ReplaceToken.ps1
Find-ReplaceToken -String (Get-Content config.template.json -Raw) | Out-File config.json
config.json (result):
{
"url": "http://localhost:8080",
"username": "admin",
"password": "Test123"
}
.NOTES
Inspired by this other Gist: https://gist.github.com/niclaslindstedt/8425dbc5db81b779f3f46659f7232f91
#>
function Get-EnvironmentVariable {
param (
$Variable
)
(Get-Item -Path Env:$Variable).Value
}
function Find-ReplaceToken {
[CmdletBinding()]
param(
[string]$String
)
$Result = $String | Select-String -Pattern "\{\{ ?(\w*?) ?\}\}" -AllMatches
$EnvironmentVariablesMap = @{}
foreach($Match in $Result.Matches){
if ($Match.Groups)
{
for($i = 1; $i -lt $Match.Groups.Count; $i++){
$VariableName = $Match.Groups[$i].Value
$VariableValue = Get-EnvironmentVariable -Variable $VariableName
$EnvironmentVariablesMap[$VariableName] = $VariableValue
}
}
}
foreach($Entry in $EnvironmentVariablesMap.GetEnumerator()){
$String = $String -replace "\{\{ ?($($Entry.Key)*?) ?\}\}",$Entry.Value
}
$String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment