Skip to content

Instantly share code, notes, and snippets.

@janisBerz
Created February 1, 2022 09:47
Show Gist options
  • Save janisBerz/40133e247fc7c30a29d4504ff6e3976b to your computer and use it in GitHub Desktop.
Save janisBerz/40133e247fc7c30a29d4504ff6e3976b to your computer and use it in GitHub Desktop.
TF cleanup
$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