Search code examples
terraform

How can I list Terraform resources with their IDs


I want to move some Terraform resources from one repository to another. I reckon the simplest way to do that would be terraform import in one repository and terraform rm in the other.

With terraform state list I can get a list of resources, but without their ID. I thought I can combine that output with terraform state show but it's very slow and I have to parse out the ID from the HCL. Unfortunately there is no JSON output.

With terraform show -json I can get the whole state in JSON format, but there can be a lot of nesting of modules, so parsing that wouldn't be trivial either.

Are there any other options?

Edit 1:

terraform show -json for the relatively small repository I am working on gives me 2000 lines (too much to be sure of the format) starting with:

{
    "format_version": "0.1",
    "terraform_version": "0.14.9",
    "values": {
        "root_module": {
            "child_modules": [
                {
                    "address": "module.cloudtrail",
                    "child_modules": [
                        {
                            "address": "module.cloudtrail.module.cloudtrail_bucket",
                            "resources": [
                                {

I think there is at least one more level of nesting of child_modules. I think resources can be on every level. It's possible to get the list from that, but I don't think it's trivial.


Solution

  • I just realised that I kind of get what I want every time I do a terraform plan. But I don't want the plan, so I can do terraform refresh | sed s'|: Refreshing state... \[id=| |' | sed s'|\]$||'. It's a bit slow, but I get a list of resources with their ID.

    I can even add sed s'|^|terraform import |' > import.sh and import all the resources (or a part of them after an edit) with bash import.sh