Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install gke-workload-security@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin gke-workload-security v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install gke-workload-security

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/gke-workload-security/

Extract the ZIP to .github/skills/ in your repo. The folder name must match gke-workload-security for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 8.1 KB
---
name: gke-workload-security
description: >-
  Audits, configures, and hardens workload-level security controls for Google
  Kubernetes Engine (GKE) applications and namespaces. Covers running security
  audits (`audit_cluster.sh`), enforcing Network Policies (default-deny and Dataplane
  V2 logging), isolating high-risk pods inside GKE Sandbox (`gVisor`), enforcing Pod
  Security Standards (`restricted` labeling) and pod securityContext, and mounting Secret Manager secrets via
  CSI (`SecretProviderClass`). Use when auditing workload security posture, isolating
  namespaces, applying pod security standards, or
  configuring network policies and secret volume mounts. Don't use for Workload Identity (use gke-workload-identity), cluster-wide
  control plane security, RBAC hardening, Binary Authorization, Shielded Nodes,
  or enabling platform-level GKE add-ons (use gke-platform-security instead).
metadata:
  version: "1.0.3"
  category: Security
---

# GKE Workload Security

> **Routing Note:** For Workload Identity IAM and KSA/GSA bindings, use the `gke-workload-identity` skill. For cluster-level security flags (`--database-encryption-key`, `--security-posture`, RBAC, Shielded Nodes, Binary Authorization), use the `gke-platform-security` skill.

This skill provides workflows and best practices for securing GKE workloads. It
covers security auditing, Identity and Access Management (Workload Identity),
Network Security (Network Policies), and Node Security.

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gke-workload-security)"`
and append `agent-skills/1.0 (skill:gke-workload-security)` to `User-Agent` headers.

## Workflows

### 1. Security Audit

Assess the current security posture of your cluster using the provided audit
script.

**Prerequisites:**

-   `gcloud` CLI authenticated.
-   `jq` command-line JSON processor installed.

**Capabilities:**

-   Checks for Workload Identity.
-   Verifies Network Policy is enabled.
-   Checks if Shielded Nodes are enabled.
-   Checks if Binary Authorization is enabled.
-   Checks for Private Cluster configuration.

**Command:**

```bash
scripts/audit_cluster.sh <cluster-name> <region> <project-id>
```

### 2. Configure Workload Identity

Workload Identity allows Kubernetes Service Accounts (KSAs) to impersonate
Google Service Accounts (GSAs). Use this method when workloads require a
dedicated GSA to access Google Cloud APIs; for most workloads, direct IAM
principal binding (covered in the `gke-workload-identity` skill) is the
recommended method.

**Steps:**

1.  **Create Namespace and KSA:**

    ```bash
    kubectl create namespace workload-identity-test-ns
    kubectl create serviceaccount <ksa-name> \
        --namespace workload-identity-test-ns
    ```

2.  **Bind KSA to GSA:**

    ```bash
    gcloud iam service-accounts add-iam-policy-binding <gsa-name>@<project-id>.iam.gserviceaccount.com \
        --role roles/iam.workloadIdentityUser \
        --member "serviceAccount:<project-id>.svc.id.goog[workload-identity-test-ns/<ksa-name>]"
    ```

3.  **Annotate KSA:**

    ```bash
    kubectl annotate serviceaccount <ksa-name> \
        --namespace workload-identity-test-ns \
        iam.gke.io/gcp-service-account=<gsa-name>@<project-id>.iam.gserviceaccount.com
    ```

4.  **Verify Example Pod:** Use existing asset
    `assets/workload-identity-pod.yaml` to test the configuration. Update the
    `<ksa-name>` in the file first.

    ```bash
    kubectl apply -f assets/workload-identity-pod.yaml -n workload-identity-test-ns
    ```

### 3. Implement Network Policies

Control traffic flow between Pods using Network Policies. By default, all
traffic is allowed.

**Enable Network Policy Enforcement:**

```bash
gcloud container clusters update <cluster-name> \
    --update-addons=NetworkPolicy=ENABLED \
    --region <region>
```

> [!NOTE] If your cluster uses Dataplane V2 (`--enable-dataplane-v2`), Network
> Policy enforcement is built-in and this step is not required (and may fail).

**Apply Default Deny Policy:** Isolate namespaces by denying all ingress and
egress traffic by default.

**Replace `<target-namespace>` with the namespace you want to isolate.**

```bash
kubectl apply -f assets/default-deny-netpol.yaml -n <target-namespace>
```

### 4. GKE Sandbox (gVisor) Pod Isolation

Run untrusted workloads in a sandbox for extra kernel isolation. *(Note:
Enabling Shielded Nodes (`--enable-shielded-nodes`) and GKE Sandbox
(`--enable-gke-sandbox`) at the cluster control plane level are platform-level
actions covered in the `gke-platform-security` skill.)*

**Run a Sandboxed Pod:** Add `runtimeClassName: gvisor` to your Pod spec:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: sandboxed-pod
spec:
  runtimeClassName: gvisor
  containers:
  - name: app
    image: nginx
```

### 5. Pod Security Standards

Enforce security policies on namespaces using labels.

**Enforce Restricted Profile:**

```bash
kubectl label --overwrite ns <namespace> \
    pod-security.kubernetes.io/enforce=restricted \
    pod-security.kubernetes.io/enforce-version=latest
```

> [!NOTE] Using `latest` ensures you use the policies corresponding to the
> cluster's current version. You can pin it to a specific version (e.g.,
> `v1.30`) to lock down the namespace to policies of a specific release.

### 6. Secret Manager Integration (CSI Driver)

Mount secrets from Google Cloud Secret Manager directly as volumes in your pods.

**Prerequisites**: Secret Manager CSI driver must be enabled on the cluster.

**Example SecretProviderClass:**

```yaml
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: my-secret-provider
spec:
  provider: gcp
  parameters:
    secrets: |
      - resourceName: "projects/<project-id>/secrets/my-secret/versions/latest"
        fileName: "my-secret-file"
```

**Example Pod Spec excerpt:**

```yaml
spec:
  containers:
    - name: my-app
      volumeMounts:
        - name: secrets-store-inline
          mountPath: "/mnt/secrets"
          readOnly: true
  volumes:
    - name: secrets-store-inline
      csi:
        driver: secrets-store.csi.k8s.io
        readOnly: true
        volumeAttributes:
          secretProviderClass: "my-secret-provider"
```

### 7. Enable Network Policy Logging

If using GKE Dataplane V2, you can log allowed and denied connections.

**Steps:**

1.  Configure the `NetworkLogging` custom resource.

**Example NetworkLogging Manifest:**

```yaml
apiVersion: networking.gke.io/v1alpha1
kind: NetworkLogging
metadata:
  name: default
spec:
  cluster:
    allow:
      log: true
      delegate: true
    deny:
      log: true
      delegate: true
```

This will log connection details to Cloud Logging.

## Best Practices

1.  **Least Privilege:** Always use Workload Identity with minimal IAM roles.
    Avoid using Node default service accounts.
2.  **Network Isolation:** Use Network Policies to restrict Pod-to-Pod
    communication. Enable Network Policy Logging for visibility.
3.  **Image Security:** Use Binary Authorization to ensure only trusted images
    are deployed.
4.  **Secret Management**: Use Secret Manager CSI driver instead of default
    Kubernetes secrets for sensitive data.
5.  **Pod Security**: Enforce `baseline` or `restricted` Pod Security Standards
    on all non-system namespaces.
6.  **Policy Enforcement**: Consider using **Policy Controller** (Gatekeeper) to
    enforce custom security and compliance policies across the cluster.

## Resources

-   [Workload Identity Federation for GKE](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity)
-   [GKE Network Policies](https://cloud.google.com/kubernetes-engine/docs/how-to/network-policy)
-   [Pod Security Standards in GKE](https://cloud.google.com/kubernetes-engine/docs/how-to/podsecurityadmission)
-   [Google Secret Manager CSI Driver](https://cloud.google.com/secret-manager/docs/secret-manager-managed-csi-component)
-   [GKE Dataplane V2 Network Logging](https://cloud.google.com/kubernetes-engine/docs/how-to/network-policy-logging)
assets/
default-deny-netpol.yaml 0.2 KB
---
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  # checkov:skip=CKV_K8S_39:Default deny all intentionally matches all pods
  name: default-deny-all

spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
workload-identity-pod.yaml 1.2 KB
---
apiVersion: v1
kind: Pod
metadata:
  name: workload-identity-test
  namespace: workload-identity-test-ns
spec:
  serviceAccountName: <ksa-name> # Replace with your KSA name
  automountServiceAccountToken: false
  containers:
    - image: gcr.io/google.com/cloudsdktool/cloud-sdk@sha256:0d19f566f418b8aa0109eba1d04db88e36e88d09559267b4559982d07c685a0b
      name: workload-identity-test
      command:
        - "sleep"
        - "infinity"
      livenessProbe:
        exec:
          command:
            - true
        initialDelaySeconds: 5
        periodSeconds: 5
      readinessProbe:
        exec:
          command:
            - true
        initialDelaySeconds: 5
        periodSeconds: 5

      imagePullPolicy: Always
      resources:
        requests:
          cpu: 100m
          memory: 128Mi
        limits:
          cpu: 100m
          memory: 128Mi
      securityContext:
        allowPrivilegeEscalation: false
        capabilities:
          drop:
            - ALL
        readOnlyRootFilesystem: true

  nodeSelector:
    iam.gke.io/gke-metadata-server-enabled: "true"
  securityContext:
    runAsNonRoot: true
    runAsUser: 65532
    seccompProfile:
      type: RuntimeDefault
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gke-workload-security)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:gke-workload-security)` in the `User-Agent`
    header. If a `User-Agent` header is already specified, append this string to
    the end of it rather than overwriting existing `User-Agent` data — the
    collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
    tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:gke-workload-security)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
scripts/
audit_cluster.sh 2.2 KB
#!/bin/bash
set -e
set -o pipefail

CLUSTER_NAME="${1}"
REGION="${2}"
PROJECT_ID="${3}"

if [[ -z "${CLUSTER_NAME}" ]] || [[ -z "${REGION}" ]] || [[ -z "${PROJECT_ID}" ]]; then
    echo "Usage: ${0} <cluster-name> <region> <project-id>"
    exit 1
fi

echo "Auditing Cluster: ${CLUSTER_NAME} in ${REGION} (Project: ${PROJECT_ID})"
echo "---------------------------------------------------"

# Get Cluster Details
CLUSTER_JSON=$(gcloud container clusters describe "${CLUSTER_NAME}" --region "${REGION}" --project "${PROJECT_ID}" --format=json)

# Extract all configurations in one pass for performance
# Output format: TSV (Tab Separated Values)
VALUES=$(echo "${CLUSTER_JSON}" | jq -r '
  [
    (.workloadIdentityConfig.workloadPool // "DISABLED"),
    (.networkPolicy.enabled // "FALSE" | tostring),
    (.networkConfig.datapathProvider // "LEGACY"),
    (.shieldedNodes.enabled // "FALSE" | tostring),
    (.binaryAuthorization.evaluationMode // "DISABLED"),
    (.privateClusterConfig.enablePrivateNodes // "FALSE" | tostring)
  ] | @tsv
')

read -r WI_CONFIG NETPOL_ENABLED DATAPATH_PROVIDER SHIELDED_NODES BINAUTH_CONFIG PRIVATE_NODES <<< "${VALUES}"

# Check Workload Identity
if [[ "${WI_CONFIG}" != "DISABLED" ]]; then
    echo "[PASS] Workload Identity is ENABLED (${WI_CONFIG})"
else
    echo "[FAIL] Workload Identity is DISABLED"
fi

# Check Network Policy (Explicit or DPv2)
if [[ "${NETPOL_ENABLED}" == "true" ]] || [[ "${DATAPATH_PROVIDER}" == "ADVANCED_DATAPATH" ]]; then
    echo "[PASS] Network Policy is ENABLED (Provider: ${DATAPATH_PROVIDER})"
else
    echo "[FAIL] Network Policy is DISABLED"
fi

# Check Shielded Nodes
if [[ "${SHIELDED_NODES}" == "true" ]]; then
    echo "[PASS] Shielded Nodes are ENABLED"
else
    echo "[FAIL] Shielded Nodes are DISABLED"
fi

# Check Binary Authorization
if [[ "${BINAUTH_CONFIG}" != "DISABLED" ]]; then
    echo "[PASS] Binary Authorization is ENABLED (${BINAUTH_CONFIG})"
else
    echo "[WARN] Binary Authorization is DISABLED"
fi

# Check Private Cluster
if [[ "${PRIVATE_NODES}" == "true" ]]; then
    echo "[PASS] Private Cluster (Nodes) is ENABLED"
else
    echo "[WARN] Private Cluster (Nodes) is DISABLED"
fi

echo "---------------------------------------------------"
echo "Audit Complete."

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE