id: gcloud-mig-no-load-balancer

info:
  name: Managed Instance Group Not Using Load Balancer
  author: princechaddha
  severity: low
  description: |
    Ensure that each Managed Instance Group is using a load balancer to act as an instance group frontend. Google Cloud Managed Instance Groups (MIGs) are groups of virtual machine (VM) instances that you control as a single entity. MIGs support rich features such as autoscaling and autohealing, load balancing, multiple zone coverage, and stateful workloads.
  impact: |
    Without a load balancer, traffic is not evenly distributed among instances, potentially leading to poor performance, reduced availability, and inefficient resource utilization.
  remediation: |
    Configure a load balancer for your Managed Instance Group by creating a backend service and associating it with your MIG. This ensures even traffic distribution and improved availability.
  reference:
    - https://www.trendmicro.com/cloudoneconformity/knowledge-base/gcp/ComputeEngine/mig-load-balancer-check.html
    - https://cloud.google.com/compute/docs/instance-groups/adding-an-instance-group-to-a-load-balancer
  tags: cloud,devops,gcp,gcloud,compute,reliability,mig,load-balancer,gcp-cloud-config

flow: |
  code(1)
  for(let projectId of iterate(template.projectIds)){
    set("projectId", projectId)
    code(2)
    for(let instanceGroup of iterate(template.instanceGroups)){
      set("instanceGroupName", instanceGroup.name)
      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 compute instance-groups list --project $projectId --only-managed --format="json(name)"

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

  - engine:
      - sh
      - bash
    source: |
      gcloud compute backend-services list --project $projectId --format="json(backends[].group)" | grep $instanceGroupName

    matchers:
      - type: word
        words:
          - "name"
        negative: true

    extractors:
      - type: dsl
        dsl:
          - '"Managed Instance Group " + instanceGroupName + " in project " + projectId + " is not associated with any load balancer backend service"'
# digest: 4b0a00483046022100fd07fe7b5044882943a82b02e5f3f8ef7e7d3637ae16e1fac9da1348c033104d022100fc93be04033ba0417bace21359c56a7b8eeb498cf7486a6b8c9b7b60cce1d4e7:922c64590222798bb761d5b6d8e72950