Skip to content

Instantly share code, notes, and snippets.

@walkness
Last active May 22, 2023 21:30
Show Gist options
  • Save walkness/b98799eafcc14b14e23ea501f6f040b6 to your computer and use it in GitHub Desktop.
Save walkness/b98799eafcc14b14e23ea501f6f040b6 to your computer and use it in GitHub Desktop.
Generates Terraform Import Commands for v4 AWS S3 Bucket Configuration Changes
const fs = require("fs");
const rawData = fs.readFileSync("plan.json");
const data = JSON.parse(rawData);
const changes = data.resource_changes.filter(
(c) =>
c.change.actions.indexOf("create") !== -1 &&
c.type.startsWith("aws_s3_bucket_")
);
const lines = changes.map((c) => {
let base = `terraform import ${c.address} ${c.change.after.bucket}`;
if (c.type === "aws_s3_bucket_acl") {
base = `${base},${c.change.after.acl}`;
}
return base;
});
console.log(lines.join("\n"));
@walkness
Copy link
Author

walkness commented Dec 7, 2022

This little script is helpful when upgrading the Terraform AWS provider from v3 to v4, which introduced significant changes to the AWS S3 bucket configuration that, I believe, requires importing existing resources to the new resources.

Assumes that a plan.json file has first been generated in the same directory as this script by running:

terraform plan -out "tfplan"
terraform show -json "tfplan" > plan.json

Running:

node importS3Resources.js

will not actually import any Terraform resources, but will produce a series of terraform import ... commands that can be used in a script to import all resources, e.g.:

terraform import aws_s3_bucket_acl.example example-bucket,private
terraform import aws_s3_bucket_server_side_encryption_configuration.example example-bucket

@walkness
Copy link
Author

Variation for moving Route53 zone to a different account:

const fs = require("fs");

const rawData = fs.readFileSync("plan.json");

const data = JSON.parse(rawData);

const changes = data.resource_changes.filter(
  (c) =>
    c.change.actions.indexOf("create") !== -1 && c.type === "aws_route53_record"
);

const lines = changes.map((c) => {
  const { zone_id, name, type } = c.change.after;
  let base = `terraform import ${c.address} ${zone_id}_${name}_${type}`;
  return base;
});

console.log(lines.join("\n"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment