0%
April 9, 2025

Import Existing Resources Into Terraform Project

terraform

Database

1resource "aws_db_instance" "billie" {
2  allocated_storage      = var.db_storage
3  engine                 = var.db_engine
4  engine_version         = var.db_engine_version
5  instance_class         = var.db_instance_class
6  db_name                = var.db_name
7  username               = var.db_username
8  password               = var.db_password
9  db_subnet_group_name   = var.db_aws_subnet_group.name
10  vpc_security_group_ids = [var.rds_security_group_id]
11  identifier             = var.db_identifier
12  storage_encrypted      = true
13  publicly_accessible    = true
14  skip_final_snapshot    = true # don't save the final snapshot when being destroyed
15  tags = {
16    Name = var.db_tag_name
17  }
18  lifecycle {
19    prevent_destroy = true
20
21    ignore_changes = [
22      db_name
23    ]
24  }
25  depends_on = [var.db_aws_subnet_group]
26}

Note that we have to add line-19 to avoid any mistake that deletes this resource (any adjustment that leads to a deletion will be forbiddened by terraform).

Line 21-23 simply ignore the mismatch between our own terraform dbname and the actual dbname (it doesn't quite matter to us for that mismatch).

Now to import the database, we execute:

terraform import aws_db_instance.billie <db-identifier>

Then

terraform apply -target=aws_db_instance.billie

to confirm the changes.

S3 Bucket

resource "aws_s3_bucket" "existing_bucket" {
  bucket = var.bucket_name

  tags = {
    Name        = "Billie File Sync Bucket"
    Environment = var.env
  }

  lifecycle {
    prevent_destroy = true
  }
}

For the same reason as rds resource we set prevent_destroy = true. And the import procedure is the same:

terraform import aws_s3_bucket.existing_bucket <bucket-name>

also

terraform apply -target=aws_s3_bucket.existing_bucket

to confirm the changes.

Potential Error and Summary

  • When importing existing resources terraform will scan the whole project, we will get an error if there are resources that cannot be determined in the planning stage.

    But very likely we are in a situation where we just want to deploy / import the database first without deploying any other resources (e.g., we just want to do it stage by stage, creating database is one of the milestones).

    In this case we just comment out all the resouces that are yet to be created, and then terraform import and terraform apply -target again.

  • Note that for terraform import the identifier that we should use may vary according to different resources, when in doubt we just need to check the documentation.