Terraform Workspaces with AWS Elastic Kubernetes Service

If you're a Cloud Engineer working with several environments in different AWS accounts, you definitely should try Terraform Workspaces.

Terraform Workspaces is a reliable way to handle projects with more than one environment managed from a specific account to another.

The diagram below shows what I'm doing in this lab:

Let's say that you have an account for DevOps team. This account will be responsible for provisioning and managing other environments as well, like Staging and Production. In this case, we will provision a Kubernetes cluster in each account using AWS EKS.

First of all, pay attention to your backend S3 configuration. If your .tfstates files will be stored on your DevOps account you should configure the workspace_key_prefix. With these configurations you'll have a structure like that:

Where your workspace_key_prefix is your project-name and the environment name will be created automatically by Terraform Workspaces.

Here's the backend S3 manifest

In your Prod and Staging account, you must create manually an IAM role in order to attach the permission to DevOps account.

In your DevOps account, add the assume role/policy to your user, group, or instance.

Configure workspace in your Terraform manifests. Create a file for each environment with AWS region, account, and role

# Staging.tfvars - Staging Environment

aws_region = "us-east-1"
aws_account = "<AWS_ACCOUNT_ID>"
aws_role = "<IAM_CROSS_ACCOUNT_ROLE>"

Setup the provider with the assume role resource, and variable.tf files with roles definitions

# Variables.tf file

variable "provider_env_roles" {
type = map
default = {
"staging" = "arn:aws:iam::<AWS_ACCOUNT_ID>:role/<IAM_ROLE>"
"prod" = "arn:aws:iam::<AWS_ACCOUNT_ID>:role/<IAM_ROLE>"
}
}

Now let's create the workspace and start creating the environment. In this example, I'm creating both workspaces and provisioning a Staging environment.

In this lab, I'm using Terraform v0.13.7.

Well, this is it! Enjoy it.

DevOps / Cloud Engineer 🇨🇦