Review Kubernetes metadata label syntax

Verify both valid label syntax and matching selectors.

Description

Invalid Kubernetes labels can cause the API to reject resource creation or updates. Services, NetworkPolicies and operational tools use labels to select resources, so manage both their syntax and meaning.

A label value may be empty or contain up to 63 characters. A nonempty value must begin and end with an alphanumeric character; alphanumerics, hyphens, underscores and dots are allowed in between.

Potential impact

  • Invalid labels can prevent deployment or resource updates.
  • Even a valid label can fail to select the intended resources when selectors do not match.

Remediation

  • Use label keys and values that satisfy Kubernetes syntax rules. Check the separate rules for a key’s optional DNS prefix and name.
  • When changing labels, review Service and policy selectors and verify the resources actually selected.

Examples

These metadata excerpts omit the required pod spec. Values are case-sensitive, so a selector for MyApp must use the same value.

Before

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "terraform-example"

    labels = {
      app = "g**dy.l+bel"
    }
  }
}

After

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "terraform-example"

    labels = {
      app = "MyApp"
    }
  }
}

Explanation:

  • Before: The value contains asterisks and a plus sign, making it invalid and liable to API rejection.
  • After: MyApp is a valid value. Selectors in other resources must also match it.

References