Create and run jobs as a non-root user

This document describes how to create and run a Batch job as a non-root user.

By default, Batch executes runnables as the root user. If you want Batch to execute runnables as a non-root user—for example, to run an application that doesn't allow root users or to meet security requirements—create a Batch job that uses OS Login. When you enable OS Login in a Batch job, OS Login configures a user account for you on the VMs that your job runs on. All runnables in the job are then executed by your user account on the VM instead of by the root user.

Before you begin

  1. If you haven't used Batch before, review Get started with Batch and enable Batch by completing the prerequisites for projects and users.
  2. If you haven't done so already, enable the OS Login API by running the following command:

    gcloud services enable oslogin.googleapis.com
    
  3. To get the permissions that you need to create and run a job as a non-root user, ask your administrator to grant you the following IAM roles:

    For more information about granting roles, see Manage access to projects, folders, and organizations.

    You might also be able to get the required permissions through custom roles or other predefined roles.

Create a job that runs as a non-root user

Create a Batch job that runs executables through your own user account by doing the following:

Use the Google Cloud CLI or REST API to create a job that includes the runAsNonRoot field set to true in the main body of the JSON file:

"runAsNonRoot": true

For example, a job that runs executables as a non-root user would have a JSON configuration file similar to the following:

{
    "taskGroups": [
      {
        "taskSpec": {
          "runnables": [
            {
              "script": {
                "text": "echo Hello World! This is task $BATCH_TASK_INDEX executed by $(whoami)."
              }
            }
          ]
        },
        "taskCount": 3,
        "runAsNonRoot": true
      }
    ],
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

What's next