Recently I needed to refactor some terraform solutions we were moving around. I had quite a big service bus terraform solution we wanted to break up into smaller more managable parts.

It is easy enough to move resource definitions to the different workspaces but the problem is the resources already exist so when you run terraform or your pipeline runs it then it will fail because they already exist and it wont auto-import them. Auto import would be cool but I can understand there are complexities which make it difficult.

Anyway I hate the idea of manually writing all of the import commands so I put together the following powershell script which will read the state file and then generate an import command for every resource in the file.

$folder = 'C:\Users\Michael\source\repos\[My Solution]'

$stateFilePath = $folder + '\' + 'terraform.tfstate'
$outputFile = $folder + '\' + 'importfileoutputs.txt'

$sb = [System.Text.StringBuilder]::new()

$stateJson = Get-Content -Raw -Path $stateFilePath | ConvertFrom-Json

$resources = $stateJson.resources
foreach($resource in $resources){
    $terraformResourceType = $resource.type
    $terraformResourcename = $

    foreach($instance in $resource.instances){
        $terraformResourceId = $

        $text = 'terraform import ' + $terraformResourceType + '.' + $terraformResourcename + ' ' + $terraformResourceId


Set-Content -Path $outputFile -Value $sb.ToString()

Once I had my file with all of the import commands I could parameterise then just with find/replace (Id probably make the script do this if I had more time).

I then take the parameterised import commands and put them in a batch file in the workspace and then just make my devops pipeline run the commands the next time it runs and it will import all of the resources to the state for that environment.

I then remove the commands from the batch file so they dont run on future pipeline runs.

Anyway it saved me ages on this refactoring and hopefully it helps someone else and if anyone has better ways to do this id love to hear about them.


Buy Me A Coffee