DevOps by Patrik

Replace Placeholders in YAML Configs Using PowerShell

When managing configuration files (like YAML for CI/CD), you may need to replace placeholder values with actual items — for example, when working with multiple components or environments.

This guide shows how to automate two common tasks using PowerShell:

  1. Replacing a placeholder line with multiple entries.

  2. Dynamically inserting names where specific patterns are used.

Task 1: Replace a Placeholder Line with a List

Suppose your YAML file contains this line:

  - "{item}/**/*"

You can replace it with multiple entries, like:

  - "ServiceA/**/*"
  - "ServiceB/**/*"

PowerShell Example:

# Define the list of items
$itemList = "ServiceA,ServiceB" -split ',' | ForEach-Object { $_.Trim() }

# Read the YAML content
$content = Get-Content -Path "input.yml" -Raw

# Build the replacement block with correct indentation
$replacement = ($itemList | ForEach-Object { '  - "' + $_ + '/**/*"' }) -join "`n"

# Replace only the exact placeholder line
$content = $content -replace '(?m)^ {8}- "\{item\}/\*\*/\*"', $replacement

# Write the updated content
Set-Content -Path "output.yml" -Value $content

Using PowerShell to manage placeholders in configuration files helps streamline setup for dynamic environments or multiple components. These techniques are useful for automating CI/CD pipelines, especially when working with reusable templates and environment-specific configurations.

powershell
automation
templates
ci-cd
scripting

Comments