terraform

Getting state list with resource IDs


I want to get the full list of objects managed by terraform and their IDs.

I know that I can run terraform state list to get all the resources in the state.

I also know that I can run terraform state show <resource> to get a detailed information about it, including it's ID.

So naturally I created the following script:

for resource in $(terraform state list); do ID=$(terraform state show $resource | grep -E " id\s*=" | head -n 1 | awk -F " = " '{print $2}'); echo "$resource $ID"; done

Which runs on all the resources from the state list and adds them their ID.

My problem is that for big configurations of 100+ resources this script will take a long time to complete.

Is there a way to speed it up? Or maybe m approach is not the best one and there is a more efficient way to achieve the thing I'm looking for?


Thanks to Paolo I was able to get all the resources in one command.

Alternative solution with grep+awk instead of jq is this:

terraform show | grep -e '^ id ' -e '^# ' | awk '/^# / { gsub(/^# /, "", $0); gsub(/:$/, "", $0); printf "%s ", $0; getline; print $3 }'


Solution

  • This should give you the desired output:

    $ terraform show -json | jq -r '[try .values.root_module.resources[], try .values.root_module.child_modules[].resources[]][] | [.address, .values.id] | @tsv'