Importing an AWS S3 Bucket with Terraform 🪣

Terraform Imports

The terraform docs are great, but sometimes I need a straight forward example of how to do something before I can fully understand the docs. Hashicorp does have a number of hands on tutorials that help too; here is the one for importing resources.

This is a straight forward example of importing a single AWS S3 bucket into terraform.

Terraform import block

The main thing is to use a terraform import block to import the resource into terrafrom management. If we have an S3 bucket called my_bucket we can import it with the following block:

1
2
3
4
import "aws_s3_bucket" "my_bucket" {
    to = aws_s3_bucket.bucket
    id = "bucket-name"
}

Then you want a corresponding resource block for the my_bucket:

1
2
3
resource "aws_s3_bucket" "bucket" {
    bucket = "my_bucket"
}

You'll want to match the configuration of your S3 bucket as closely as possible. You can do that by mathcing the bucket properties you see in the AWS console with the terraform docs for the aws_s3_bucket resource.

Or you can use the terraform plan command and examine the plan output to see what details it is trying to import and match those against reality. Sometimes this technique can give you a good head start on the configuration and then you just iron out a few details rather than all the details.

Benefits of Importing Resources

Importing resources into Terraform offers several advantages:

  • Version Control: Track and manage your resource's configuration alongside your other infrastructure code for consistency and reproducibility.
  • Disaster Recovery: Easily recreate your resources using your Terraform configuration, minimizing downtime and data loss.
  • Automation: Integrate resource management into your infrastructure provisioning workflows, enabling automated creation, deletion, and updates.

Conclusion

Importing resources into Terraform lets you seamlessly integrate your IaC workflows. It safeguards your resources, simplifies management, and paves the way for automated infrastructure provisioning. By following these steps and understanding the benefits, you can effectively leverage Terraform to preserve and manage your valuable infrastructure.

Integrating IaC, especially when you have many existing resources already, is a process. You start with a few resources and then add more as you get comfortable with the process. It's a great way to learn about the resources you are managing and to get a better understanding of how they are configured.

📨 Contact GSPC ✉️

AWS Certified Certified Terraform Associate AWS Serverless AWS Certified Developer Associate GitHub Foundations Certification GitHub Actions Certification Certified SysOps Administrator