> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ppio.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a template with the SDK

> Define a template with the SDK builder, build it, and create a sandbox from the result: base image, build steps, packages, caching, tags and size.

The SDK defines a template with a chainable builder, starting from a base image and adding build steps. Building the definition stores it under a template name and returns a build whose template ID creates sandboxes. Use the `PPIO` client as the entry point: start with `ppio.template.new()` in both Python and Node.js.

> [!NOTE]
>
> Install the SDK, or the CLI for `ppio` commands, and set the `PPIO_API_KEY` and `PPIO_DOMAIN` environment variables before running these examples. See [Quickstart](https://docs.ppio.ai/sandbox/quickstart.md) and [Install and authenticate](https://docs.ppio.ai/sandbox/cli/install.md).

## Build a template

**1. Define the template**

Start from a base image and add the steps the build runs.

```python Python theme={null}
template = ppio.template.new().from_image("python:3.12")
```

```javascript Node.js theme={null}
const template = ppio.template.new().fromImage('python:3.12')
```

**2. Build the template**

Pass the definition and a template name. CPU and memory apply to the sandboxes created from the template.

```python Python theme={null}
build = ppio.template.build(
    template,
    "my-python-template",
    cpu_count=2,
    memory_mb=1024,
)
```

```javascript Node.js theme={null}
const build = await ppio.template.build(template, 'my-python-template', {
  cpuCount: 2,
  memoryMB: 1024,
})
```

**3. Create a sandbox from the template**

Pass the template ID from the build. The sandbox starts from the built image.

```python Python theme={null}
sandbox = ppio.sandbox.create(build.template_id)
print(sandbox.sandbox_id)

result = sandbox.commands.run("python --version")
print(result.stdout)

sandbox.kill()
```

```javascript Node.js theme={null}
const sandbox = await ppio.sandbox.create(build.templateId)
console.log(sandbox.sandboxId)

const result = await sandbox.commands.run('python --version')
console.log(result.stdout)

await sandbox.kill()
```

### Full example

The CLI block builds the template from a Dockerfile instead of builder calls.

```python Python theme={null}
# main.py
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_image("python:3.12")

build = ppio.template.build(
    template,
    "my-python-template",
    cpu_count=2,
    memory_mb=1024,
)

sandbox = ppio.sandbox.create(build.template_id)
print(sandbox.sandbox_id)

result = sandbox.commands.run("python --version")
print(result.stdout)

sandbox.kill()
```

```javascript Node.js theme={null}
// index.mts
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromImage('python:3.12')

const build = await ppio.template.build(template, 'my-python-template', {
  cpuCount: 2,
  memoryMB: 1024,
})

const sandbox = await ppio.sandbox.create(build.templateId)
console.log(sandbox.sandboxId)

const result = await sandbox.commands.run('python --version')
console.log(result.stdout)

await sandbox.kill()
```

```bash CLI theme={null}
# Build a template from a Dockerfile (alias: template ct), then create a sandbox and run a command
ppio template create my-python-template --dockerfile ./ppio.Dockerfile
sandbox_id=$(ppio sandbox create my-python-template -d)
ppio sandbox exec "$sandbox_id" "python --version"
ppio sandbox kill -y "$sandbox_id"
```

## Names

Every build needs a template name. Keep names stable for a logical template family. The returned template ID is the immutable build output used at runtime.

## Builder methods

Each method returns the builder, so calls chain. Pass options as keyword arguments in Python and as a trailing options object in Node.js.

| Method | Parameters |
| - | - |
| `from_image` / `fromImage` | `image`, plus an optional registry `username` and `password`. `from_base_image` / `fromBaseImage` selects the default base image. The `from*` family also covers language images and other registries |
| `set_user` / `setUser` | `user`: the user that the following build steps run as |
| `set_workdir` / `setWorkdir` | `workdir`: the directory the following build steps run in |
| `run_cmd` / `runCmd` | `command`: one command, or a list of commands joined with `&&`. `user` (optional, or `options.user` in Node.js): the user to run as |
| `copy` | `src`: a path or a list of paths. `dest`: the destination path in the template. `force_upload` / `forceUpload` (optional): upload even if the files are cached. `user` (optional): the owner of the copied files. `mode` (optional): permissions such as `0o755`. `resolve_symlinks` / `resolveSymlinks` (optional): resolve symlinks while copying |
| `set_envs` / `setEnvs` | A key and value mapping of environment variables |
| `pip_install` / `pipInstall` | Packages as a string or a list. `g` defaults to true and installs globally; `g=False` / `{ g: false }` installs with `--user`. With no packages, it runs `pip install .` |
| `npm_install` / `npmInstall` | Packages as a string or a list. `g` for a global install, `dev` for development dependencies. With no packages, it installs from `package.json` |
| `bun_install` / `bunInstall` | The same options as npm, but uses `bun` |
| `apt_install` / `aptInstall` | Packages are required. `no_install_recommends` / `noInstallRecommends` and `fix_missing` / `fixMissing` add apt flags. It runs `apt-get update` and installs as root |
| `git_clone` / `gitClone` | `url` (required). `path` (optional): the destination of the clone. `branch` (optional): adds `--single-branch`. `depth` (optional): the shallow-clone depth. `user` (optional): the user to run the clone as |
| `skip_cache` / `skipCache` | None. It forces this instruction and every following layer to rebuild |

## Choose a base image

A template definition starts by choosing a base image, or an existing template, with one of the `from*` methods.

```python Python theme={null}
import os

from ppio_sandbox import PPIO

ppio = PPIO()

# The default base image
base = ppio.template.new().from_base_image()

# A specific language image
python = ppio.template.new().from_python_image("3.12")
ubuntu = ppio.template.new().from_ubuntu_image("24.04")

# A custom image, with private registry credentials from the environment
custom = ppio.template.new().from_image(
    "myregistry.com/myimage:latest",
    username=os.environ["REGISTRY_USERNAME"],
    password=os.environ["REGISTRY_PASSWORD"],
)
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()

// The default base image
const base = ppio.template.new().fromBaseImage()

// A specific language image
const python = ppio.template.new().fromPythonImage('3.12')
const ubuntu = ppio.template.new().fromUbuntuImage('24.04')

// A custom image, with private registry credentials from the environment
const custom = ppio.template.new().fromImage('myregistry.com/myimage:latest', {
  username: process.env.REGISTRY_USERNAME,
  password: process.env.REGISTRY_PASSWORD,
})
```

## Build from a private registry

To build from an image hosted in a private or cloud registry, pass credentials when selecting the base image. For a generic registry, use `from_image` / `fromImage` with a user name and password. Dedicated helpers exist for AWS ECR, Google Container Registry, Oracle Cloud (OCI) and Huawei Cloud SWR.

| Registry | Method | Credentials |
| - | - | - |
| Generic, basic auth | `from_image` / `fromImage` | `username`, `password` |
| AWS ECR | `from_aws_registry` / `fromAWSRegistry` | `access_key_id` / `accessKeyId`, `secret_access_key` / `secretAccessKey`, `region` |
| Google GCR and GAR | `from_gcp_registry` / `fromGCPRegistry` | `service_account_json` / `serviceAccountJSON` as a path, a JSON string or an object |
| Oracle OCI | `from_oci_registry` / `fromOCIRegistry` | `tenancy_ocid` / `tenancyOcid`, `user_ocid` / `userOcid`, `fingerprint`, `private_key` / `privateKey`, `region` |
| Huawei Cloud SWR | `from_huawei_cloud_registry` / `fromHuaweiCloudRegistry` | `access_key_id` / `accessKeyId`, `secret_access_key` / `secretAccessKey`, `region` |

```python Python theme={null}
import os

from ppio_sandbox import PPIO

ppio = PPIO()

# Generic private registry, basic auth
template = ppio.template.new().from_image(
    "myregistry.com/team/app:latest",
    username=os.environ["REGISTRY_USERNAME"],
    password=os.environ["REGISTRY_PASSWORD"],
)

# AWS ECR
ppio.template.new().from_aws_registry(
    "123456789.dkr.ecr.us-west-2.amazonaws.com/app:latest",
    access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
    secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"],
    region="us-west-2",
)
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()

// Generic private registry, basic auth
const template = ppio.template.new().fromImage('myregistry.com/team/app:latest', {
  username: process.env.REGISTRY_USERNAME,
  password: process.env.REGISTRY_PASSWORD,
})

// AWS ECR
ppio.template.new().fromAWSRegistry(
  '123456789.dkr.ecr.us-west-2.amazonaws.com/app:latest',
  {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: 'us-west-2',
  },
)
```

> [!WARNING]
>
> Pass registry credentials and Git tokens from environment variables, never in a repository URL.

## Set the user and workdir

After choosing a base image, control which user the following build steps run as and which directory they run in.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = (
    ppio.template.new()
    .from_ubuntu_image("24.04")
    .set_user("root")
    .apt_install(["git"])
    .set_user("user")
    .set_workdir("/home/user/app")
)
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template
  .new()
  .fromUbuntuImage('24.04')
  .setUser('root')
  .aptInstall(['git'])
  .setUser('user')
  .setWorkdir('/home/user/app')
```

## Run a command

`run_cmd` / `runCmd` runs a shell command during the build. It accepts a single command string or a list of commands joined with `&&`, and an optional user to run as.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

template.run_cmd('apt-get update')
template.run_cmd(['pip install numpy', 'pip install pandas'])
template.run_cmd('apt-get install vim', user='root')
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

template.runCmd('apt-get update')
template.runCmd(['pip install numpy', 'pip install pandas'])
template.runCmd('apt-get install vim', { user: 'root' })
```

## Copy files

`copy` includes local files or directories in the image. The source may be a single path or a list of paths, and the destination is a path in the template. Options control ownership, permissions and upload behavior.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

template.copy('requirements.txt', '/home/user/')
template.copy(['app.py', 'config.py'], '/app/', mode=0o755)
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

template.copy('requirements.txt', '/home/user/')
template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 })
```

## Set environment variables

`set_envs` / `setEnvs` sets environment variables from a key and value mapping.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

template.set_envs({'APP_ENV': 'production', 'PORT': '8000'})
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

template.setEnvs({ NODE_ENV: 'production', PORT: '8080' })
```

> [!WARNING]
>
> Environment variables set with `set_envs` / `setEnvs` are available only during the template build, not at sandbox runtime.

## Install packages

Dedicated helpers wrap common package managers. Each accepts a single package name or a list. When packages are omitted, the language helpers install from the working directory with `pip install .` or `package.json`.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

template.pip_install('numpy')
template.pip_install(['pandas', 'scikit-learn'])
template.pip_install('numpy', g=False)
template.pip_install()

template.npm_install('express')
template.npm_install('tsx', g=True)
template.npm_install('typescript', dev=True)

template.bun_install(['lodash', 'axios'])

template.apt_install(['git', 'curl', 'wget'])
template.apt_install(['vim'], no_install_recommends=True)
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

template.pipInstall('numpy')
template.pipInstall(['pandas', 'scikit-learn'])
template.pipInstall('numpy', { g: false })
template.pipInstall()

template.npmInstall('express')
template.npmInstall('tsx', { g: true })
template.npmInstall('typescript', { dev: true })

template.bunInstall(['lodash', 'axios'])

template.aptInstall(['git', 'curl', 'wget'])
template.aptInstall(['vim'], { noInstallRecommends: true })
```

## Clone a repository

`git_clone` / `gitClone` clones a repository into the image. Only the URL is required. A destination path and clone options are optional.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

template.git_clone('https://github.com/user/repo.git', '/app/repo')
template.git_clone(
    'https://github.com/user/repo.git',
    branch='main',
    depth=1,
)
template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root')
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

template.gitClone('https://github.com/user/repo.git', '/app/repo')
template.gitClone('https://github.com/user/repo.git', undefined, {
  branch: 'main',
  depth: 1,
})
template.gitClone('https://github.com/user/repo.git', '/app/repo', { user: 'root' })
```

> [!WARNING]
>
> `git_clone` / `gitClone` has no authentication parameters. For a private repository, set up access in an earlier `run_cmd` / `runCmd` or `set_envs` / `setEnvs` step, with the token taken from an environment variable rather than written into the URL.

## Set CPU and memory

CPU and memory are set when the template is built. Set the size at build time, then create sandboxes from the template.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")
build = ppio.template.build(template, "big-worker", cpu_count=4, memory_mb=8192)

sandbox = ppio.sandbox.create(build.template_id)

sandbox.kill()
```

```javascript Node.js theme={null}
// index.mts
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')
const build = await ppio.template.build(template, 'big-worker', {
  cpuCount: 4,
  memoryMB: 8192,
})

const sandbox = await ppio.sandbox.create(build.templateId)

await sandbox.kill()
```

> [tab] Python
>
> **cpu\_count** `number`
>
> vCPU is a whole number. Must stay within the team's maximums.
>
> **memory\_mb** `number`
>
> Memory is set in fixed increments and scales with the vCPU count, within a fixed range per vCPU. Must stay within the team's maximums.

> [tab] Node.js
>
> **cpuCount** `number`
>
> vCPU is a whole number. Must stay within the team's maximums.
>
> **memoryMB** `number`
>
> Memory is set in fixed increments and scales with the vCPU count, within a fixed range per vCPU. Must stay within the team's maximums.

Current maximums are on [Quotas and limits](https://docs.ppio.ai/sandbox/quotas.md).

## Control build caching

Template builds cache completed layers, so a repeated build does not rerun every instruction, which speeds up iteration. Caching is enabled by default and needs no configuration. Skip the cache only when a fresh build is required: a build without the cache is significantly slower.

The SDK and the CLI offer three levels of control.

| Scope | Effect | How |
| - | - | - |
| Whole build | Ignores the whole cache and rebuilds the template from scratch | `skip_cache=True` in Python, `skipCache: true` in Node.js, as a build option |
| From a layer onward | Rebuilds this instruction and every following layer; placed on a `from*` instruction, it invalidates the whole template cache | `.skip_cache()` in Python, `.skipCache()` in Node.js, on the builder |
| CLI | Ignores the cache during a build | `ppio template build --no-cache` |

> [!WARNING]
>
> The chained `skip_cache()` / `skipCache()` method does not skip a single instruction. It applies to every subsequent layer from the point where it is called, so the earlier the call, the more of the cache is invalidated.

The example skips the cache in the definition and forces a full rebuild. The two approaches can be combined.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = (
    ppio.template.new()
    .from_python_image("3.12")
    .skip_cache()  # no cache for any layer from here on
    .run_cmd("pip install -U pip")
)

build = ppio.template.build(
    template,
    "my-template-no-cache",
    skip_cache=True,  # ignore the cache for the whole template
)
```

```javascript Node.js theme={null}
// index.mts
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template
  .new()
  .fromPythonImage('3.12')
  .skipCache() // no cache for any layer from here on
  .runCmd('pip install -U pip')

const build = await ppio.template.build(template, 'my-template-no-cache', {
  skipCache: true, // ignore the cache for the whole template
})
```

## Tag builds

Tags label builds for release management without changing the underlying template name. Pass tags when the template is built, or assign them later.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

build = ppio.template.build(
    template,
    "agent-runtime-base",
    tags=["v1.0.0", "latest"],
)

ppio.template.assign_tags("agent-runtime-base:v1.0.0", "production")

tags = ppio.template.get_tags(build.template_id)
print(tags)
```

```javascript Node.js theme={null}
// index.mts
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

const build = await ppio.template.build(template, 'agent-runtime-base', {
  tags: ['v1.0.0', 'latest'],
})

await ppio.template.assignTags('agent-runtime-base:v1.0.0', 'production')

const tags = await ppio.template.getTags(build.templateId)
console.log(tags)
```

## Read build logs

Build logs show provisioning progress and help diagnose a failed build.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
template = ppio.template.new().from_python_image("3.12")

build = ppio.template.build(template, "my-logged-template")
print(build.build_id)
```

```javascript Node.js theme={null}
// index.mts
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const template = ppio.template.new().fromPythonImage('3.12')

const build = await ppio.template.build(template, 'my-logged-template')
console.log(build.buildId)
```

> [!NOTE]
>
> Template builds fail for these common reasons: invalid credentials for a private registry, a package install failure inside `run_cmd` / `runCmd`, a start command that exits unexpectedly, a ready command that never succeeds, or CPU and memory settings outside the platform limits. See [Errors](https://docs.ppio.ai/sandbox/errors.md).


## Related topics

- [Build a template with the CLI](https://docs.ppio.ai/sandbox/templates/build-cli.md)
- [Mount an S3 bucket in a sandbox](https://docs.ppio.ai/sandbox/filesystem/mount-s3.md)
- [What is a sandbox template?](https://docs.ppio.ai/sandbox/templates/overview.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.