我有一个映射变量来标识现有的s3桶:
resource "aws_s3_bucket" "bucket" {
for_each = var.s3_replication
bucket = each.value.source
#other configuration
}
variable "s3_replication" {
description = "Map of buckets to replicate"
type = map
default = {
logs = {
source = "logs_bucket",
destination = "central_logs_bucket"
},
security = {
source = "cloudtrail_bucket",
destination = "central_security_bucket"
}
}
}
由于这些桶已经存在,我试图导入它们,然后将a配置应用于它们以更新资源。不幸的是,我无法弄清楚如何在这些上做地形导入。我试过:
terraform import aws_s3_bucket.bucket["logs"] logs_bucket
terraform import aws_s3_bucket.bucket[logs] logs_bucket
terraform import aws_s3_bucket.bucket[0] logs_bucket
terraform import aws_s3_bucket.bucket[0].source logs_bucket
terraform import aws_s3_bucket.bucket[0[source]] logs_bucket
所有失败都有不同的错误。任何关于如何导入现有资源在地图上列出的想法?
terraform import
子命令依赖于资源名称空间内map键中的字符串,这些字符串是第一类表达式,这会导致shell解释器的问题,其中资源不是第一类表达式,因为它们不是Terraform DSL。您可以通过将整个资源名称强制转换为字面值字符串来解决这个问题:
terraform import 'aws_s3_bucket.bucket["logs"]' logs_bucket
,这将解决您的问题。
在做import
之前,我建议做一个地球化的plan
。该计划的输出如下所示:
Terraform will perform the following actions:
# aws_s3_bucket.bucket["logs"] will be created
+ resource "aws_s3_bucket" "bucket" {
+ acceleration_status = (known after apply)
+ acl = "private"
+ arn = (known after apply)
+ bucket = "logs_bucket"
+ bucket_domain_name = (known after apply)
+ bucket_regional_domain_name = (known after apply)
+ force_destroy = false
+ hosted_zone_id = (known after apply)
+ id = (known after apply)
+ region = (known after apply)
+ request_payer = (known after apply)
+ tags_all = (known after apply)
+ website_domain = (known after apply)
+ website_endpoint = (known after apply)
+ versioning {
+ enabled = (known after apply)
+ mfa_delete = (known after apply)
}
}
# aws_s3_bucket.bucket["security"] will be created
+ resource "aws_s3_bucket" "bucket" {
+ acceleration_status = (known after apply)
+ acl = "private"
+ arn = (known after apply)
+ bucket = "cloudtrail_bucket"
+ bucket_domain_name = (known after apply)
+ bucket_regional_domain_name = (known after apply)
+ force_destroy = false
+ hosted_zone_id = (known after apply)
+ id = (known after apply)
+ region = (known after apply)
+ request_payer = (known after apply)
+ tags_all = (known after apply)
+ website_domain = (known after apply)
+ website_endpoint = (known after apply)
+ versioning {
+ enabled = (known after apply)
+ mfa_delete = (known after apply)
}
}
Plan: 2 to add, 0 to change, 0 to destroy.
有了这个计划,我们可以看到将要创建的资源可以作为aws_s3_bucket.bucket["logs"]
和aws_s3_bucket.bucket["security"]
的引用。我们可以这样导入它们,而不是执行apply
: Bash:
terraform import 'aws_s3_bucket.bucket["security"]' cloudtrail-bucket
terraform import 'aws_s3_bucket.bucket["logs"]' logs-bucket
Windows CMD:
terraform import 'aws_s3_bucket.bucket["security"]' cloudtrail-bucket
terraform import 'aws_s3_bucket.bucket["logs"]' logs-bucket
答案的语法是正确的。我的代码出故障了,因为它找不到varsfile。我需要添加-var-file={{路径到tfvars}}。所以最后的语法看起来像:
terraform import -var-file={{ path to tfvars}} 'aws_s3_bucket.bucket["logs"]' logs_bucket