This content originally appeared on DEV Community and was authored by DEV Community
Terraform workspaces allow for isolated state environments. When developing on AWS, it may be helpful to use local containers for cost savings and temporary environments. Local deployments can be accomplished through dynamic blocks and workspace environments.
Define AWS Provider
We will initialize the provider block with our region configuration in our terraform directory. Then with the use of dynamic blocks, we can set individual endpoints. In this case, we want to configure the DynamoDB endpoint. If using localstack, you can expand this to a larger array of services.
provider "aws" {
region = "us-east-2"
dynamic "endpoints" {
for_each = terraform.workspace == "local" ? [1] : []
content {
dynamodb = "http://localhost:8000"
}
}
}
Create Dynamo Resource
resource "aws_dynamodb_table" "workspaces" {
name = "workspaces"
billing_mode = "PROVISIONED"
read_capacity = 1
write_capacity = 1
hash_key = "id"
attribute {
name = "id"
type = "S"
}
}
Start dynamo docker container
docker run --rm -d -p 8000:8000 amazon/dynamodb-local
Create and Select Workspace
If this is the first time, you will want to create the local workspace:
terraform workspace new local
Otherwise, if switching between local and the default workspace
terraform workspace select local
Run Terraform Apply
~ terraform apply
...
aws_dynamodb_table.workspaces: Creating...
aws_dynamodb_table.workspaces: Creation complete after 0s [id=workspaces]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Now we can validate the table exists locally and not in AWS
### Remote
~ aws dynamodb list-tables
{
"TableNames": []
}
### Local
~ aws dynamodb list-tables --endpoint http://localhost:8000
{
"TableNames": [
"workspaces"
]
}
Provision in AWS
To provision the resource now in AWS you can switch back to the default namespace, and run terraform apply again.
~ terraform workspace select default
~ terraform apply -auto-approve
...
aws_dynamodb_table.workspaces: Creating...
aws_dynamodb_table.workspaces: Still creating... [10s elapsed]
aws_dynamodb_table.workspaces: Creation complete after 13s [id=workspaces]
~ aws dynamodb list-tables
{
"TableNames": [
"workspaces"
]
}
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-14T00:38:59+00:00) Terraform Workspaces for Local AWS Development. Retrieved from https://www.scien.cx/2022/03/14/terraform-workspaces-for-local-aws-development/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.