Skip to content

Commit

Permalink
token replacement scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
eriqua committed Sep 18, 2023
1 parent 24ba586 commit 18fce73
Show file tree
Hide file tree
Showing 2 changed files with 196 additions and 0 deletions.
107 changes: 107 additions & 0 deletions avm/utilities/pipelines/tokensReplacement/Convert-TokensInFileList.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<#
.SYNOPSIS
This Function Helps with Testing A Module Locally
.DESCRIPTION
This Function aggregates all the different token types (Default and Local) and then passes them to the Convert Tokens Script to replace tokens in a parameter file
.PARAMETER FilePathList
Mandatory. The list of file paths that contain tokens to be replaced.
.PARAMETER Tokens
Mandatory. An object containing the parameter file tokens to set
.PARAMETER TokenPrefix
Mandatory. The prefix used to identify a token in the parameter file (i.e. <<)
.PARAMETER TokenSuffix
Mandatory. The suffix used to identify a token in the parameter file (i.e. >>)
.PARAMETER SwapValueWithName
Optional. A boolean that enables the search for the original value and replaces it with a token. Used to revert configuration. Default is false
.PARAMETER OutputDirectory
Optional. A string for a custom output directory of the modified parameter file
.NOTES
- Make sure you provide the right information in the objects that contain tokens. This is in the form of
@(
@{ Name = 'tenantId'; Value = '12345678-1234-1234-1234-123456789123' }
- Ensure you have the ability to perform the deployment operations using your account
- If providing TokenKeyVaultName parameter, ensure you have read access to secrets in the key vault to be able to retrieve the tokens.
#>

function Convert-TokensInFileList {
[CmdletBinding()]
param (
[parameter(
Mandatory = $true,
ValueFromPipeline = $true
)]
[String[]] $FilePathList,

[parameter(Mandatory = $true)]
[hashtable] $Tokens,

[parameter(Mandatory = $true)]
[string] $TokenPrefix,

[parameter(Mandatory = $true)]
[string] $TokenSuffix,

[parameter(Mandatory = $false)]
[bool] $SwapValueWithName = $false,

[parameter(Mandatory = $false)]
[string] $OutputDirectory
)

begin {
# Load used funtions
. (Join-Path $PSScriptRoot 'helper' 'Convert-TokenInFile.ps1')
}

process {
# Combine All Input Token Types, Remove Duplicates and Only Select entries with on empty values
$FilteredTokens = ($Tokens | Sort-Object -Unique).Clone()
@($FilteredTokens.Keys) | ForEach-Object {
if ([String]::IsNullOrEmpty($FilteredTokens[$_])) {
$FilteredTokens.Remove($_)
}
}
Write-Verbose ('Using [{0}] tokens' -f $FilteredTokens.Keys.Count)

# Apply Prefix and Suffix to Tokens and Prepare Object for Conversion
Write-Verbose ("Applying Token Prefix '$TokenPrefix' and Token Suffix '$TokenSuffix'")
foreach ($Token in @($FilteredTokens.Keys)) {
$newKey = -join ($TokenPrefix, $Token, $TokenSuffix)
$FilteredTokens[$newKey] = $FilteredTokens[$Token] # Add formatted entry
$FilteredTokens.Remove($Token) # Replace original
}
# Convert Tokens in Parameter Files
try {
foreach ($FilePath in $FilePathList) {
# Prepare Input to Token Converter Function
$ConvertTokenListFunctionInput = @{
FilePath = $FilePath
TokenNameValueObject = $FilteredTokens.Clone()
SwapValueWithName = $SwapValueWithName
}
if ($OutputDirectory) {
$ConvertTokenListFunctionInput += @{OutputDirectory = $OutputDirectory }
}
# Convert Tokens in the File
Convert-TokenInFile @ConvertTokenListFunctionInput
$ConversionStatus = $true
}
} catch {
$ConversionStatus = $false
Write-Verbose $_.Exception.Message -Verbose
}
}
end {
Write-Verbose "Token Replacement Status: $ConversionStatus"
return [bool] $ConversionStatus
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<#
.SYNOPSIS
Recieves an Input Object of Name/Value and Searches the Current File for the Name and Replaces it with the Value
.DESCRIPTION
Recieves an Input Object of Name/Value and Searches the Current File for the Name and Replaces it with the Value
.PARAMETER FilePath
Mandatory. Full Path for the file that contains the strings that need to be replaced. Supports multiple files comma seperated.
.PARAMETER TokenNameValueObject
Mandatory. An Object that contains the Name Key and Value Key For replacing tokens in files. See Example for structure.
.PARAMETER SwapValueWithName
Optional. A Boolean That swaps the tokens in the TokenNameValueObject Object. Used to find the Value and Swap with the Name instead. Default is False
.EXAMPLE
$Object = @(
@{ Name = "TextA"; Value = "TextB" }
@{ Name = "TextC"; Value = "TextD" }
)
Convert-TokenInFile -FilePath 'C:\fileA.txt','C:\fileB.txt' -TokenNameValueObject $Object
.EXAMPLE
$Object = @(
@{ Name = "TextA"; Value = "TextB" }
@{ Name = "TextC"; Value = "TextD" }
)
Convert-TokenInFile -FilePath 'C:\fileA.txt','C:\fileB.txt' -TokenNameValueObject $Object -OutputDirectory 'C:\customDirectory'
.EXAMPLE
$Object = @(
@{ Name = "TextA"; Value = "TextB" }
@{ Name = "TextC"; Value = "TextD" }
)
Convert-TokenInFile -FilePath 'C:\fileA.txt','C:\fileB.txt' -TokenNameValueObject $Object -SwapValueWithName $true
#>
function Convert-TokenInFile {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string[]] $FilePath,

[Parameter(Mandatory, ValueFromPipeline = $true)]
[psobject] $TokenNameValueObject,

[Parameter(Mandatory = $false)]
[string] $OutputDirectory,

[Parameter(Mandatory = $false)]
[bool] $SwapValueWithName = $false
)
# Swap Value with Name instead
if ($SwapValueWithName) {
Write-Verbose "Swapping 'Value' with 'Name'"
@($TokenNameValueObject.Keys) | ForEach-Object {
$newKey = $TokenNameValueObject[$_]
$TokenNameValueObject[$newKey] = $_ # Add swapped entry
$TokenNameValueObject.Remove($_) # Remove original
}
}
# Begin the Replace Function
# Process Path for Token Replacement
foreach ($Path in $FilePath) {
# Extract Required Content From the Input
try {
$File = Get-Content -Path $Path
$FileName = Split-Path -Path $Path -Leaf
} catch {
throw $PSItem.Exception.Message
}
Write-Verbose "Processing Tokens for file: $FileName"
# Perform the Replace of Tokens in the File
$TokenNameValueObject.Keys | ForEach-Object {
# If type is secure string
if ($TokenNameValueObject[$_] -is [System.Security.SecureString]) {
$TokenNameValueObject[$_] = $TokenNameValueObject[$_] | ConvertFrom-SecureString -AsPlainText
}
$File = $File -replace [Regex]::Escape($_), $TokenNameValueObject[$_]
}
# Set Content
if ($OutputDirectory -and (Test-Path -Path $OutputDirectory -PathType Container)) {
# If Specific Output Directory Provided
$Path = Join-Path $OutputDirectory $FileName
}
# Set Content
$File | Set-Content -Path $Path
}
}

0 comments on commit 18fce73

Please sign in to comment.