id: gcloud-gke-cost-allocation-disabled

info:
  name: GKE Clusters Without Cost Allocation Enabled
  author: princechaddha
  severity: medium
  description: |
    Ensure that cost allocation is enabled for your Google Kubernetes Engine (GKE) clusters to gain detailed insights into resource usage. This feature allows you to break down resource consumption by Kubernetes namespaces and labels, making it easier to associate costs with specific entities and access detailed cost reports through billing data exported to BigQuery.
  impact: |
    Without cost allocation enabled, you lack detailed visibility into resource consumption and cost distribution across Kubernetes components, making it difficult to make informed decisions for cost optimization, budgeting, and chargeback allocation.
  remediation: |
    Enable cost allocation for your GKE clusters using:
    gcloud container clusters update CLUSTER_NAME --region=REGION --enable-cost-allocation
  reference:
    - https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-usage-metering
    - https://www.trendmicro.com/cloudoneconformity/knowledge-base/gcp/GKE/enable-cost-allocation.html
  tags: cloud,devops,gcp,gcloud,gke,kubernetes,cost,monitoring,gcp-cloud-config

flow: |
  code(1)
  for(let projectId of iterate(template.projectIds)){
    set("projectId", projectId)
    code(2)
    for(let cluster of iterate(template.clusters)){
      cluster = JSON.parse(cluster)
      set("clusterName", cluster.name)
      set("location", cluster.location)
      code(3)
    }
  }

self-contained: true

code:
  - engine:
      - sh
      - bash
    source: |
      gcloud projects list --format="json(projectId)"

    extractors:
      - type: json
        name: projectIds
        internal: true
        json:
          - '.[].projectId'

  - engine:
      - sh
      - bash
    source: |
      gcloud container clusters list --project $projectId --format="json(name,location)"

    extractors:
      - type: json
        name: clusters
        internal: true
        json:
          - '.[]'

  - engine:
      - sh
      - bash
    source: |
      gcloud container clusters describe $clusterName --location $location --project $projectId --format="json(costManagementConfig.enabled)"

    matchers:
      - type: word
        words:
          - "null"

    extractors:
      - type: dsl
        dsl:
          - '"GKE cluster " + clusterName + " in " + location + " of project " + projectId + " does not have cost allocation enabled"'
# digest: 4b0a00483046022100a335e96ed39d59f29bf4c52683a4c46f13abcf1306f72e9f3081377983e32e9e022100930b95594fc5920f5f39e0c5de255f78c0c0b5e7021e32e18a4f7385845a1975:922c64590222798bb761d5b6d8e72950