Last active
April 12, 2023 13:43
-
-
Save veleek/e3a9374a182a3eebcee19651f98862e7 to your computer and use it in GitHub Desktop.
Migrate a set of resources from terragrunt folders into a single terraform state with multiple modules.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
This is a script that scrapes terraform for a set of terragrunt folders and extracts all the resources to | |
generate a set of `terraform import` statements that can be used to import the existing state into the | |
Terraform state. Note: This uses the `address` field of the resource to generate the import statement. | |
For resources like access policies that is not actually correct because the address uses `/` separators | |
for everything and the import expects them to be broken into three space separated components. You need | |
to identify these (mostly stuff with a `role/blahblah` in the path) and separate the role, account, and | |
project segments manually. | |
#> | |
cd $PSScriptRoot | |
cls | |
$modules = dir .\deploy\terragrunt -Directory | select -exp Name | |
$modules = @("pubsub") | |
$es = @("test", "stg", "prd") | select -First 1 | |
foreach ($e in $es) | |
{ | |
Write-Host "================ Creating $e =================" -ForegroundColor Yellow | |
$ms = Join-Path $PSScriptRoot "migrate-$e.ps1" | |
#Remove-Item $ms -ErrorAction SilentlyContinue | |
swe $e | |
#$env:TF_VAR_environment = $e | |
foreach($m in $modules) | |
{ | |
Write-Host " ----- Generating imports for $m ----- " -ForegroundColor DarkYellow | |
Add-Content -Path $ms "# Module $m" | |
cd (Join-Path $PSScriptRoot deploy\terragrunt $m) | |
tg init -reconfigure | |
$state = tg show -json | ConvertFrom-Json | |
$root = $state.values.root_module | |
foreach ($r in $root.resources) | |
{ | |
if($r.mode -eq "data") | |
{ | |
continue; | |
} | |
$migrateCommand = "terraform import 'module.$m.$($r.address)' '$($r.values.id)'" | |
Write-Host $migrateCommand -ForegroundColor Blue | |
Add-Content -Path $ms $migrateCommand | |
} | |
foreach ($child in $root.child_modules) | |
{ | |
foreach ($r in $child.resources) | |
{ | |
if($r.mode -eq "data") | |
{ | |
continue; | |
} | |
$migrateCommand = "terraform import 'module.$m.$($r.address)' '$($r.values.id)'" | |
Write-Host $migrateCommand -ForegroundColor Blue | |
Add-Content -Path $ms $migrateCommand | |
} | |
} | |
} | |
} | |
cd $PSScriptRoot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment