Unable to terraform import s3 bucket state

1.1k Views Asked by At

I prepared a terraform script to provision some s3 buckets as below:

resource "aws_s3_bucket" "my_buckets" {
  count = length(var.bucket_config)
  bucket = "${var.bucket_config[count.index].name}-${terraform.workspace}"
  tags = {...}
}

The script works fine when I deploy to dev environment. However, some of buckets have already been manually created in production environment hence the script fails during deployment.

I tried to use terraform import to sync the state:

terraform import aws_s3_bucket.my_buckets arn:aws:s3:::bucket1-prod 

and I received error:

aws_s3_bucket.my_buckets: Importing from ID "arn:aws:s3:::bucket1-prod"...
aws_s3_bucket.my_buckets: Import prepared!
  Prepared aws_s3_bucket for import
aws_s3_bucket.my_buckets: Refreshing state... [id=arn:aws:s3:::bucket1-prod]
╷
│ Error: reading Amazon S3 (Simple Storage) Bucket (arn:aws:s3:::bucket1-prod): InvalidARNError: invalid ARN
│ caused by: invalid Amazon s3 ARN, unknown resource type, arn:aws:s3:::bucket1-prod
│ 
│ 
╵

I have double triple confirmed the ARN is a valid ARN (I copy/pasted), so wonder what I'm doing wrong here? I did try to double/single quote the ARN too.

Folloiwing @Marcin's answer below, I tried

terraform import aws_s3_bucket.my_buckets[0] bucket1-prod 

It indeed solved the ARN issue but failed me with error:

no matches found: aws_s3_bucket.my_buckets[0]

When I exam my plan, I found output entries like below:

  # aws_s3_bucket.my_buckets[0] will be created
  + resource "aws_s3_bucket" "my_buckets" { ... }

Note the resource is addressed as "aws_s3_bucket" "my_buckets" instead of "aws_s3_bucket" "my_buckets[0]". It's probably why I can't use [0] in my import statement. Am I doing something wrong with the count looping?

P.S. I did validate that [0] is the correct index based on the comments in the plan output.

When I run the following command, it works but only for one bucket.

terraform import aws_s3_bucket.my_buckets bucket1-prod 
1

There are 1 best solutions below

6
On

You have to specify instance index which you are importing as you are using count and also use a bucket name, e.g.

terraform import aws_s3_bucket.my_buckets[0] bucket1-prod