Skip to main content

Cloud and deployment · Beginner · 20 min

Tag cloud resources so you know what costs what

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/aws 6.74 · AWS CLI 2.42.4

You will have a four-key tagging scheme applied to every AWS resource through Terraform default_tags, a script that lists resources missing a tag, a tag policy ready for your organisation and cost allocation tags that split the bill by project.

On this page

An AWS bill lists services: so much for EC2, so much for S3. It does not say which of those costs belong to the shop front, which to the staging copy someone forgot, and which to the experiment that ended in March. Tags fill that gap. A tag is a key and a value, such as Project=storefront, attached to a resource. Once every resource carries the same few keys, you can filter the console by them, find things nobody owns, and split the bill by project.

The hard part is not the tagging itself. It is getting the same keys, spelled the same way, onto everything, including the resources someone makes by hand on a Friday afternoon. In this tutorial you will:

  • write down a scheme of four keys: Project, Env, Owner and CostCentre
  • apply it to every resource in a Terraform project with the AWS provider's default_tags, and reject bad values before anything is created
  • find resources that are missing tags with a short script built on the Resource Groups Tagging API, and fix them
  • prepare a tag policy that makes AWS Organizations hold accounts to the scheme
  • activate the keys as cost allocation tags so Cost Explorer can group spend by them
  • see how Google Cloud labels and Azure tags carry the same scheme

The demo lives in ~/tagging-demo. It creates a VPC, a security group and three empty S3 buckets. AWS does not charge for VPCs or security groups, and S3 charges for stored data and requests, so empty buckets cost nothing while they stay empty. The last step deletes everything.

Step 1 · Install Terraform, the AWS CLI and jq

Install curl, unzip and jq, then download Terraform 1.17.2 for your machine's architecture, check it against HashiCorp's published checksums and put it on your PATH:

Bash
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
TF_VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version

Install version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:

Bash
AWS_CLI_VERSION=2.42.4
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --version

If the AWS CLI is already installed, the installer stops and says so; run sudo ./aws/install --update instead. Neither tool gets updates from apt. To upgrade later, run the same commands with a newer version number.

The AWS provider is a large download, a few hundred megabytes unpacked. If you pay for data by the bundle, as many people on prepaid mobile data do, set a plugin cache so every Terraform project on the machine shares one copy:

Bash
mkdir -p ~/.terraform.d/plugin-cache
echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Check it worked

sha256sum prints terraform_1.17.2_linux_amd64.zip: OK (or arm64). terraform version prints Terraform v1.17.2 on its first line, aws --version starts with aws-cli/2.42.4, and jq --version prints a version number.

Step 2 · Write the scheme down

A tagging scheme only works if everyone uses the same keys with the same spelling. AWS treats tag keys and values as case sensitive, so Env=prod, env=prod and Env=Prod are three different tags, and Cost Explorer would show them as three rows. Decide once, write it down, and keep the file with your infrastructure code.

Four keys are enough for a small team:

  • Project: which product or client the resource serves. This is the key you will split the bill by.
  • Env: dev, staging or prod. It tells you what is safe to switch off.
  • Owner: a team address, not a person. People change jobs; platform@example.com still works next year.
  • CostCentre: the code your finance team uses, such as CC-104. It lets them charge costs to the right budget without asking you.

Make the project folder and record the scheme in it:

Bash
mkdir -p ~/tagging-demo
cd ~/tagging-demo
cat > TAGGING.md <<'MD'
# Tagging scheme

Every resource carries these four tags. Keys are case sensitive: copy them exactly.

| Key        | Allowed values                       | Example              |
| ---------- | ------------------------------------ | -------------------- |
| Project    | lowercase, letters, digits, hyphens  | storefront           |
| Env        | dev, staging, prod                   | dev                  |
| Owner      | a team email address, never a person | platform@example.com |
| CostCentre | CC- followed by three digits         | CC-104               |

Optional: Name, for a readable label in the console.
Never put secrets or personal data in a tag; tags are visible to anyone who can list resources and appear in billing reports.
MD
cat TAGGING.md

The Example values are placeholders. Replace storefront, platform@example.com and CC-104 with your own project, team address and cost centre wherever they appear in this tutorial.

Check it worked

cat TAGGING.md prints the table with four rows: Project, Env, Owner and CostCentre.

Step 3 · Apply the tags everywhere with default_tags

You could add a tags = { ... } map to every resource by hand, and someone would forget one. The AWS provider has a better place for this: a default_tags block in the provider. Every resource the provider creates that supports tags gets those tags, and a resource can still add its own or override one by using the same key.

Point the AWS CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder); /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles covers setting one up.

Save the Region and a random suffix in a small file, so later commands can read them back. Bucket names are global across all AWS accounts, and the suffix keeps yours unique:

Bash
cd ~/tagging-demo
SUFFIX=$(head -c 4 /dev/urandom | od -An -tx1 | tr -d ' \n')
cat > demo.env <<EOF
export AWS_REGION=eu-west-2
export SUFFIX=${SUFFIX}
EOF
. ./demo.env

The examples use eu-west-2 (London). Any Region works if you use it everywhere. If you are in Africa and your account has the Cape Town Region (af-south-1) turned on, it is closer to you; it is an opt-in Region, so it must be enabled in the account first.

Then confirm who you are:

Bash
aws sts get-caller-identity

The output shows the account ID and the identity you are signed in as. Check it is the sandbox account before you go on.

Now write the Terraform files. variables.tf declares one variable per tag, each with a validation block, so a typo such as Env=Production stops the plan instead of reaching AWS. providers.tf turns the variables into default tags:

Bash
cd ~/tagging-demo

cat > versions.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.74"
    }
  }
}
HCL

cat > variables.tf <<'HCL'
variable "aws_region" {
  type    = string
  default = "eu-west-2"
}

variable "project" {
  type        = string
  description = "Project tag: lowercase letters, digits and hyphens."
  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{1,30}$", var.project))
    error_message = "project must be lowercase letters, digits and hyphens, starting with a letter."
  }
}

variable "env" {
  type        = string
  description = "Env tag: dev, staging or prod."
  validation {
    condition     = contains(["dev", "staging", "prod"], var.env)
    error_message = "env must be one of dev, staging or prod."
  }
}

variable "owner" {
  type        = string
  description = "Owner tag: a team email address."
  validation {
    condition     = can(regex("^[a-z0-9._-]+@[a-z0-9.-]+$", var.owner))
    error_message = "owner must be a lowercase team email address."
  }
}

variable "cost_centre" {
  type        = string
  description = "CostCentre tag: CC- followed by three digits."
  validation {
    condition     = can(regex("^CC-[0-9]{3}$", var.cost_centre))
    error_message = "cost_centre must look like CC-104."
  }
}
HCL

cat > providers.tf <<'HCL'
provider "aws" {
  region = var.aws_region

  default_tags {
    tags = {
      Project    = var.project
      Env        = var.env
      Owner      = var.owner
      CostCentre = var.cost_centre
    }
  }
}
HCL

cat > terraform.tfvars <<'EOF'
project     = "storefront"
env         = "dev"
owner       = "platform@example.com"
cost_centre = "CC-104"
EOF

The tag keys live in one place, providers.tf, and the values in terraform.tfvars. A second environment needs only a second values file, such as prod.tfvars with env = "prod".

Initialise the project and try a bad value on purpose:

Bash
terraform init
Bash
terraform plan -var 'env=Production'

Check it worked

terraform init ends with Terraform has been successfully initialized!. The plan with env=Production fails with Invalid value for variable and your message, env must be one of dev, staging or prod., and nothing is created.

Step 4 · Create resources and read their tags back

Add the resources: a VPC, a security group in it, and two buckets. None of them mentions Project, Env or CostCentre. The logs bucket shows the two things a resource can still do: add a tag of its own (Name) and override a default (Owner, because the data team looks after logs):

Bash
cd ~/tagging-demo
cat > main.tf <<'HCL'
resource "aws_vpc" "main" {
  cidr_block = "10.42.0.0/16"

  tags = {
    Name = "${var.project}-${var.env}"
  }
}

resource "aws_security_group" "web" {
  name        = "${var.project}-${var.env}-web"
  description = "Web tier for ${var.project}"
  vpc_id      = aws_vpc.main.id

  tags = {
    Name = "${var.project}-${var.env}-web"
  }
}

resource "aws_s3_bucket" "assets" {
  bucket_prefix = "${var.project}-${var.env}-assets-"
}

resource "aws_s3_bucket" "logs" {
  bucket_prefix = "${var.project}-${var.env}-logs-"

  tags = {
    Name  = "${var.project}-${var.env}-logs"
    Owner = "data@example.com"
  }
}

output "logs_bucket_tags" {
  value = aws_s3_bucket.logs.tags_all
}
HCL
terraform fmt
terraform plan -out=tfplan
terraform apply tfplan

In the plan, each resource shows two maps. tags is what you wrote on the resource. tags_all is what AWS will get: the defaults merged with the resource's own tags, with the resource winning where the keys match.

Read the merged tags back from Terraform, then ask AWS directly. The Resource Groups Tagging API answers one question across services: which resources in this Region carry a given tag?

Bash
terraform output logs_bucket_tags

. ./demo.env
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=storefront \
  --query 'ResourceTagMappingList[].ResourceARN' --output text

Now change one default and see how far it reaches. Plan with a different cost centre, but do not apply:

Bash
terraform plan -var 'cost_centre=CC-210'

Check it worked

The apply ends with Apply complete! Resources: 4 added, 0 changed, 0 destroyed. The output shows Owner = "data@example.com" next to Project = "storefront", Env = "dev", CostCentre = "CC-104" and Name. get-resources prints four ARNs: the VPC, the security group and both buckets. The last plan says Plan: 0 to add, 4 to change, 0 to destroy., because a change to a default tag is a change to every resource.

Step 5 · Find resources that are missing tags

default_tags covers what Terraform makes. Accounts also collect resources made in the console, by scripts and by other tools. Make two of those by hand: a scratch bucket someone tagged with only the project, and one nobody tagged at all:

Bash
cd ~/tagging-demo
. ./demo.env
aws s3api create-bucket --bucket "tagdemo-scratch-${SUFFIX}" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"
aws s3api put-bucket-tagging --bucket "tagdemo-scratch-${SUFFIX}" \
  --tagging 'TagSet=[{Key=Project,Value=storefront}]'
aws s3api create-bucket --bucket "tagdemo-orphan-${SUFFIX}" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"

The tagging API has a blind spot you need to know about: get-resources returns resources that are tagged, or were tagged once. A resource that has never had a tag does not appear at all. So the audit script below asks two questions. First, which tagged resources lack one of the four keys? Second, as a check for the blind spot, which S3 buckets in the Region are absent from the tagging API's answer?

Bash
cd ~/tagging-demo
cat > audit-tags.sh <<'SH'
#!/usr/bin/env bash
# Lists resources in one Region that are missing a required tag.
set -euo pipefail
region="${AWS_REGION:?set AWS_REGION first}"
required='["Project","Env","Owner","CostCentre"]'

tagged=$(aws resourcegroupstaggingapi get-resources --region "$region" --output json)

echo "Tagged resources missing a required key:"
echo "$tagged" | jq -r --argjson req "$required" '
  .ResourceTagMappingList[]
  | {arn: .ResourceARN, missing: ($req - [.Tags[].Key])}
  | select(.missing | length > 0)
  | "  \(.arn)  missing: \(.missing | join(", "))"'

echo "S3 buckets in $region with no tags at all:"
aws s3api list-buckets --bucket-region "$region" --query 'Buckets[].Name' --output json \
  | jq -r '.[]' | while read -r bucket; do
      arn="arn:aws:s3:::${bucket}"
      if ! echo "$tagged" | jq -e --arg arn "$arn" 'any(.ResourceTagMappingList[]; .ResourceARN == $arn)' > /dev/null; then
        echo "  ${arn}"
      fi
    done
SH
chmod +x audit-tags.sh
./audit-tags.sh

The AWS CLI follows the API's pages for you, so the script sees every tagged resource however many there are. The $req - [...] part is jq's array subtraction: the required keys minus the keys the resource has leaves exactly the missing ones.

Fix what it found. The scratch bucket is in use, so give it the missing tags. tag-resources adds tags to any supported resource by ARN and keeps the tags already there:

Bash
aws resourcegroupstaggingapi tag-resources \
  --resource-arn-list "arn:aws:s3:::tagdemo-scratch-${SUFFIX}" \
  --tags Project=storefront,Env=dev,Owner=platform@example.com,CostCentre=CC-104

The next command deletes the orphan bucket. In your own account, check first that an untagged bucket is empty and that nobody claims it; ask in your team channel before you delete anything you did not make. Here you made it a minute ago:

Bash
aws s3api delete-bucket --bucket "tagdemo-orphan-${SUFFIX}"
./audit-tags.sh

The S3 check only covers buckets. For a full inventory of every resource type, including never-tagged ones, turn on the AWS Config managed rule required-tags with your four keys: it marks each resource it records as compliant or not.

Check it worked

The first run prints the scratch bucket under the first heading with missing: Env, Owner, CostCentre, and the orphan bucket under the second. tag-resources returns "FailedResourcesMap": {}. The second run prints both headings and nothing under either.

Step 6 · Hold every account to the scheme with a tag policy

If your company runs several AWS accounts under AWS Organizations, a tag policy states the scheme once for all of them. It fixes the capitalisation of each key, can list the allowed values, and, for the resource types you name under enforced_for, rejects a tagging request with a value that breaks the rules.

Know its limit before you rely on it: a tag policy checks the tags a resource has. It does not stop anyone creating a resource with no tags. Keep default_tags and the audit script; the policy catches the typos.

Write the policy file:

Bash
cd ~/tagging-demo
cat > tag-policy.json <<'JSON'
{
  "tags": {
    "project": {
      "tag_key": { "@@assign": "Project" }
    },
    "env": {
      "tag_key": { "@@assign": "Env" },
      "tag_value": { "@@assign": ["dev", "staging", "prod"] },
      "enforced_for": { "@@assign": ["s3:bucket"] }
    },
    "owner": {
      "tag_key": { "@@assign": "Owner" }
    },
    "costcentre": {
      "tag_key": { "@@assign": "CostCentre" },
      "tag_value": { "@@assign": ["CC-104", "CC-210"] }
    }
  }
}
JSON
jq '.tags | keys' tag-policy.json

The lowercase names on the left (project, env) only identify each rule; tag_key sets the capitalisation AWS should see. Only s3:bucket is enforced here. Add other types from the AWS list of resource types that support enforcement once you have checked the audit is clean for them, or you will block teams mid-deploy.

Creating and attaching the policy needs the organisation's management account, or an account it has delegated policy management to. Turn on tag policies for the organisation, create the policy, and attach it to one sandbox account or organisational unit first (replace <account-or-ou-id>):

Bash
ROOT_ID=$(aws organizations list-roots --query 'Roots[0].Id' --output text)
aws organizations enable-policy-type --root-id "$ROOT_ID" --policy-type TAG_POLICY
POLICY_ID=$(aws organizations create-policy --name tagging-scheme --type TAG_POLICY \
  --description "Project, Env, Owner and CostCentre" \
  --content file://tag-policy.json --query 'Policy.PolicySummary.Id' --output text)
aws organizations attach-policy --policy-id "$POLICY_ID" --target-id <account-or-ou-id>

Then, signed in to the member account, list the resources that do not comply:

Bash
aws resourcegroupstaggingapi get-resources \
  --include-compliance-details --exclude-compliant-resources \
  --query 'ResourceTagMappingList[].[ResourceARN, ComplianceDetails.NoncompliantKeys]'

Check it worked

jq prints the four rule names: "costcentre", "env", "owner" and "project". In an organisation, aws organizations describe-effective-policy --policy-type TAG_POLICY --target-id <account-id> run from the management account shows the policy in force for that account, and a put-bucket-tagging with Env=Prod on a bucket in that account fails with an error naming the tag policy.

Step 7 · Turn on cost allocation tags and split the bill

Tags on resources do not reach the bill by themselves. Each key has to be activated as a cost allocation tag in the Billing console, by the management account if you use Organizations, or by the account itself if it stands alone. Three facts shape when you do this:

  • A key only shows up for activation after it is on at least one resource. Apply your Terraform first.
  • Activation can take up to 24 hours to take effect.
  • Costs are tagged from activation onwards. AWS offers a backfill of earlier months from the same cost allocation tags page if you need history.

Do it today, before you need the report. Activate all four keys:

Bash
aws ce update-cost-allocation-tags-status --cost-allocation-tags-status \
  TagKey=Project,Status=Active TagKey=Env,Status=Active \
  TagKey=Owner,Status=Active TagKey=CostCentre,Status=Active
aws ce list-cost-allocation-tags --type UserDefined --status Active

A day or so later, group a month's costs by project. Replace the dates with the month you want; End is the first day after it:

Bash
aws ce get-cost-and-usage \
  --time-period Start=2026-11-01,End=2026-12-01 \
  --granularity MONTHLY --metrics UnblendedCost \
  --group-by Type=TAG,Key=Project

Each Cost Explorer API request is charged, at USD 0.01 per request on AWS's pricing page when checked on 26 November 2026, so run reports like this one deliberately rather than in a loop. The same grouping in the Cost Explorer console is free to view.

Check it worked

On the Billing console's Cost allocation tags page, the four keys show as Active, and list-cost-allocation-tags lists them. In the cost report, groups have keys such as Project$storefront. A group with nothing after the $ is spend on resources without a Project tag: that number is your to-do list.

Step 8 · Carry the scheme to Google Cloud and Azure

The idea travels; the rules change. Add the mapping to your scheme file so whoever works in the other cloud does not reinvent it:

Bash
cd ~/tagging-demo
cat >> TAGGING.md <<'MD'

## Other clouds

| AWS tag    | Google Cloud label | Azure tag  |
| ---------- | ------------------ | ---------- |
| Project    | project            | Project    |
| Env        | env                | Env        |
| Owner      | owner (team-name)  | Owner      |
| CostCentre | cost_centre        | CostCentre |

Google Cloud label keys and values are lowercase letters, digits, underscores and dashes,
so an email address cannot be a value: use platform-team, and cc-104 for the cost centre.
Azure tag names are not case sensitive, values are. Resources do not inherit resource group tags.
MD
tail -n 14 TAGGING.md

On Google Cloud, labels do the job of tags for cost reports. The google Terraform provider has a default_labels argument that works like default_tags:

HCL
provider "google" {
  project = "your-project-id" # replace this
  region  = "europe-west2"

  default_labels = {
    project     = "storefront"
    env         = "dev"
    owner       = "platform-team"
    cost_centre = "cc-104"
  }
}

On Azure, the azurerm provider has no provider-level default tags, so keep the map in a local and pass it on each resource. Azure Policy has built-in definitions that copy a tag from the resource group to resources that lack it, which covers what people make in the portal:

HCL
locals {
  tags = {
    Project    = "storefront"
    Env        = "dev"
    Owner      = "platform@example.com"
    CostCentre = "CC-104"
  }
}

resource "azurerm_resource_group" "storefront" {
  name     = "storefront-dev"
  location = "southafricanorth"
  tags     = local.tags
}

Check it worked

tail prints the mapping table with four rows and the two notes. The Google Cloud row for Owner shows owner (team-name), a reminder that the value changes form.

Step 9 · Clean up

The next commands delete the VPC, the security group and all buckets from this demo. Run them only in the sandbox account. Delete the scratch bucket you made by hand, then plan the destroy and read it before you apply it:

Bash
cd ~/tagging-demo
. ./demo.env
aws s3api delete-bucket --bucket "tagdemo-scratch-${SUFFIX}"
terraform plan -destroy -out=tfplan
terraform apply tfplan

Then delete the demo folder, which holds the state, demo.env and your scheme file. Copy TAGGING.md, audit-tags.sh and tag-policy.json into your real infrastructure repository first if you want to keep them:

Bash
cd ~
rm -rf ~/tagging-demo

If you installed the tools only for this tutorial, remove Terraform, the plugin cache and the AWS CLI, and delete the TF_PLUGIN_CACHE_DIR line from ~/.bashrc:

Bash
sudo rm -f /usr/local/bin/terraform
rm -rf ~/.terraform.d/plugin-cache
sudo rm -rf /usr/local/aws-cli /usr/local/bin/aws /usr/local/bin/aws_completer

Check it worked

The destroy ends with Destroy complete! Resources: 4 destroyed. Before you remove the CLI, aws s3api list-buckets --query 'Buckets[].Name' lists no storefront-dev- or tagdemo- bucket. ls ~/tagging-demo reports No such file or directory.

Next steps

  • Use your new tags to track down what is costing money in /tutorials/find-and-stop-what-is-costing-you-on-aws.
  • Put a monthly budget and alerts on the account in /tutorials/set-an-aws-budget-and-cost-alerts.
  • Bring hand-made resources like the scratch bucket under Terraform, so default_tags covers them too, in /tutorials/import-existing-cloud-resources-into-terraform.
  • See default_tags in a full project layout in /tutorials/lay-out-the-relay-opentofu-project.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.