问题
I created an AWS resource in the AWS management console. I then ran terraform import
to import the AWS resource into Terraform. Now I have this terraform.tfstate
file. But how can I convert this back to a Terraform configuration file?
回答1:
As the terraform import docs explain, currently Terraform will only import the resource into your state file and won't generate the config for you.
If you try this without even defining the resource Terraform will throw an error telling you to define the resource and even providing a bare bones example:
Error: resource address "aws_instance.foo" does not exist in the configuration.
Before importing this resource, please create its configuration in the root module. For example:
resource "aws_instance" "foo" {
# (resource arguments)
}
If you were to then take that config and put that into a .tf
file for Terraform to use it should import fine but a plan will tell you that it's missing required fields:
Error: aws_instance.foo: "ami": required field is not set
Error: aws_instance.foo: "instance_type": required field is not set
If you then add those required fields and run a plan again Terraform will then show you the diff you have between the resource you imported and the changes the config wants to apply. You probably then want to go back to your config and align these so your plan is empty and then apply it. At that point it's as if Terraform originally created the resource and will then proceed to manage it as part of the resource lifecycle.
来源:https://stackoverflow.com/questions/49486300/how-to-convert-terraform-tfstate-to-config-file