1. Answers
  2. Assign 'edit' ClusterRole to a Service Account in a Namespace

How do I assign the 'edit' cluster role to a service account in a namespace?

This guide explains how to use Pulumi to assign the ’edit’ ClusterRole to a service account within a specific namespace in a Kubernetes cluster. The ClusterRoleBinding resource will be used to link the ’edit’ ClusterRole to the service account.

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Define the namespace where the service account will be created
const namespaceName = "example-namespace";

// Create a namespace
const namespace = new k8s.core.v1.Namespace(namespaceName, {
    metadata: { name: namespaceName },
});

// Create a service account in the namespace
const serviceAccount = new k8s.core.v1.ServiceAccount("example-service-account", {
    metadata: {
        name: "example-service-account",
        namespace: namespaceName,
    },
});

// Bind the 'edit' cluster role to the service account in the namespace
const editRoleBinding = new k8s.rbac.v1.ClusterRoleBinding("edit-role-binding", {
    metadata: {
        name: "edit-role-binding",
    },
    subjects: [{
        kind: "ServiceAccount",
        name: serviceAccount.metadata.name,
        namespace: namespaceName,
    }],
    roleRef: {
        kind: "ClusterRole",
        name: "edit",
        apiGroup: "rbac.authorization.k8s.io",
    },
});

Key Points

  • Namespace Creation: A namespace is created to house the service account.
  • Service Account Creation: A service account is created within the specified namespace.
  • ClusterRoleBinding: The ’edit’ ClusterRole is bound to the service account using a ClusterRoleBinding.

Summary

In this guide, we created a namespace and a service account within that namespace. We then assigned the ’edit’ ClusterRole to the service account using a ClusterRoleBinding. This setup allows the service account to have ’edit’ permissions within the namespace.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up