简体   繁体   中英

import an existing bucket in terraform

I wanted to create an event notification on an existing s3_bucket (which is not setup by me in this current terraform code).

I came across this answer:

terraform aws_s3_bucket_notification existing bucket

so I tried this. Here, local.bucket_name is the name of the existing bucket.

notification.tf

resource "aws_s3_bucket" "trigger_pipeline" {
  bucket = local.bucket_name
}

terraform import aws_s3_bucket.trigger_pipeline local.bucket_name

However, I am not sure how to use this import statement. Do I use it after the resource block? Do I use it in the beginning of the same file?

If I use it as it is, under the resource block, I get this error:

Invalid block definition: Either a quoted string block label or an opening brace ("{") is expected here.HCL

at the dot here: aws_s3_bucket.trigger_pipeline

Edit:

So first I defined s3 resource as shown in the question above. Then I run terraform init . Next, I run terraform import aws_s3_bucket.trigger_pipeline "myoriginalbucketname" on the CLI. However, I still get the error that:

Before importing this resource, please create its configuration in the root module. For example:

resource "aws_s3_bucket" "trigger_pipeline" {
  # (resource arguments)
}

I guess I am getting the sequence of events wrong

I would suggest you to use data block here. Data Block allows to use information defined outside of Terraform which helps to execute Terraform code on an existing infrastructure resources(read more here ), in this case it's S3 Bucket. Like resource block, data block support arguments to specify how they behave; for aws_s3_bucket it's "bucket"( read more here ).

data "aws_s3_bucket" "trigger_pipeline" {
bucket = "local.bucket_name"
}
// use data.aws_s3_bucket.trigger_pipeline.<attribute_reference> in script

resource "aws_s3_bucket_notification" "bucket_notification" {
bucket = data.aws_s3_bucket.trigger_pipeline.id
// your code block for Notification configuration
}

local.bucket_name executes in your bash, not in TF. You have to actually provide the full name:

terraform import aws_s3_bucket.trigger_pipeline "my-bucket-name"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM