DEV Community

Kit Sunde
Kit Sunde

Posted on • Updated on

Rename your terraform workspace on s3.

There's always a workspace default in terraform as it's natural to start with it, then create a second workspace production. But default isn't a good name for staging and it doesn't map onto branches.

It's rather simple to move the workspace though if you look into an s3 bucket with the workspace:

$ aws s3 ls --recursive s3://mediapop-tfstate
2018-06-08 17:28:47      92004 env:/production/terraform
2018-06-02 14:08:00      44605 terraform
Enter fullscreen mode Exit fullscreen mode

These two files are the .tfstate files you're used to seeing locally, it's pretty obvious by the name which file belongs to what workspace. So lets rename it into staging.

$ aws s3 mv s3://mediapop-tfstate/terraform s3://mediapop-tfstate/env:/staging/terraform
Enter fullscreen mode Exit fullscreen mode

We've now renamed the default workspace to the staging workspace and can do:

$ terraform workspace change staging
$ terraform plan

...

No changes. Infrastructure is up-to-date.
Enter fullscreen mode Exit fullscreen mode

If you're using DynamoDB for locking you'll also need to rename the lock. Or you'll receive this message:

Error refreshing state: state data in S3 does not have the expected content.

This may be caused by unusually long delays in S3 processing a previous state
update. Please wait for a minute or two and try again. If this problem
persists, and neither S3 nor DynamoDB are experiencing an outage, you may need
to manually verify the remote state and update the Digest value stored in the
DynamoDB table to the following value

Get the digest of the old lock:

$ aws dynamodb get-item  --key '{"LockID": {"S": "mediapop-tfstate/terraform-md5"}}' --table-name mediapop-tfstate
Enter fullscreen mode Exit fullscreen mode

Outputs:

{
    "Item": {
        "Digest": {
            "S": "9a9098da0fd7e3a11d57fc5d9718e095"
        },
        "LockID": {
            "S": "mediapop-tfstate/terraform-md5"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Create a new file staging.json and rename the lock:

{
    "Digest": {
        "S": "9a9098da0fd7e3a11d57fc5d9718e095"
    },
    "LockID": {
        "S": "mediapop-tfstate/env:/staging/terraform-md5"
    }
}
Enter fullscreen mode Exit fullscreen mode

Then push the item to dynamodb:

aws dynamodb put-item --item file://staging.json --table-name mediapop-tfstate
Enter fullscreen mode Exit fullscreen mode

Delete the old default lock:

aws dynamodb remove-item  --key '{"LockID": {"S": "mediapop-tfstate/terraform-md5"}}' --table-name mediapop-tfstate
Enter fullscreen mode Exit fullscreen mode

Top comments (0)