Is there any way to generate terraform configuration from tfstate file

I want terraform resource configuration (.tf) file from tfstate(.json) for each resource…as i’m importing resource so i dont have configuration file for that resource…only state file is upgrading whenever i import resource by using terraforming tool.

Hi @Aliabbask08!

terraform import adds the resource into the state file but it will not generate a Terraform resource configuration for it in its *.tf (reference here). With the coming of 0.12, it might be feature we can more confidently develop. Additional context in the Github issue!

In the meantime, you might be able to write some code to transform the JSON of the resource in the state file to Terraform’s JSON Configuration Syntax. For example, given I imported a resource into the state file as such:

{
  "mode": "managed",
  "type": "aws_vpc",
  "name": "default",
  "provider": "provider.aws",
  "instances": [
    {
      "schema_version": 1,
      "attributes": {
        "arn": "arn:aws:ec2:xxxxxxx:xxxxxxxxxxxx:vpc/vpc-xxxxxxxxxxxxxxxxx",
        "assign_generated_ipv6_cidr_block": false,
        "cidr_block": "10.0.0.0/16",
        "default_network_acl_id": "acl-xxxxxxxxxxxxxxxxx",
        "default_route_table_id": "rtb-xxxxxxxxxxxxxxxxx",
        "default_security_group_id": "sg-xxxxxxxxxxxxxxxxx",
        "dhcp_options_id": "dopt-970eeff2",
        "enable_classiclink": false,
        "enable_classiclink_dns_support": false,
        "enable_dns_hostnames": true,
        "enable_dns_support": true,
        "id": "vpc-xxxxxxxxxxxxxxxxx",
        "instance_tenancy": "default",
        "ipv6_association_id": "",
        "ipv6_cidr_block": "",
        "main_route_table_id": "rtb-xxxxxxxxxxxxxxxxx",
        "tags": {
          "Name": "my-vpc"
        }
      }
    }
  ]
}

I can restructure the JSON by grabbing the attributes from the resource’s state and mapping it into JSON configuration syntax below.

{
  "resource": {
    "aws_vpc": {
      "default": {
        "assign_generated_ipv6_cidr_block": false,
        "cidr_block": "10.0.0.0/16",
        "default_network_acl_id": "acl-xxxxxxxxxxxxxxxx",
        "default_route_table_id": "rtb-xxxxxxxxxxxxxxxx",
        "default_security_group_id": "sg-xxxxxxxxxxxxxxxx",
        "dhcp_options_id": "dopt-970eeff2",
        "enable_classiclink": false,
        "enable_classiclink_dns_support": false,
        "enable_dns_hostnames": true,
        "enable_dns_support": true,
        "id": "vpc-xxxxxxxxxxxxxxxx",
        "instance_tenancy": "default",
        "ipv6_association_id": "",
        "ipv6_cidr_block": "",
        "main_route_table_id": "rtb-xxxxxxxxxxxxxxxx",
        "tags": {
          "Name": "my-vpc"
        }
      }
    }
  }
}

When you run terraform plan on the resource JSON configuration above, it will treat it as another Terraform resource. HOWEVER - you’ll still need to do some refactor to pass the arguments dynamically.

Hope this helps!