Creating a service account for a Kubernetes app

Kubernetes enables access control for workloads by providing service accounts. A service account represents an identity for processes that run in a pod. When a process is authenticated through a service account, it can contact the API server and access cluster resources. If a pod doesn’t have an assigned service account, it gets the default service account.

In MKE, you give a service account access to cluster resources by creating a grant, the same way that you would give access to a user or a team.

In this example, you will create a service account and a grant that could be used for an NGINX server.

Create the Kubernetes namespace

A Kubernetes user account is global, but a service account is scoped to a namespace, so you need to create a namespace before you create a service account.

  1. Navigate to the Namespaces page and click Create.

  2. In the Object YAML editor, append the following text.

    metadata:
      name: nginx
    
  3. Click Create.

  4. In the nginx namespace, click the More options icon, and in the context menu, select Set Context, and click Confirm.

  5. Click the Set context for all namespaces toggle and click Confirm.

Create a service account

Create a service account named nginx-service-account in the nginx namespace.

  1. Navigate to the Service Accounts page and click Create.

  2. In the Namespace dropdown, select nginx.

  3. In the Object YAML editor, paste the following text.

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: nginx-service-account
    
  4. Click Create.

The action first creates a new namespace that contains the automatically created default service account. An additional service account is created soon after, and thus you will see two service accounts in the new namespace.

Create a role binding

To give the service account access to cluster resources, use the MKE web UI to create a role binding with Restricted Control permissions.

  1. From the left-side navigation panel, navigate to Access Control > Grants.

    Note

    If Hide Swarm Navigation is selected on the <username> > Admin Settings > Tuning page, Grants will display as Role Bindings under the Access Control menu item.

  2. In the Grants pane, select the Kubernetes tab and click Create Role Binding.

  3. In the Subject pane, under SELECT SUBJECT TYPE, select Service Account.

  4. In the Namespace dropdown, select nginx.

  5. In the Service Account dropdown, select nginx-service-account and then click Next.

  6. In the Resource Set pane, select the nginx namespace and thenclick Next.

  7. In the Role pane, under ROLE TYPE, select Role and then select Restricted Control.

  8. Click Create.

The NGINX service account can now access all cluster resources in the nginx namespace.