我在AWS管理控制台中创建了一个AWS资源。然后我运行terraform import
将AWS资源导入Terraform。现在我有了这个terraform.tfstate
文件。但是如何将其转换回Terraform配置文件?
答案 0 :(得分:2)
正如terraform import
docs解释的那样,目前Terraform只会将资源导入您的州档案,并且不会为您生成配置。
如果您在没有定义资源的情况下尝试此操作,Terraform将抛出一个错误,告诉您定义资源,甚至提供一个简单的例子:
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)
}
如果您要将该配置放入.tf
文件中以供Terraform使用,则应该导入正常但计划会告诉您它缺少必填字段:
Error: aws_instance.foo: "ami": required field is not set
Error: aws_instance.foo: "instance_type": required field is not set
如果您随后添加了这些必填字段并再次运行计划,Terraform将显示您导入的资源与配置要应用的更改之间的差异。您可能希望返回到您的配置并对齐这些,以便您的计划为空,然后应用它。此时,Terraform最初创建了资源,然后将其作为资源生命周期的一部分进行管理。
答案 1 :(得分:1)
您可以使用terraform show命令生成tf文件的原型,如下所示:
# terraform show
命令输出为:
# tencentcloud_instance.ajaxhe_ins:
resource "tencentcloud_instance" "ajaxhe_ins" {
allocate_public_ip = true
availability_zone = "ap-hongkong-2"
create_time = "2020-01-23T11:09:28Z"
expired_time = "2020-05-24T09:41:36Z"
id = "ins-59xsw9ji"
image_id = "img-31tjrtph"
instance_charge_type = "PREPAID"
instance_charge_type_prepaid_renew_flag = "NOTIFY_AND_MANUAL_RENEW"
instance_name = "centos-1GB--2170"
instance_status = "RUNNING"
instance_type = "S2.SMALL1"
internet_charge_type = "BANDWIDTH_PREPAID"
internet_max_bandwidth_out = 1
private_ip = "172.18.1.0"
project_id = 0
public_ip = "129.173.115.221"
running_flag = true
security_groups = [
"sg-lxlzf8fn",
]
subnet_id = "subnet-3a05z4r3"
system_disk_id = "disk-b0p7allu"
system_disk_size = 50
system_disk_type = "CLOUD_PREMIUM"
tags = {}
vpc_id = "vpc-g3q13u9g"
}
然后,删除不可更改的配置,例如:id,public_ip,instance_status等。
最终的main.tf文件可能如下所示:
# tencentcloud_instance.ajaxhe_ins:
resource "tencentcloud_instance" "ajaxhe_ins" {
allocate_public_ip = true
availability_zone = "ap-hongkong-2"
create_time = "2020-01-23T11:09:28Z"
image_id = "img-31tjrtph"
instance_charge_type = "PREPAID"
instance_charge_type_prepaid_renew_flag = "NOTIFY_AND_MANUAL_RENEW"
instance_name = "centos-1GB--2170"
instance_status = "RUNNING"
instance_type = "S2.SMALL1"
internet_charge_type = "BANDWIDTH_PREPAID"
internet_max_bandwidth_out = 1
private_ip = "172.18.1.0"
project_id = 0
running_flag = true
security_groups = [
"sg-lxlzf8fn",
]
subnet_id = "subnet-3a05z4r3"
system_disk_id = "disk-b0p7allu"
system_disk_size = 50
system_disk_type = "CLOUD_PREMIUM"
tags = {}
vpc_id = "vpc-g3q13u9g"
}