Created
February 1, 2022 09:47
-
-
Save janisBerz/40133e247fc7c30a29d4504ff6e3976b to your computer and use it in GitHub Desktop.
TF cleanup
This file contains 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
$tfApplyResult = &terraform apply -auto-approve -json | |
$tfResultObjects = $tfApplyResult | ConvertFrom-Json | |
$try = 0 | |
if (($tfResultObjects.'@level' -match 'error').count -gt 0 -or $try -gt 5) { | |
Write-Host "Found $(($tfResultObjects.'@level' -match 'error').count) resources in error state." | |
Write-Host "Will try to import resources that are in error state." | |
foreach ($result in $tfResultObjects) { | |
if ($result.'@level' -eq "error") { | |
Write-Host "Removing state for $($result.diagnostic.address)." | |
&terraform state rm $($result.diagnostic.address) | |
$resourceId = [regex]::matches($result.'@message', '"[^"]*"').value[0] | |
if ($result.diagnostic.address) { | |
Write-Host "Importing Address: $($result.diagnostic.address); ID: $resourceId" | |
&terraform import $result.diagnostic.address $resourceId | |
} | |
} | |
} | |
$tfApplyResult = &terraform apply -auto-approve -json | |
$tfResultObjects = $tfApplyResult | ConvertFrom-Json | |
$try += 1 | |
} | |
$tfstate = &terraform state list | |
$tfAPIMResources = $tfstate -like "module.apim_api.azurerm_api*" | |
foreach ($state in $tfAPIMResources) { | |
Write-Host "Removing state for $state." | |
&terraform state rm $state | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment