Edit on GitHub

Tiltfile API Reference

Tiltfiles are written in Starlark, a dialect of Python. For more information on Starlark’s built-ins, see the Starlark Spec. The rest of this page details Tiltfile-specific functionality.

Extensions

Can’t find what you’re looking for in this reference?

Tilt users can contribute extensions to share with other users. Browse them for examples of what you can do with a Tiltfile. Load them into your own Tiltfile. Includes:

  • conftest: Use Conftest to test your configuration files.
  • coreos_prometheus: Deploys Prometheus to a monitoring namespace, managed by the CoreOS Prometheus Operator and CRDs
  • docker_build_sub: Specify extra Dockerfile directives in your Tiltfile beyond docker_build.
  • file_sync_only: No-build, no-push, file sync-only development. Useful when you want to live-reload a single config file into an existing public image, like nginx.
  • git_resource: Deploy a dockerfile from a remote repository – or specify the path to a local checkout for local development.
  • helm_remote: Install a remote Helm chart (in a way that gets properly uninstalled when running tilt down)
  • jest_test_runner: Jest JavaScript test runner. Example from Contribute an Extension.
  • local_output: Run a local command and get the output as string
  • min_tilt_version: Require a minimum Tilt version to run this Tiltfile.
  • min_k8s_version: Require a minimum Kubernetes version to run this Tiltfile.
  • namespace: Functions for interacting with namespaces.
  • pack: Build container images using pack and buildpacks.
  • print_tiltfile_dir: Print all files in the Tiltfile directory. If recursive is set to True, also prints files in all recursive subdirectories.
  • procfile: Create Tilt resources from a foreman Procfile.
  • restart_process: Wrap a docker_build to restart the given entrypoint after a Live Update (replaces restart_container())
  • secret: Functions for creating secrets.
  • snyk: Use Snyk to test your configuration files.

Data


__file__ = ''

The path of the Tiltfile. Set as a local variable in each Tiltfile as it loads.

os. environ = typing.Dict[str, str]

A dictionary of your environment variables.

For example, os.environ['HOME'] is usually your home directory.

Captured each time the Tiltfile begins execution.

Tiltfile dictionaries support many of the same methods as Python dictionaries, including:

  • dict.get(key, default)
  • dict.items()

See the Starlark spec for more.

os. name = ''

The name of the operating system. ‘posix’ (for Linux and MacOS) or ‘nt’ (for Windows).

Designed for consistency with os.name in Python .

config. main_dir = ''

The absolute directory of the main Tiltfile.

Often used to determine the location of vendored code and caches.

config. main_path = ''

The absolute path of the main Tiltfile.

config. tilt_subcommand = ''

The sub-command with which tilt was invoked. Does not include extra args or options.

Examples:

  • run tilt down -> config.tilt_subcommand == “down”
  • run tilt up frontend backend -> config.tilt_subcommand == “up”
  • run tilt alpha tiltfile-result -> config.tilt_subcommand == “alpha tiltfile-result”

Functions


allow_k8s_contexts ( contexts )

Specifies that Tilt is allowed to run against the specified k8s context names.

To help reduce the chances you accidentally use Tilt to deploy to your production cluster, Tilt will only push to clusters that have been whitelisted for local development.

By default, Tilt whitelists Minikube, Docker for Desktop, Microk8s, Red Hat CodeReady Containers, Kind, K3D, and Krucible.

To whitelist your development cluster, add a line in your Tiltfile:

allow_k8s_contexts(‘context-name’)

where ‘context-name’ is the name returned by kubectl config current-context .

For more on which cluster context is right for you, see Choosing a Local Dev Cluster .

Parameters: contexts ( Union [ str , List [ str ]]) – a string or list of strings, specifying one or more k8s context names that Tilt is allowed to run in. This list is in addition to the default of all known-local clusters.

Example

allow_k8s_contexts('my-staging-cluster')

allow_k8s_contexts(['my-staging-cluster', 'gke_some-project-123456_us-central1-b_windmill'])
Return type: None
analytics_settings ( enable )

Overrides Tilt telemetry.

By default, Tilt does not send telemetry. After you successfully run a Tiltfile, the Tilt web UI will nudge you to opt in or opt out of telemetry.

The Tiltfile can override these telemetry settings, for teams that always want telemetry enabled or disabled.

Parameters: enable ( bool ) – if true, telemetry will be turned on. If false, telemetry will be turned off.
Return type: None
blob ( contents )

Creates a Blob object that wraps the provided string. Useful for passing strings in to functions that expect a Blob , e.g. k8s_yaml .

Return type: Blob
custom_build ( ref , command , deps , tag='' , disable_push=False , skips_local_docker=False , live_update=[] , match_in_env_vars=False , ignore=[] , entrypoint=[] , command_bat='' , outputs_image_ref_to='' )

Provide a custom command that will build an image.

Example

custom_build(
  'gcr.io/my-project/frontend-server',
  'docker build -t $EXPECTED_REF .',
  ['.'],
)

Please read the Custom Build Script How-to on how to use this function.

All custom build scripts build an image and put it somewhere. But there are several different patterns for where they put the image, how they compute a digest of the contents, and how they push the image to the cluster. custom_build has many options to support different combinations of each mode. The guide has some examples of common combinations.

Parameters:
  • ref ( str ) – name for this image (e.g. ‘myproj/backend’ or ‘myregistry/myproj/backend’). If this image will be used in a k8s resource(s), this ref must match the spec.container.image param for that resource(s).
  • command ( str ) – a command that, when run in the shell, builds an image puts it in the registry as ref . In the default mode, must produce an image named $EXPECTED_REF . Executed with sh -c on macOS/Linux, or cmd /S /C on Windows.
  • deps ( List [ str ]) – a list of files or directories to be added as dependencies to this image. Tilt will watch those files and will rebuild the image when they change. Only accepts real paths, not file globs.
  • tag ( str ) – Some tools can’t change the image tag at runtime. They need a pre-specified tag. Tilt will set $EXPECTED_REF = image_name:tag , then re-tag it with its own tag before pushing to your cluster.
  • disable_push ( bool ) – whether Tilt should push the image in to the registry that the Kubernetes cluster has access to. Set this to true if your command handles pushing as well.
  • skips_local_docker ( bool ) – Whether your build command writes the image to your local Docker image store. Set this to true if you’re using a cloud-based builder or independent image builder like buildah .
  • live_update ( List [ LiveUpdateStep ]) –

    set of steps for updating a running container (see Live Update documentation ).

  • match_in_env_vars ( bool ) – specifies that k8s objects can reference this image in their environment variables, and Tilt will handle those variables the same as it usually handles a k8s container spec’s image s.
  • ignore ( Union [ str , List [ str ]]) – set of file patterns that will be ignored. Ignored files will not trigger builds and will not be included in images. Follows the dockerignore syntax . Patterns/filepaths will be evaluated relative to each dep (e.g. if you specify deps=['dep1', 'dep2'] and ignores=['foobar'] , Tilt will ignore both deps1/foobar and dep2/foobar ).
  • entrypoint ( Union [ str , List [ str ]]) – command to run when this container starts. Takes precedence over the container’s CMD or ENTRYPOINT , and over a container command specified in k8s YAML . If specified as a string, will be evaluated in a shell context (e.g. entrypoint="foo.sh bar" will be executed in the container as /bin/sh -c 'foo.sh bar' ); if specifed as a list, will be passed to the operating system as program name and args. Kubernetes-only.
  • command_bat ( str ) – The command to run, expressed as a Windows batch command executed with cmd /S /C . Takes precedence over the command parameter on Windows. Ignored on macOS/Linux.
  • outputs_image_ref_to ( str ) – Specifies a file path. When set, the custom build command must write a content-based tagged image ref to this file. Tilt will read that file after the cmd runs to get the image ref, and inject that image ref into the YAML. For more on content-based tags, see <custom_build.html#why-tilt-uses-immutable-tags>_
dc_resource ( name , trigger_mode=TRIGGER_MODE_AUTO , resource_deps=[] )

Configures the Docker Compose resource of the given name. Note: Tilt does an amount of resource configuration for you(for more info, see Tiltfile Concepts: Resources ); you only need to invoke this function if you want to configure your resource beyond what Tilt does automatically.

Parameters:
Return type:

None

decode_json ( json )

Deserializes the given JSON into a starlark object

Parameters: json ( Union [ str , Blob ]) – the JSON to deserialize
Return type: Union [ Dict [ str , Any ], List [ Any ]]
decode_yaml ( yaml )

Deserializes the given yaml document into a starlark object

Parameters: yaml ( Union [ str , Blob ]) – the yaml to deserialize
Return type: Union [ Dict [ str , Any ], List [ Any ]]
decode_yaml_stream ( yaml )

Deserializes the given yaml stream (i.e., any number of yaml documents, separated by "\n---\n" ) into a list of starlark objects.

Parameters: yaml ( Union [ str , Blob ]) – the yaml to deserialize
Return type: List [ Union [ Dict [ str , Any ], List [ Any ]]]
default_registry ( host , host_from_cluster=None , single_name='' )

Specifies that any images that Tilt builds should be renamed so that they have the specified Docker registry.

This is useful if, e.g., a repo is configured to push to Google Container Registry, but you want to use Elastic Container Registry instead, without having to edit a bunch of configs. For example, default_registry("gcr.io/myrepo") would cause docker.io/alpine to be rewritten to gcr.io/myrepo/docker.io_alpine

For more info, see our Using a Personal Registry Guide .

Parameters:
  • host ( str ) – host of the registry that all built images should be renamed to use.
  • host_from_cluster ( Optional [ str ]) – registry host to use when referencing images from inside the cluster (i.e. in Kubernetes YAML). Only include this arg if it is different from host . For more on this use case, see this guide .
  • single_name ( str ) – In ECR, each repository in a registry needs to be created up-front. single_name lets you set a single repository to push to (e.g., a personal dev repository), and embeds the image name in the tag instead.

Images are renamed following these rules:

  1. Replace / and @ with _ .
  2. Prepend the value of host and a / .

e.g., with default_registry('gcr.io/myorg') , an image called user-service becomes gcr.io/myorg/user-service .

(Note: this logic is currently crude, on the assumption that development image names are ephemeral and unimportant. Please let us know if they don’t suit you!)

Return type: None
disable_snapshots ( )

Disables Tilt’s snapshots feature, hiding it from the UI.

This is intended for use in projects where there might be some kind of data policy that does not allow developers to upload snapshots to TiltCloud.

Note that this directive does not provide any real security, since a developer can always simply edit it out of the Tiltfile, but it at least ensures a pretty high bar of intent.

Return type: None
docker_build ( ref , context , build_args={} , dockerfile='Dockerfile' , dockerfile_contents='' , live_update=[] , match_in_env_vars=False , ignore=[] , only=[] , entrypoint=[] , target='' , ssh='' , network='' , secret='' , extra_tag='' , container_args=None , cache_from=[] , pull=False )

Builds a docker image.

The invocation

docker_build('myregistry/myproj/backend', '/path/to/code')

is roughly equivalent to the shell call

docker build /path/to/code -t myregistry/myproj/backend

For more information on the ignore and only parameters, see our Guide to File Changes .

Note that you can’t set both the dockerfile and dockerfile_contents arguments (will throw an error).

Note also that the entrypoint parameter is not supported for Docker Compose resources. If you need it for your use case, let us know.

Parameters:
  • ref ( str ) – name for this image (e.g. ‘myproj/backend’ or ‘myregistry/myproj/backend’). If this image will be used in a k8s resource(s), this ref must match the spec.container.image param for that resource(s).
  • context ( str ) – path to use as the Docker build context.
  • build_args ( Dict [ str , str ]) – build-time variables that are accessed like regular environment variables in the RUN instruction of the Dockerfile. See the Docker Build Arg documentation .
  • dockerfile ( str ) – path to the Dockerfile to build.
  • dockerfile_contents ( Union [ str , Blob ]) – raw contents of the Dockerfile to use for this build.
  • live_update ( List [ LiveUpdateStep ]) –

    set of steps for updating a running container (see Live Update documentation ).

  • match_in_env_vars ( bool ) – specifies that k8s objects can reference this image in their environment variables, and Tilt will handle those variables the same as it usually handles a k8s container spec’s image s.
  • ignore ( Union [ str , List [ str ]]) –

    set of file patterns that will be ignored. Ignored files will not trigger builds and will not be included in images. Follows the dockerignore syntax . Patterns will be evaluated relative to the context parameter.

  • only ( Union [ str , List [ str ]]) – set of file paths that should be considered for the build. All other changes will not trigger a build and will not be included in images. Inverse of ignore parameter. Only accepts real paths, not file globs. Patterns will be evaluated relative to the context parameter.
  • entrypoint ( Union [ str , List [ str ]]) –

    command to run when this container starts. Takes precedence over the container’s CMD or ENTRYPOINT , and over a container command specified in k8s YAML . If specified as a string, will be evaluated in a shell context (e.g. entrypoint="foo.sh bar" will be executed in the container as /bin/sh -c 'foo.sh bar' ); if specifed as a list, will be passed to the operating system as program name and args.

  • target ( str ) – Specify a build stage in the Dockerfile. Equivalent to the docker build --target flag.
  • ssh ( Union [ str , List [ str ]]) – Include SSH secrets in your build. Use ssh=’default’ to clone private repositories inside a Dockerfile. Uses the syntax in the docker build –ssh flag .
  • network ( str ) – Set the networking mode for RUN instructions. Equivalent to the docker build --network flag.
  • secret ( Union [ str , List [ str ]]) – Include secrets in your build in a way that won’t show up in the image. Uses the same syntax as the docker build –secret flag .
  • extra_tag ( Union [ str , List [ str ]]) – Tag an image with one or more extra references after each build. Useful when running Tilt in a CI pipeline, where you want each image to be tagged with the pipeline ID so you can find it later. Uses the same syntax as the docker build --tag flag.
  • container_args ( Optional [ List [ str ]]) – args to run when this container starts. Takes precedence over a container args specified in k8s YAML .
  • cache_from ( Union [ str , List [ str ]]) – Cache image builds from a remote registry. Uses the same syntax as docker build –cache-from flag .
  • pull ( bool ) – Force pull the latest version of parent images. Equivalent to the docker build --pull flag.
Return type:

None

docker_compose ( configPaths )

Run containers with Docker Compose.

Tilt will read your Docker Compose YAML and separate out the services. We will infer which services defined in your YAML correspond to images defined elsewhere in your Tiltfile (matching based on the DockerImage ref).

Tilt will watch your Docker Compose YAML and reload if it changes.

For more info, see the guide to Tilt with Docker Compose .

Examples:

# Path to file
docker_compose('./docker-compose.yml')

# List of files
docker_compose(['./docker-compose.yml', './docker-compose.override.yml'])
Parameters: configPaths ( Union [ str , List [ str ]]) – Path(s) to Docker Compose yaml files.
Return type: None
docker_prune_settings ( disable=True , max_age_mins=360 , num_builds=0 , interval_hrs=1 , keep_recent=2 )

Configures Tilt’s Docker Pruner, which runs occasionally in the background and prunes Docker images associated with your current project.

The pruner runs soon after startup (as soon as at least some resources are declared, and there are no pending builds). Subsequently, it runs after every num_builds Docker builds, or, if num_builds is not set, every interval_hrs hours.

The pruner will prune:
  • stopped containers built by Tilt that are at least max_age_mins mins old
  • images built by Tilt and associated with this Tilt run that are at least max_age_mins mins old, and not in the keep_recent most recent builds for that image name
  • dangling build caches that are at least max_age_mins mins old
Parameters:
  • disable ( bool ) – if true, disable the Docker Pruner
  • max_age_mins ( int ) – maximum age, in minutes, of images/containers to retain. Defaults to 360 mins., i.e. 6 hours
  • num_builds ( int ) – number of Docker builds after which to run a prune. (If unset, the pruner instead runs every interval_hrs hours)
  • interval_hrs ( int ) – run a Docker Prune every interval_hrs hours (unless num_builds is set, in which case use the “prune every X builds” logic). Defaults to 1 hour
  • keep_recent ( int ) – when pruning, retain at least the keep_recent most recent images for each image name. Defaults to 2
Return type:

None

enable_feature ( feature_name )

Configures Tilt to enable non-default features (e.g., experimental or deprecated).

The Tilt features controlled by this are generally in an unfinished state, and not yet documented.

As a Tiltfile author, you don’t need to worry about this function unless something else directs you to (e.g., an experimental feature doc, or a conversation with a Tilt contributor).

As a Tiltfile reader, you can probably ignore this, or you can ask the person who added it to the Tiltfile what it’s doing there.

Parameters: feature_name ( str ) – name of the feature to enable
Return type: None
encode_json ( obj )

Serializes the given starlark object into JSON.

Only supports maps with string keys, lists, strings, ints, and bools.

Parameters: obj ( Union [ Dict [ str , Any ], List [ Any ]]) – the object to serialize
Return type: Blob
encode_yaml ( obj )

Serializes the given starlark object into YAML.

Only supports maps with string keys, lists, strings, ints, and bools.

Parameters: obj ( Union [ Dict [ str , Any ], List [ Any ]]) – the object to serialize
Return type: Blob
encode_yaml_stream ( objs )

Serializes the given starlark objects into a YAML stream (i.e., multiple YAML documents, separated by "\n---\n" ).

Only supports maps with string keys, lists, strings, ints, and bools.

Parameters: objs ( List [ Union [ Dict [ str , Any ], List [ Any ]]]) – the object to serialize
Return type: Blob
fail ( msg )

Raises an error that cannot be intercepted. Can be used anywhere in a Tiltfile.

Return type: None
fall_back_on ( files )

Specify that any changes to the given files will cause Tilt to fall back to a full image build (rather than performing a live update).

fall_back_on step(s) may only go at the beginning of your list of steps.

(Files must be a subset of the files that we’re already watching for this image; that is, if any files fall outside of DockerBuild.context or CustomBuild.deps, an error will be raised.)

For more info, see the Live Update Reference .

Parameters: files ( Union [ str , List [ str ]]) – a string or list of strings of files. If relative, will be evaluated relative to the Tiltfile. Tilt compares these to the local paths of edited files when determining whether to fall back to a full image build.
Return type: LiveUpdateStep
filter_yaml ( yaml , labels=None , name=None , namespace=None , kind=None , api_version=None )

Call this with a path to a file that contains YAML, or with a Blob of YAML. (E.g. it can be called on the output of kustomize or helm .)

Captures the YAML entities that meet the filter criteria and returns them as a blob; returns the non-matching YAML as the second return value.

For example, if you have a file of all your YAML, but only want to pass a few elements to Tilt:

# extract all YAMLs matching labels "app=foobar"
foobar_yaml, rest = filter_yaml('all.yaml', labels={'app': 'foobar'})
k8s_yaml(foobar_yaml)

# extract YAMLs of kind "deployment" with metadata.name regex-matching "baz", also matching "bazzoo" and "bar-baz"
baz_yaml, rest = filter_yaml(rest, name='baz', kind='deployment')
k8s_yaml(baz_yaml)

# extract YAMLs of kind "deployment" exactly matching metadata.name "foo"
foo_yaml, rest = filter_yaml(rest, name='^foo$', kind='deployment')
k8s_yaml(foo_yaml)
Parameters:
  • yaml ( Union [ str , List [ str ], Blob ]) – Path(s) to YAML, or YAML as a Blob .
  • labels ( Optional [ dict ]) – return only entities matching these labels. (Matching entities must satisfy all of the specified label constraints, though they may have additional labels as well: see the Kubernetes docs for more info.)
  • name ( Optional [ str ]) – Case-insensitive regexp specifying the metadata.name property of entities to match
  • namespace ( Optional [ str ]) – Case-insensitive regexp specifying the metadata.namespace property of entities to match
  • kind ( Optional [ str ]) – Case-insensitive regexp specifying the kind of entities to match (e.g. “Service”, “Deployment”, etc.).
  • api_version ( Optional [ str ]) – Case-insensitive regexp specifying the apiVersion for kind , (e.g., “apps/v1”)
Returns:

2-element tuple containing

  • matching ( Blob ): blob of YAML entities matching given filters
  • rest ( Blob ): the rest of the YAML entities

helm ( pathToChartDir , name='' , namespace='' , values=[] , set=[] )

Run helm template on a given directory that contains a chart and return the fully rendered YAML as a Blob Chart directory is watched (See watch_file ).

For more examples, see the Helm Cookbook .

Parameters:
  • pathToChartDir ( str ) – Path to the directory locally (absolute, or relative to the location of the Tiltfile).
  • name ( str ) – The release name. Equivalent to the helm –name flag
  • namespace ( str ) – The namespace to deploy the chart to. Equivalent to the helm –namespace flag
  • values ( Union [ str , List [ str ]]) – Specify one or more values files (in addition to the values.yaml file in the chart). Equivalent to the Helm --values or -f flags ( see docs ).
  • set ( Union [ str , List [ str ]]) – Specify one or more values. Equivalent to the Helm --set flag.
Return type:

Blob

include ( path )

Include another Tiltfile.

Loads any builds or resources defined in that Tiltfile.

If you want to define common functions or constants and import them into another Tiltfile, see the load() function.

Example

include('./frontend/Tiltfile')
include('./backend/Tiltfile')
k8s_context ( )

Returns the name of the Kubernetes context Tilt is connecting to.

Example

if k8s_context() == 'prod':
  fail("failing early to avoid overwriting prod")
Return type: str
k8s_kind ( kind , api_version=None , * , image_json_path=[] , image_object_json_path=None , pod_readiness='' )

Tells Tilt about a k8s kind.

For CRDs that use images built by Tilt: call this with image_json_path or image_object to tell Tilt where in the CRD’s spec the image is specified.

For CRDs that do not use images built by Tilt, but have pods you want in a Tilt resource: call this without image_json_path , simply to specify that this type is a Tilt workload. Then call k8s_resource() with extra_pod_selectors to specify which pods Tilt should associate with this resource.

(Note the * in the signature means image_json_path must be passed as a keyword, e.g., image_json_path=”{.spec.image}” )

Example

# Fission has a CRD named "Environment"
k8s_yaml('deploy/fission.yaml')
k8s_kind('Environment', image_json_path='{.spec.runtime.image}')

Here’s an example that specifies the image location in a UselessMachine Custom Resource .

Parameters:
  • kind ( str ) – Case-insensitive regexp specifying he value of the kind field in the k8s object definition (e.g., “Deployment” )
  • api_version ( Optional [ str ]) – Case-insensitive regexp specifying the apiVersion for kind , (e.g., “apps/v1”)
  • image_json_path ( Union [ str , List [ str ]]) – Either a string or a list of string containing json path(s) within that kind’s definition specifying images deployed with k8s objects of that type. This uses the k8s json path template syntax, described here .
  • image_object – A specifier of the form image_object={‘json_path’: ‘{.path.to.field}’, ‘repo_field’: ‘repo’, ‘tag_field’: ‘tag’} . Used to tell Tilt how to inject images into Custom Resources that express the image repo and tag as separate fields.
  • pod_readiness ( str ) – Possible values: ‘ignore’, ‘wait’. Controls whether Tilt waits for pods to be ready before the resource is considered healthy (and dependencies can start building). By default, Tilt will wait for pods to be ready if it thinks a resource has pods. This can be overridden on a resource-by-resource basis by the k8s_resource function.
k8s_resource ( workload='' , new_name='' , port_forwards=[] , extra_pod_selectors=[] , trigger_mode=TRIGGER_MODE_AUTO , resource_deps=[] , objects=[] , auto_init=True , pod_readiness='' , links=[] )

Configures or creates the specified Kubernetes resource.

A “resource” is a bundle of work managed by Tilt: a Kubernetes resource consists of one or more Kubernetes objects to deploy, and zero or more image build directives for the images referenced therein.

Tilt assembles Kubernetes resources automatically, as described in Tiltfile Concepts: Resources . You may call k8s_resource to configure an automatically created Kubernetes resource, or to create and configure a new one:

  • If configuring an automatically created resource: the workload parameter must be specified.
  • If creating a new resource: both the objects and new_name parameters must be specified.

Calling k8s_resource is optional ; you can use this function to configure port forwarding for your resource, to rename it, or to adjust any of the other settings specified below, but in many cases, Tilt’s default behavior is sufficient.

Examples:

# load Deployment foo
k8s_yaml('foo.yaml')

# modify the resource called "foo" (auto-assembled by Tilt)
# to forward container port 8080 to localhost:8080
k8s_resource(workload='foo', port_forwards=8080)
# load CRD "bar", Service "bar", and Secret "bar-password"
k8s_yaml('bar.yaml')

# create a new resource called "bar" which contains the objects
# loaded above (none of which are workloads, so none of which
# would be automatically assigned to a resource). Note that the
# first two object selectors specify both 'name' and 'kind',
# since just the string "bar" does not uniquely specify a single object.
# As the object name "bar-password" is unique, "bar-password" suffices as
# an object selector (though a more more qualified object selector
# like "bar-password:secret" or "bar-password:secret:default" would
# be accepted as well).
k8s_resource(
  objects=['bar:crd', 'bar:service', 'bar-password'],
  new_name='bar'
)

For more examples, see Tiltfile Concepts: Resources .

Parameters:
  • workload ( str ) – The name of an existing auto-assembled resource to configure (Tilt generates resource names when it assembles resources by workload ). (If you instead want to create/configure a _new_ resource, use the objects parameter in conjunction with new_name .)
  • new_name ( str ) – If non-empty, will be used as the new name for this resource. (To programmatically rename all resources, see workload_to_resource_function() .)
  • port_forwards ( Union [ str , int , PortForward , List [ Union [ str , int , PortForward ]]]) – Local ports to connect to the pod. If a target port is specified, that will be used. Otherwise, if the container exposes a port with the same number as the local port, that will be used. Otherwise, the default container port will be used. Port forward configurations may also be specified with a PortForward object. Example values: 9000 (connect localhost:9000 to the container’s port 9000, if it is exposed, otherwise connect to the container’s default port), ‘9000:8000’ (connect localhost:9000 to the container port 8000), [‘9000:8000’, ‘9001:8001’] (connect localhost:9000 and :9001 to the container ports 8000 and 8001, respectively). [8000, 8001] (assuming the container exposes both 8000 and 8001, connect localhost:8000 and localhost:8001 to the container’s ports 8000 and 8001, respectively).
  • extra_pod_selectors ( Union [ Dict [ str , str ], List [ Dict [ str , str ]]]) – In addition to relying on Tilt’s heuristics to automatically find Kubernetes resources associated with this resource, a user may specify extra labelsets to force pods to be associated with this resource. An pod will be associated with this resource if it has all of the labels in at least one of the entries specified (but still also if it meets any of Tilt’s usual mechanisms).
  • trigger_mode ( TriggerMode ) –

    One of TRIGGER_MODE_AUTO or TRIGGER_MODE_MANUAL . For more info, see the Manual Update Control docs .

  • resource_deps ( List [ str ]) –

    A list of resources on which this resource depends. See the Resource Dependencies docs .

  • objects ( List [ str ]) – A list of Kubernetes objects to be added to this resource, specified via Tilt’s Kubernetes Object Selector syntax. If the workload parameter is specified, these objects will be added to the existing resource; otherwise, these objects will form a new resource with name new_name . If an object selector matches more than one Kubernetes object, or matches an object already associated with a resource, k8s_resource raises an error.
  • auto_init ( bool ) – whether this resource runs on tilt up . Defaults to True . Note that auto_init=False is only compatible with trigger_mode=TRIGGER_MODE_MANUAL .
  • pod_readiness ( str ) – Possible values: ‘ignore’, ‘wait’. Controls whether Tilt waits for pods to be ready before the resource is considered healthy (and dependencies can start building). By default, Tilt will wait for pods to be ready if it thinks a resource has pods.
  • links ( Union [ str , Link , List [ Union [ str , Link ]]]) – one of more links to be associated with this resource in the UI. (Note that port forwards specified via the port_forwards parameter will automatically show up as URLs in the UI; rather, the links parameter is generally for non-port-forward URLs, e.g. your ingress always sets up an endpoint my.service.foo .)
Return type:

None

k8s_yaml ( yaml , allow_duplicates=False )

Call this with a path to a file that contains YAML, or with a Blob of YAML.

We will infer what (if any) of the k8s resources defined in your YAML correspond to Images defined elsewhere in your Tiltfile (matching based on the DockerImage ref and on pod selectors). Any remaining YAML is YAML that Tilt applies to your k8s cluster independently.

Any YAML files are watched (See watch_file ).

Examples:

# path to file
k8s_yaml('foo.yaml')

# list of paths
k8s_yaml(['foo.yaml', 'bar.yaml'])

# Blob, i.e. `local` output (in this case, script output)
templated_yaml = local('./template_yaml.sh')
k8s_yaml(templated_yaml)
Parameters:
  • yaml ( Union [ str , List [ str ], Blob ]) – Path(s) to YAML, or YAML as a Blob .
  • allow_duplicates ( bool ) – If you try to register the same Kubernetes resource twice, this function will assume this is a mistake and emit an error. Set allow_duplicates=True to allow duplicates. There are some Helm charts that have duplicate resources for esoteric reasons.
Return type:

None

kustomize ( pathToDir )

Run kustomize on a given directory and return the resulting YAML as a Blob Directory is watched (see watch_file ). Checks for and uses separately installed kustomize first, if it exists. Otherwise, uses kubectl’s kustomize. See blog post .

Parameters: pathToDir ( str ) – Path to the directory locally (absolute, or relative to the location of the Tiltfile).
Return type: Blob

Creates a Link object that describes a link associated with a resource.

Parameters:
  • url ( str ) – the URL to link to
  • name ( str , optional ) – the name of the link. If provided, this will be the text of this URL when displayed in the Web UI. This parameter can be useful for disambiguating between multiple links on a single resource, e.g. naming one link “App” and one “Debugger.” If not given, the Web UI displays the URL itself (e.g. “localhost:8888”).
Return type:

Link

listdir ( directory , recursive=False )

Returns all the files at the top level of the provided directory. If recursive is set to True, returns all files that are inside of the provided directory, recursively.

Directory is watched (See watch_file ).

Return type: List [ str ]
load ( path , *args )

Include another Tiltfile.

Similar to include(path) , but binds variables in the global scope.

Used when you want to define common functions or constants to share across Tiltfiles.

Example

load('./lib/Tiltfile', 'create_namespace')
create_namespace('frontend')

If path starts with "ext://" the path will be treated as a Tilt Extension .

Example

load('ext://hello_world', 'hi') # Resolves to https://github.com/tilt-dev/tilt-extensions/blob/master/hello_world/Tiltfile
hi() # prints "Hello world!"
local ( command , quiet=False , command_bat='' , echo_off=False )

Runs a command on the host machine, waits for it to finish, and returns its stdout as a Blob

Parameters:
  • command ( Union [ str , List [ str ]]) – Command to run. If a string, executed with sh -c on macOS/Linux, or cmd /S /C on Windows; if a list, will be passed to the operating system as program name and args.
  • quiet ( bool ) – If set to True, skips printing output to log.
  • command_bat ( str ) – The command to run, expressed as a Windows batch command executed with cmd /S /C . Takes precedence over the command parameter on Windows. Ignored on macOS/Linux.
  • echo_off ( bool ) – If set to True, skips printing command to log.
Return type:

Blob

local_resource ( name , cmd , deps=None , trigger_mode=TRIGGER_MODE_AUTO , resource_deps=[] , ignore=[] , auto_init=True , serve_cmd='' , cmd_bat='' , serve_cmd_bat='' , allow_parallel=False , links=[] )

Configures one or more commands to run on the host machine (not in a remote cluster).

By default, Tilt performs an update on local resources on tilt up and whenever any of their deps change.

When Tilt performs an update on a local resource:

  • if cmd is non-empty, it is executed
  • if cmd succeeds: - Tilt kills any extant serve_cmd process from previous updates of this resource - if serve_cmd is non-empty, it is executed

For more info, see the Local Resource docs .

Parameters:
  • name ( str ) – will be used as the new name for this resource
  • cmd ( Union [ str , List [ str ]]) – command to be executed on host machine. If a string, executed with sh -c on macOS/Linux, or cmd /S /C on Windows; if a list, will be passed to the operating system as program name and args.
  • deps ( Union [ str , List [ str ], None ]) – a list of files or directories to be added as dependencies to this cmd. Tilt will watch those files and will run the cmd when they change. Only accepts real paths, not file globs.
  • trigger_mode ( TriggerMode ) –

    one of TRIGGER_MODE_AUTO or TRIGGER_MODE_MANUAL . For more info, see the Manual Update Control docs .

  • resource_deps ( List [ str ]) –

    a list of resources on which this resource depends. See the Resource Dependencies docs .

  • ignore ( Union [ str , List [ str ]]) –

    set of file patterns that will be ignored. Ignored files will not trigger runs. Follows the dockerignore syntax . Patterns will be evaluated relative to the Tiltfile.

  • auto_init ( bool ) – whether this resource runs on tilt up . Defaults to True . Note that auto_init=False is only compatible with trigger_mode=TRIGGER_MODE_MANUAL .
  • serve_cmd ( str ) – Tilt will run this command on update and expect it to not exit. Executed with sh -c on macOS/Linux, or cmd /S /C on Windows.
  • cmd_bat ( str ) – The command to run, expressed as a Windows batch command executed with cmd /S /C . Takes precedence over the cmd parameter on Windows. Ignored on macOS/Linux.
  • serve_cmd_bat ( str ) – The command to run, expressed as a Windows batch command executed with cmd /S /C . Takes precedence over the serve_cmd parameter on Windows. Ignored on macOS/Linux.
  • allow_parallel ( bool ) – By default, all local resources are presumed unsafe to run in parallel, due to race conditions around modifying a shared file system. Set to True to allow them to run in parallel.
  • links ( Union [ str , Link , List [ Union [ str , Link ]]]) – one of more links to be associated with this resource in the Web UI (e.g. perhaps you have a “reset database” workflow and want to attach a link to the database web console). Provide one or more strings (the URLs to link to) or Link objects.
Return type:

None

port_forward ( local_port , container_port=None , name=None , link_path=None )

Creates a PortForward object specifying how to set up and display a Kubernetes port forward.

By default, the host for a port-forward is localhost . This can be changed with the --host flag when invoking Tilt via the CLI.

Parameters:
  • local_port ( int ) – the local port to forward traffic to.
  • container_port ( int , optional ) – if provided, the container port to forward traffic from . If not provided, Tilt will forward traffic from local_port , if exposed, and otherwise, from the first default container port. E.g.: PortForward(1111) forwards traffic from container port 1111 (if exposed; otherwise first default container port) to localhost:1111 .
  • name ( str , optional ) – the name of the link. If provided, this will be text of this URL when displayed in the Web UI. This parameter can be useful for disambiguating between multiple port-forwards on a single resource, e.g. naming one link “App” and one “Debugger.” If not given, the Web UI displays the URL itself (e.g. “localhost:8888”).
  • link_path ( str , optional ) – if given, the path at the port forward URL to link to; e.g. a port forward on localhost:8888 with link_path='/v1/app' would surface a link in the UI to localhost:8888/v1/app .
Return type:

PortForward

read_file ( file_path , default=None )

Reads file and returns its contents.

If the file_path does not exist and default is not None , default will be returned. In any other case, an error reading file_path will be a Tiltfile load error.

Parameters:
  • file_path ( str ) – Path to the file locally (absolute, or relative to the location of the Tiltfile).
  • default ( Optional [ str ]) – If not None and the file at file_path does not exist, this value will be returned.
Return type:

Blob

read_json ( path , default=None )

Reads the file at path and deserializes its contents as JSON

If the path does not exist and default is not None , default will be returned. In any other case, an error reading path will be a Tiltfile load error.

Parameters:
  • path ( str ) – Path to the file locally (absolute, or relative to the location of the Tiltfile).
  • default ( Optional [ str ]) – If not None and the file at path does not exist, this value will be returned.
Return type:

Union [ Dict [ str , Any ], List [ Any ]]

read_yaml ( path , default=None )

Reads the file at path and deserializes its contents into a starlark object

If the path does not exist and default is not None , default will be returned. In any other case, an error reading path will be a Tiltfile load error.

Parameters:
  • path ( str ) – Path to the file locally (absolute, or relative to the location of the Tiltfile).
  • default ( Union [ Dict [ str , Any ], List [ Any ], None ]) – If not None and the file at path does not exist, this value will be returned.
Return type:

Union [ Dict [ str , Any ], List [ Any ]]

read_yaml_stream ( path , default=None )

Reads a yaml stream (i.e., yaml documents separated by "\n---\n" ) from the file at path and deserializes its contents into a starlark object

If the path does not exist and default is not None , default will be returned. In any other case, an error reading path will be a Tiltfile load error.

Parameters:
  • path ( str ) – Path to the file locally (absolute, or relative to the location of the Tiltfile).
  • default ( Optional [ List [ Union [ Dict [ str , Any ], List [ Any ]]]]) – If not None and the file at path does not exist, this value will be returned.
Return type:

List [ Union [ Dict [ str , Any ], List [ Any ]]]

restart_container ( )

For use with Docker Compose resources only.

Specify that a container should be restarted when it is live-updated. In practice, this means that the container re-executes its ENTRYPOINT within the changed filesystem.

May only be included in a live_update once, and only as the last step.

For more info (and for the equivalent functionality for Kubernetes resources), see the Live Update Reference .

Return type: LiveUpdateStep
run ( cmd , trigger=[] )

Specify that the given cmd should be executed when updating an image’s container

May not precede any sync steps in a live_update .

For more info, see the Live Update Reference .

Parameters:
  • cmd ( str ) – A shell command.
  • trigger ( Union [ List [ str ], str ]) – If the trigger argument is specified, the build step is only run when there are changes to the given file(s). Paths relative to Tiltfile. (Note that in addition to matching the trigger, file changes must also match at least one of this Live Update’s syncs in order to trigger this run. File changes that do not match any syncs will be ignored.)
Return type:

LiveUpdateStep

secret_settings ( disable_scrub=False )

Configures Tilt’s handling of Kubernetes Secrets. By default, Tilt scrubs the text of any Secrets from the logs; e.g. if Tilt applies a Secret with contents ‘mysecurepassword’, Tilt redacts this string if ever it appears in the logs, to prevent users from accidentally sharing sensitive information in snapshots etc.

If you need other configuration options, let us know .

Parameters: disable_scrub ( bool ) – if True, Tilt will not scrub secrets from logs.
Return type: None
set_team ( team_id )

Associates this Tiltfile with the team identified by team_id .

Sends usage information to Tilt Cloud periodically.

Return type: None
struct ( **kwargs )

Creates an object with arbitrary fields.

Examples:

x = struct(a="foo", b=6)
print("%s %d" % (x.a, x.b)) # prints "foo 6"
Return type: Any
sync ( local_path , remote_path )

Specify that any changes to localPath should be synced to remotePath

May not follow any run steps in a live_update .

For more info, see the Live Update Reference .

Parameters:
  • localPath – A path relative to the Tiltfile’s directory. Changes to files matching this path will be synced to remotePath . Can be a file (in which case just that file will be synced) or directory (in which case any files recursively under that directory will be synced).
  • remotePath – container path to which changes will be synced. Must be absolute.
Return type:

LiveUpdateStep

trigger_mode ( trigger_mode )

Sets the default TriggerMode for resources in this Tiltfile. (Trigger mode may still be adjusted per-resource with k8s_resource() .)

If this function is not invoked, the default trigger mode for all resources is TRIGGER MODE AUTO .

See also: Manual Update Control documentation

Parameters: trigger_mode ( TriggerMode ) – may be one of TRIGGER_MODE_AUTO or TRIGGER_MODE_MANUAL
update_settings ( max_parallel_updates=3 , k8s_upsert_timeout_secs=30 )

Configures Tilt’s updates to your resources. (An update is any execution of or change to a resource. Examples of updates include: doing a docker build + deploy to Kubernetes; running a live update on an existing container; and executing a local resource command).

If you need other configuration options, let us know .

Parameters:
  • max_parallel_updates ( int ) – maximum number of updates Tilt will execute in parallel. Default is 3. Must be a positive integer.
  • k8s_upsert_timeout_secs ( int ) – timeout (in seconds) for Kubernetes upserts (i.e. create / apply calls). Minimum value is 1.
Return type:

None

version_settings ( check_updates=True , constraint='' )

Controls Tilt’s behavior with regard to its own version.

Parameters:
  • check_updates ( bool ) – If true, Tilt will check GitHub for new versions of itself and display a notification in the web UI when an upgrade is available.
  • constraint ( str ) –

    If non-empty, Tilt will check its currently running version against this constraint and generate an error if it doesn’t match. Examples:

    • <0.17.0 - less than 0.17.0
    • >=0.13.2 - at least 0.13.2

    See more at the constraint syntax documentation .

Return type:

None

watch_file ( file_path )

Watches a file. If the file is changed a re-exectution of the Tiltfile is triggered.

Parameters: file_path ( str ) – Path to the file locally (absolute, or relative to the location of the Tiltfile).
Return type: None
watch_settings ( ignore )

Configures global watches.

May be called multiple times to add more ignore patterns.

Parameters: ignore ( Union [ str , List [ str ]]) – A string or list of strings that should not trigger updates. Equivalent to adding patterns to .tiltignore. Relative patterns are evaluated relative to the current working dir. See Debugging File Changes for more details.
Return type: None
workload_to_resource_function ( fn )

Provide a function that will be used to name Tilt resources .

Tilt will auto-generate resource names for you. If you do not like the names it generates, you can use this to customize how Tilt generates names.

Example

# name all tilt resources after the k8s object namespace + name
def resource_name(id):
  return id.namespace + '-' + id.name
workload_to_resource_function(resource_name)

The names it generates must be unique (i.e., two workloads can’t map to the same resource name).

Parameters: fn ( Callable [[ K8sObjectID ], str ]) – A function that takes a K8sObjectID and returns a str . Tilt will call this function once for each workload to determine that workload’s resource’s name.
Return type: None
os. getcwd ( )

Returns a string representation of the current working directory.

The current working directory is the directory containing the currently executing Tiltfile. If your Tiltfile runs any commands, they run from this directory.

While calling :meth:load or :meth:include to execute another Tiltfile, returns the directory of the loaded/included Tiltfile.

Return type: str
os. getenv ( key , default=None )

Return the value of the environment variable key if it exists, or default if it doesn’t.

Parameters:
  • key ( str ) – An environment variable name.
  • default – The value to return if the variable doesn’t exist.
Return type:

str

os. putenv ( key , value )

Set the environment variable named key to the string value. Takes effect immediately in the Tilt process. Any new subprocesses will have this environment value.

Parameters:
  • key ( str ) – An environment variable name.
  • value ( str ) – The new value.
os. unsetenv ( key , value )

Delete the environment variable named key. Takes effect immediately in the Tilt process. Any new subprocesses will not have this variable.

Parameters: key ( str ) – An environment variable name.
os.path. abspath ( path )

Return a normalized, absolute version of the path, relative to the current working directory.

Parameters: path ( str ) – A filesystem path
Return type: str
os.path. basename ( path )

Return the basename of the path.

Parameters: path ( str ) – A filesystem path
Return type: str
os.path. dirname ( path )

Return the directory name of the path.

Parameters: path ( str ) – A filesystem path
Return type: str
os.path. exists ( path )

Checks if a file or directory exists at the specified path.

Returns false if this is a broken symlink, or if the user doesn’t have permission to stat the file at this path.

Watches the path, and reloads the Tiltfile if the contents change.

Parameters: path ( str ) – A filesystem path
Return type: bool
os.path. join ( path , *paths )

Join one or more path components with the OS-specific file separator.

Parameters:
  • path – A filesystem path component
  • paths ( str ) – A variable list of components to join
Return type:

str

os.path. realpath ( path )

Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).

Parameters: path ( str ) – A filesystem path
Return type: str
config. define_bool ( name , args=False , usage='' )

Defines a config setting of type bool .

Allows the user invoking Tilt to configure a key named name to be in the dict returned by parse() .

For instance, at runtime, to set a flag of this type named foo to value True , run tilt up -- --foo . To set a value to False , you can run tilt up -- --foo=False , or use a default value, e.g.: `python config.define_bool('foo') cfg = config.parse() do_stuff = cfg.get('foo', False) `

See the Tiltfile config documentation for examples and more information.

Parameters:
  • name ( str ) – The name of the config setting
  • args ( bool ) –

    If False, the config setting is specified by its name. (e.g., if it’s named “foo”, tilt up -- --foo this setting would be True .)

    If True, the config setting is specified by unnamed positional args. (e.g., in tilt up -- True , this setting would be True .) (This usage isn’t likely to be what you want)

  • usage ( str ) – When arg parsing fails, what to print for this setting’s description.
Return type:

None

config. define_string ( name , args=False , usage='' )

Defines a config setting of type str .

Allows the user invoking Tilt to configure a key named name to be in the dict returned by parse() .

For instance, at runtime, to set a flag of this type named foo to value “bar”, run tilt up -- --foo bar .

See the Tiltfile config documentation for examples and more information.

Parameters:
  • name ( str ) – The name of the config setting
  • args ( bool ) –

    If False, the config setting is specified by its name. (e.g., if it’s named “foo”, tilt up -- --foo bar this setting would be "bar" .)

    If True, the config setting is specified by unnamed positional args. (e.g., in tilt up -- 1 , this setting would be "1" .)

  • usage ( str ) – When arg parsing fails, what to print for this setting’s description.
Return type:

None

config. define_string_list ( name , args=False , usage='' )

Defines a config setting of type List[str] .

Allows the user invoking Tilt to configure a key named name to be in the dict returned by parse() .

See the Tiltfile config documentation for examples and more information.

Parameters:
  • name ( str ) – The name of the config setting
  • args ( bool ) –

    If False, the config setting is specified by its name. (e.g., if it’s named “foo”, tilt up -- --foo bar this setting would be ["bar"] .)

    If True, the config setting is specified by unnamed positional args. (e.g., in tilt up -- 1 2 3 , this setting would be ["1" "2" "3"] .)

  • usage ( str ) – When arg parsing fails, what to print for this setting’s description.
Return type:

None

config. parse ( )

Loads config settings from tilt_config.json, overlays config settings from Tiltfile command-line args, validates them using the setting definitions specified in the Tiltfile, and returns a Dict of the resulting settings.

Settings that are defined in the Tiltfile but not specified in the config file or command-line args will be absent from the dict. Access values via, e.g., cfg.get(‘foo’, [“hello”]) to have a default value.

Note: by default, Tilt interprets the Tilt command-line args as the names of Tilt resources to run. When a Tiltfile calls parse() , that behavior is suppressed, since those args are now managed by :meth:parse. If a Tiltfile uses parse() and also needs to allow specifying a set of resources to run, it needs to call set_enabled_resources() .

See the Tiltfile config documentation for examples and more information.

Return type: Dict [ str , Any ]
Returns: A Dict where the keys are settings names and the values are their values.
config. set_enabled_resources ( resources )

Tells Tilt to only run the specified resources. (takes precedence over the default behavior of “run the resources specified on the command line”)

Calling this with an empty list results in all resources being run.

See the Tiltfile config documentation for examples and more information.

Parameters: resources ( List [ str ]) – The names of the resources to run, or an empty list to run them all.
Return type: None
shlex. quote ( s )

Returns a shell-escaped version of s , which can be safely interpolated as a single token in a shell command.

e.g.:

mystring = "foo's bar"

# bad - runs: `docker run -e foo=foo's bar myimage` (invalid shell - unmatched ')
local('docker run -e foo=%s myimage' % mystring)

# good - runs: `docker run -e foo='foo'"'"'s bar' myimage`
#        which correctly sets $foo to "foo's bar"
local('docker run -e foo=%s myimage' % shlex.quote(mystring))
Return type: str

Types


class Blob

The result of executing a command on your local system.

Under the hood, a Blob is just a string, but we wrap it this way so Tilt knows the difference between a string meant to convey content and a string indicating, say, a filepath.

To wrap a string as a blob, call blob(my_str)

class K8sObjectID
name

The object’s name (e.g., “my-service” )

Type: str
kind

The object’s kind (e.g., “deployment” )

Type: str
namespace

The object’s namespace (e.g., “default” )

Type: str
group

The object’s group (e.g., “apps” )

Type: str

Specifications for a link associated with a resource in the Web UI.

For details, see the link() method.

class LiveUpdateStep

A step in the process of performing a LiveUpdate on an image’s container.

For details, see the Live Update documentation .

class PortForward

Specifications for setting up and displaying a Kubernetes port-forward.

For details, see the port_forward() method.

class TriggerMode

A set of constants that describe how Tilt triggers an update for a resource. Possible values are:

  • TRIGGER_MODE_AUTO : the default. When Tilt detects a change to files or config files associated with this resource, it triggers an update.
  • TRIGGER_MODE_MANUAL : user manually triggers update for dirty resources (i.e. resources with pending changes) via a button in the UI. (Note that the initial build always occurs automatically.)

The default trigger mode for all manifests may be set with the top-level function trigger_mode() (if not set, defaults to TRIGGER_MODE_AUTO ), and per-resource with k8s_resource() / dc_resource() .

See also: Manual Update Control documentation

 
 
 

Was this doc helpful?