github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/tiltfile/api/__init__.py (about) 1 from typing import Dict, Union, List, Callable, Any, Optional 2 3 # Our documentation generation framework doesn't properly handle __file__, 4 # so we call it __file__ and edit it later. 5 file__: str = "" 6 """The path of the Tiltfile. Set as a local variable in each Tiltfile as it loads. 7 """ 8 9 class Blob: 10 """The result of executing a command on your local system. 11 12 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. 13 14 To wrap a string as a blob, call ``blob(my_str)``""" 15 16 class LiveUpdateStep: 17 """A step in the process of performing a LiveUpdate on an image's container. 18 19 For details, see the `Live Update documentation <live_update_reference.html>`_. 20 """ 21 pass 22 23 class PortForward: 24 """ 25 Specifications for setting up and displaying a Kubernetes port-forward. 26 27 For details, see the :meth:`port_forward` method. 28 """ 29 pass 30 31 32 class Probe: 33 """Specification for a resource readiness check. 34 35 For details, see the :meth:`probe` function. 36 """ 37 pass 38 39 40 class ExecAction: 41 """Specification for a command to execute that determines resource readiness. 42 43 For details, see the :func:`probe` and :func:`exec_action` functions. 44 """ 45 pass 46 47 48 class HTTPGetAction: 49 """Specification for a HTTP GET request to perform that determines resource readiness. 50 51 For details, see the :func:`probe` and :func:`http_get_action` functions. 52 """ 53 pass 54 55 56 class TCPSocketAction: 57 """Specification for a TCP socket connection to perform that determines resource readiness. 58 59 For details, see the :func:`probe` and :func:`tcp_socket_action` functions. 60 """ 61 pass 62 63 64 def port_forward(local_port: int, 65 container_port: Optional[int] = None, 66 name: Optional[str] = None, 67 link_path: Optional[str] = None, 68 host: Optional[str] = None) -> PortForward: 69 """ 70 Creates a :class:`~api.PortForward` object specifying how to set up and display a Kubernetes port forward. 71 72 By default, the host for a port-forward is ``localhost``. This can be changed with 73 the ``--host`` flag when invoking Tilt via the CLI. 74 75 Args: 76 local_port (int): the local port to forward traffic to. 77 container_port (int, optional): if provided, the container port to forward traffic *from*. 78 If not provided, Tilt will forward traffic from ``local_port``, if exposed, and otherwise, 79 from the first default container port. E.g.: ``PortForward(1111)`` forwards traffic from 80 container port 1111 (if exposed; otherwise first default container port) to ``localhost:1111``. 81 name (str, optional): the name of the link. If provided, this will be text of this URL when 82 displayed in the Web UI. This parameter can be useful for disambiguating between multiple 83 port-forwards on a single resource, e.g. naming one link "App" and one "Debugger." If not 84 given, the Web UI displays the URL itself (e.g. "localhost:8888"). 85 link_path (str, optional): if given, the path at the port forward URL to link to; e.g. a port 86 forward on localhost:8888 with ``link_path='/v1/app'`` would surface a link in the UI to 87 ``localhost:8888/v1/app``. 88 host (str, optional): if given, the host of the port forward (by default, ``localhost``). E.g. 89 a call to `port_forward(8888, host='elastic.local')` would forward container port 8888 to 90 ``elastic.local:8888``. 91 """ 92 pass 93 94 class Link: 95 """ 96 Specifications for a link associated with a resource in the Web UI. 97 98 For details, see the :meth:`link` method. 99 """ 100 pass 101 102 def link(url: str, name: Optional[str]) -> Link: 103 """ 104 Creates a :class:`~api.Link` object that describes a link associated with a resource. 105 106 Args: 107 url (str): the URL to link to 108 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"). 109 """ 110 pass 111 112 def fall_back_on(files: Union[str, List[str]]) -> LiveUpdateStep: 113 """Specify that any changes to the given files will cause Tilt to *fall back* to a 114 full image build (rather than performing a live update). 115 116 ``fall_back_on`` step(s) may only go at the beginning of your list of steps. 117 118 (Files must be a subset of the files that we're already watching for this image; 119 that is, if any files fall outside of DockerBuild.context or CustomBuild.deps, 120 an error will be raised.) 121 122 For more info, see the `Live Update Reference <live_update_reference.html>`_. 123 124 Args: 125 files: 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. 126 """ 127 pass 128 129 130 def set_team(team_id: str) -> None: 131 """Associates this Tiltfile with the `team <teams.html>`_ identified by `team_id`. 132 133 Sends usage information to Tilt Cloud periodically. 134 """ 135 pass 136 137 def sync(local_path: str, remote_path: str) -> LiveUpdateStep: 138 """Specify that any changes to `localPath` should be synced to `remotePath` 139 140 May not follow any `run` steps in a `live_update`. 141 142 For more info, see the `Live Update Reference <live_update_reference.html>`_. 143 144 Args: 145 localPath: A path relative to the Tiltfile's directory. Changes to files matching this path will be synced to `remotePath`. 146 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). 147 remotePath: container path to which changes will be synced. Must be absolute. 148 """ 149 pass 150 151 def run(cmd: Union[str, List[str]], trigger: Union[List[str], str] = [], echo_off: bool = False) -> LiveUpdateStep: 152 """Specify that the given `cmd` should be executed when updating an image's container 153 154 May not precede any `sync` steps in a `live_update`. 155 156 For more info, see the `Live Update Reference <live_update_reference.html>`_. 157 158 Args: 159 cmd: Command to run. If a string, executed with ``sh -c``; if a list, will be passed to the operating system 160 as program name and args. 161 162 trigger: 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.) 163 164 bool: If ``echo_off`` is set to ``True``, the command's output will not be echoed to the Tilt UI. 165 """ 166 pass 167 168 def restart_container() -> LiveUpdateStep: 169 """**For use with Docker Compose resources only.** 170 171 Specify that a container should be restarted when it is live-updated. In 172 practice, this means that the container re-executes its `ENTRYPOINT` within 173 the changed filesystem. 174 175 May only be included in a `live_update` once, and only as the last step. 176 177 For more info (and for the equivalent functionality for Kubernetes resources), 178 see the `Live Update Reference <live_update_reference.html#restarting-your-process>`__. 179 """ 180 pass 181 182 def docker_build(ref: str, 183 context: str, 184 build_args: Dict[str, str] = {}, 185 dockerfile: str = "Dockerfile", 186 dockerfile_contents: Union[str, Blob] = "", 187 live_update: List[LiveUpdateStep]=[], 188 match_in_env_vars: bool = False, 189 ignore: Union[str, List[str]] = [], 190 only: Union[str, List[str]] = [], 191 entrypoint: Union[str, List[str]] = [], 192 target: str = "", 193 ssh: Union[str, List[str]] = "", 194 network: str = "", 195 secret: Union[str, List[str]] = "", 196 extra_tag: Union[str, List[str]] = "", 197 container_args: List[str] = None, 198 cache_from: Union[str, List[str]] = [], 199 pull: bool = False, 200 platform: str = "", 201 extra_hosts: Union[str, List[str]] = []) -> None: 202 """Builds a docker image. 203 204 The invocation 205 206 .. code-block:: python 207 208 docker_build('myregistry/myproj/backend', '/path/to/code') 209 210 is roughly equivalent to the shell call 211 212 .. code-block:: bash 213 214 docker build /path/to/code -t myregistry/myproj/backend 215 216 For more information on the `ignore` and `only` parameters, see our `Guide to File Changes </file_changes.html>`_. 217 218 Note that you can't set both the `dockerfile` and `dockerfile_contents` arguments (will throw an error). 219 220 Note also that the `entrypoint` parameter is not supported for Docker Compose resources. 221 222 When using Docker Compose, Tilt expects the image build to be either managed by your Docker Compose file (via the `build <https://docs.docker.com/compose/compose-file/compose-file-v3/#build>`_ key) OR by Tilt's :meth:`docker_build`, but not both. (Follow this `GitHub issue <https://github.com/tilt-dev/tilt/issues/5196>`_ to be notified of changes to this expectation.) 223 224 Finally, Tilt will put the image in a place where the target runtime can access it. Tilt will make a best effort to detect what kind of runtime you're using (Docker Compose, Kind, GKE, etc), and pick the best strategy for getting the image into it fast. See https://docs.tilt.dev/choosing_clusters.html for more info. 225 226 Args: 227 ref: 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). 228 context: path to use as the Docker build context. 229 build_args: build-time variables that are accessed like regular environment variables in the ``RUN`` instruction of the Dockerfile. See `the Docker Build Arg documentation <https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg>`_. 230 dockerfile: path to the Dockerfile to build. 231 dockerfile_contents: raw contents of the Dockerfile to use for this build. 232 live_update: set of steps for updating a running container (see `Live Update documentation <live_update_reference.html>`_). 233 match_in_env_vars: 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. 234 ignore: set of file patterns that will be ignored, in addition to ``.git`` directory that's `ignored by default <file_changes.html#where-ignores-come-from>`_. Ignored files will not trigger builds and will not be included in images. Follows the `dockerignore syntax <https://docs.docker.com/engine/reference/builder/#dockerignore-file>`_. Patterns will be evaluated relative to the ``context`` parameter. 235 only: 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. 236 entrypoint: 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 <https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/>`_. 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 specified as a list, will be passed to the operating system as program name and args. 237 target: Specify a build stage in the Dockerfile. Equivalent to the ``docker build --target`` flag. 238 ssh: 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 <https://docs.docker.com/develop/develop-images/build_enhancements/#using-ssh-to-access-private-data-in-builds>`_. 239 network: Set the networking mode for RUN instructions. Equivalent to the ``docker build --network`` flag. 240 secret: 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 <https://docs.docker.com/develop/develop-images/build_enhancements/#new-docker-build-secret-information>`_. 241 extra_tag: 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. 242 container_args: args to run when this container starts. Takes precedence over a `container args specified in k8s YAML <https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/>`_. 243 cache_from: Cache image builds from a remote registry. Uses the same syntax as `docker build --cache-from flag <https://docs.docker.com/engine/reference/commandline/build/#specifying-external-cache-sources>`_. 244 pull: Force pull the latest version of parent images. Equivalent to the ``docker build --pull`` flag. 245 platform: Target platform for build (e.g. ``linux/amd64``). Defaults to the value of the ``DOCKER_DEFAULT_PLATFORM`` environment variable. Equivalent to the ``docker build --platform`` flag. 246 extra_hosts: Add a custom host-to-IP mapping (host:ip). Equivalent to the ``docker build --add-host`` flag. 247 """ 248 pass 249 250 def docker_compose(configPaths: Union[str, Blob, List[Union[str, Blob]]], env_file: str = None, project_name: str = "", profiles: Union[str, List[str]] = [], wait = False) -> None: 251 """Run containers with Docker Compose. 252 253 Tilt will read your Docker Compose YAML and separate out the services. 254 We will infer which services defined in your YAML 255 correspond to images defined elsewhere in your ``Tiltfile`` (matching based on 256 the DockerImage ref). 257 258 You can set up Docker Compose with a path to a file, a Blob containing Compose YAML, or a list of paths and/or Blobs. 259 260 Tilt will watch your Docker Compose YAML and reload if it changes. 261 262 For more info, see `the guide to Tilt with Docker Compose <docker_compose.html>`_. 263 264 Examples: 265 266 .. code-block:: python 267 268 # Path to file 269 docker_compose('./docker-compose.yml') 270 271 # List of files 272 docker_compose(['./docker-compose.yml', './docker-compose.override.yml']) 273 274 # Inline compose definition 275 services = {'redis': {'image': 'redis', 'ports': '6379:6379'}} 276 docker_compose(encode_yaml({'services': services})) 277 278 # File with inline override 279 services = {'app': {'environment': {'DEBUG': 'true'}}} 280 docker_compose(['docker-compose.yml', encode_yaml({'services': services})]) 281 282 Args: 283 configPaths: Path(s) and/or Blob(s) to Docker Compose yaml files or content. 284 env_file: Path to env file to use; defaults to ``.env`` in current directory. 285 project_name: The Docker Compose project name. If unspecified, uses either the 286 name of the directory containing the first compose file, or, in the case of 287 inline YAML, the current Tiltfile's directory name. 288 profiles: List of Docker Compose profiles to use. 289 wait: If ``True``, append --wait to docker compose up command. Defaults to ``False``. 290 """ 291 292 293 294 def k8s_yaml(yaml: Union[str, List[str], Blob], allow_duplicates: bool = False) -> None: 295 """Call this with a path to a file that contains YAML, or with a ``Blob`` of YAML. 296 297 We will infer what (if any) of the k8s resources defined in your YAML 298 correspond to Images defined elsewhere in your ``Tiltfile`` (matching based on 299 the DockerImage ref and on pod selectors). Any remaining YAML is YAML that Tilt 300 applies to your k8s cluster independently. 301 302 Any YAML files are watched (See ``watch_file``). 303 304 Examples: 305 306 .. code-block:: python 307 308 # path to file 309 k8s_yaml('foo.yaml') 310 311 # list of paths 312 k8s_yaml(['foo.yaml', 'bar.yaml']) 313 314 # Blob, i.e. `local` output (in this case, script output) 315 templated_yaml = local('./template_yaml.sh') 316 k8s_yaml(templated_yaml) 317 318 Args: 319 yaml: Path(s) to YAML, or YAML as a ``Blob``. 320 allow_duplicates: If you try to register the same Kubernetes 321 resource twice, this function will assume this is a mistake and emit an error. 322 Set allow_duplicates=True to allow duplicates. There are some Helm charts 323 that have duplicate resources for esoteric reasons. 324 """ 325 pass 326 327 328 def k8s_custom_deploy(name: str, 329 apply_cmd: Union[str, List[str]], 330 delete_cmd: Union[str, List[str]], 331 deps: Union[str, List[str]], 332 image_selector: str="", 333 live_update: List[LiveUpdateStep]=[], 334 apply_dir: str="", 335 apply_env: Dict[str, str]={}, 336 apply_cmd_bat: Union[str, List[str]]="", 337 delete_dir: str="", 338 delete_env: Dict[str, str]={}, 339 delete_cmd_bat: Union[str, List[str]]="", 340 container_selector: str="", 341 image_deps: List[str]=[]) -> None: 342 """Deploy resources to Kubernetes using a custom command. 343 344 For deployment tools that cannot output templated YAML for use with :meth:`k8s_yaml` 345 or need to perform additional work as part of deployment, ``k8s_custom_deploy`` 346 enables integration with Tilt. 347 348 The ``apply_cmd`` will be run whenever a path from ``deps`` changes and should 349 output the YAML of the objects it applied to the Kubernetes cluster to stdout. 350 Tilt will track workload status and stream pod logs based on this result. 351 352 The ``delete_cmd`` is run on ``tilt down`` so that the tool can clean up any 353 objects it created in the cluster as well as any state of its own. 354 355 Both ``apply_cmd`` and ``delete_cmd`` MUST be idempotent. For example, it's 356 possible that some objects might already exist when the ``apply_cmd`` is 357 invoked, and objects might have already been deleted before ``delete_cmd`` 358 is invoked. The ``apply_cmd`` should have similar semantics to ``kubectl apply`` 359 and the ``delete_cmd`` should behave similar to ``kubectl delete --ignore-not-found``. 360 361 Port forwards and other behavior can be configured using :meth:`k8s_resource` 362 using the ``name`` as specified here. 363 364 If ``live_update`` rules are specified, exactly one of ``image_selector`` or 365 ``container_selector`` must be specified to determine which container(s) are 366 eligible for in-place updates. ``image_selector`` will match containers based 367 on an image reference, while ``container_selector`` will match a single container 368 by name. 369 370 Args: 371 name: resource name to use in Tilt UI and for further customization via :meth:`k8s_resource` 372 apply_cmd: command that deploys objects to the Kubernetes cluster. If a string, executed with ``sh -c`` 373 on macOS/Linux, or ``cmd /S /C`` on Windows; if a list, will be passed to the operating system as program name and args. 374 delete_cmd: command that deletes objects in the Kubernetes cluster. If a string, executed with ``sh -c`` 375 on macOS/Linux, or ``cmd /S /C`` on Windows; if a list, will be passed to the operating system as program name and args. 376 deps: paths to watch and trigger a re-apply on change 377 image_selector: image reference to determine containers eligible for Live Update 378 live_update: set of steps for updating a running container (see `Live Update documentation <live_update_reference.html>`_). 379 apply_dir: working directory for ``apply_cmd`` 380 apply_env: environment variables for ``apply_cmd`` 381 apply_cmd_bat: If non-empty and on Windows, takes precedence over ``apply_cmd``. Ignored on other platforms. 382 If a string, executed as a Windows batch command executed with ``cmd /S /C``; if a list, will be passed to 383 the operating system as program name and args. 384 delete_dir: working directory for ``delete_cmd`` 385 delete_env: environment variables for ``delete_cmd`` 386 delete_cmd_bat: If non-empty and on Windows, takes precedence over ``delete_cmd``. Ignored on other platforms. 387 If a string, executed as a Windows batch command executed with ``cmd /S /C``; if a list, will be passed to 388 the operating system as program name and args. 389 container_selector: container name to determine container for Live Update 390 image_deps: a list of image builds that this deploy depends on. 391 The tagged image names will be injected into the environment of the 392 the apply command in the form: 393 394 `TILT_IMAGE_i` - The reference to the image #i (0-based) from the point of view of the cluster container runtime. 395 396 `TILT_IMAGE_MAP_i` - The name of the image map #i (0-based) with the current status of the image. 397 """ 398 pass 399 400 401 class TriggerMode: 402 """A set of constants that describe how Tilt triggers an update for a resource. 403 Possible values are: 404 405 - ``TRIGGER_MODE_AUTO``: the default. When Tilt detects a change to files or config files associated with this resource, it triggers an update. 406 407 - ``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.) 408 409 The default trigger mode for all manifests may be set with the top-level function :meth:`trigger_mode` 410 (if not set, defaults to ``TRIGGER_MODE_AUTO``), and per-resource with :meth:`k8s_resource` / :meth:`dc_resource`. 411 412 See also: `Manual Update Control documentation <manual_update_control.html>`_ 413 """ 414 def __init__(self): 415 pass 416 417 def trigger_mode(trigger_mode: TriggerMode): 418 """Sets the default :class:`TriggerMode` for resources in this Tiltfile. 419 (Trigger mode may still be adjusted per-resource with :meth:`k8s_resource`.) 420 421 If this function is not invoked, the default trigger mode for all resources is ``TRIGGER MODE AUTO``. 422 423 See also: `Manual Update Control documentation <manual_update_control.html>`_ 424 425 Args: 426 trigger_mode: may be one of ``TRIGGER_MODE_AUTO`` or ``TRIGGER_MODE_MANUAL`` 427 428 """ 429 430 # Hack so this appears correctly in the function signature: https://stackoverflow.com/a/50193319/4628866 431 TRIGGER_MODE_AUTO = type('_sentinel', (TriggerMode,), 432 {'__repr__': lambda self: 'TRIGGER_MODE_AUTO'})() 433 434 def dc_resource(name: str, 435 trigger_mode: TriggerMode = TRIGGER_MODE_AUTO, 436 resource_deps: List[str] = [], 437 links: Union[str, Link, List[Union[str, Link]]] = [], 438 labels: Union[str, List[str]] = [], 439 auto_init: bool = True, 440 project_name: str = "", 441 new_name: str = "", 442 infer_links: bool = True) -> None: 443 """Configures the Docker Compose resource of the given name. Note: Tilt does an amount of resource configuration 444 for you(for more info, see `Tiltfile Concepts: Resources <tiltfile_concepts.html#resources>`_); you only need 445 to invoke this function if you want to configure your resource beyond what Tilt does automatically. 446 447 Args: 448 name: The name of the resource in the docker-compose yaml. 449 trigger_mode: one of ``TRIGGER_MODE_AUTO`` or ``TRIGGER_MODE_MANUAL``. For more info, see the 450 `Manual Update Control docs <manual_update_control.html>`_. 451 resource_deps: a list of resources on which this resource depends. 452 See the `Resource Dependencies docs <resource_dependencies.html>`_. 453 links: one or more links to be associated with this resource in the UI. For more info, see 454 `Accessing Resource Endpoints <accessing_resource_endpoints.html#arbitrary-links>`_. 455 labels: used to group resources in the Web UI, (e.g. you want all frontend services displayed together, while test and backend services are displayed separately). A label must start and end with an alphanumeric character, can include ``_``, ``-``, and ``.``, and must be 63 characters or less. For an example, see `Resource Grouping <tiltfile_concepts.html#resource-groups>`_. 456 auto_init: whether this resource runs on ``tilt up``. Defaults to ``True``. For more info, see the 457 `Manual Update Control docs <manual_update_control.html>`_. 458 project_name: The Docker Compose project name to match the corresponding project loaded by 459 ``docker_compose``, if necessary for disambiguation. 460 new_name: If non-empty, will be used as the new name for this resource. 461 infer_links: whether to include the default localhost links. Defaults to ``True``. If ``False``, only links explicitly provided via the links argument will be displayed. 462 """ 463 464 pass 465 466 def k8s_resource(workload: str = "", new_name: str = "", 467 port_forwards: Union[str, int, PortForward, List[Union[str, int, PortForward]]] = [], 468 extra_pod_selectors: Union[Dict[str, str], List[Dict[str, str]]] = [], 469 trigger_mode: TriggerMode = TRIGGER_MODE_AUTO, 470 resource_deps: List[str] = [], objects: List[str] = [], 471 auto_init: bool = True, 472 pod_readiness: str = "", 473 links: Union[str, Link, List[Union[str, Link]]]=[], 474 labels: Union[str, List[str]] = [], 475 discovery_strategy: str = "") -> None: 476 """ 477 478 Configures or creates the specified Kubernetes resource. 479 480 A "resource" is a bundle of work managed by Tilt: a Kubernetes resource consists 481 of one or more Kubernetes objects to deploy, and zero or more image build directives 482 for the images referenced therein. 483 484 Tilt assembles Kubernetes resources automatically, as described in 485 `Tiltfile Concepts: Resources <tiltfile_concepts.html#resources>`_. You may call 486 ``k8s_resource`` to configure an automatically created Kubernetes resource, or to 487 create and configure a new one: 488 489 - If configuring an automatically created resource: the ``workload`` parameter must be specified. 490 - If creating a new resource: both the ``objects`` and ``new_name`` parameters must be specified. 491 492 Calling ``k8s_resource`` is *optional*; you can use this function to configure port forwarding for 493 your resource, to rename it, or to adjust any of the other settings specified below, but in many cases, 494 Tilt's default behavior is sufficient. 495 496 Examples: 497 498 .. code-block:: python 499 500 # load Deployment foo 501 k8s_yaml('foo.yaml') 502 503 # modify the resource called "foo" (auto-assembled by Tilt) 504 # to forward container port 8080 to localhost:8080 505 k8s_resource(workload='foo', port_forwards=8080) 506 507 .. code-block:: python 508 509 # load CRD "bar", Service "bar", and Secret "bar-password" 510 k8s_yaml('bar.yaml') 511 512 # create a new resource called "bar" which contains the objects 513 # loaded above (none of which are workloads, so none of which 514 # would be automatically assigned to a resource). Note that the 515 # first two object selectors specify both 'name' and 'kind', 516 # since just the string "bar" does not uniquely specify a single object. 517 # As the object name "bar-password" is unique, "bar-password" suffices as 518 # an object selector (though a more more qualified object selector 519 # like "bar-password:secret" or "bar-password:secret:default" would 520 # be accepted as well). 521 k8s_resource( 522 objects=['bar:crd', 'bar:service', 'bar-password'], 523 new_name='bar' 524 ) 525 526 For more examples, see `Tiltfile Concepts: Resources <tiltfile_concepts.html#resources>`_. 527 528 Args: 529 workload: The name of an existing auto-assembled resource to configure 530 (Tilt generates resource names when it `assembles resources by workload <tiltfile_concepts.html#resources>`_). 531 (If you instead want to create/configure a _new_ resource, use the ``objects`` parameter 532 in conjunction with ``new_name``.) 533 new_name: If non-empty, will be used as the new name for this resource. (To 534 programmatically rename all resources, see :meth:`workload_to_resource_function`.) 535 port_forwards: Host port to connect to the pod. Takes 3 forms: 536 537 ``'9000'`` (port only) - Connect localhost:9000 to the container's port 9000, 538 if it is exposed. Otherwise connect to the container's default port. 539 540 ``'9000:8000'`` (host port to container port) - Connect localhost:9000 to the container port 8000). 541 542 ``'elastic.local:9200:8000'`` (host address to container port) - Bind elasticsearch:9200 on the host 543 to container port 8000. You will also need to update /etc/host to make 'elastic.local' point to localhost. 544 545 Multiple port forwards can be specified (e.g., ``['9000:8000', '9001:8001']``). 546 The string-based syntax is sugar over the more explicit ``port_forward(9000, 8000)``. 547 extra_pod_selectors: In addition to relying on Tilt's heuristics to automatically 548 find Kubernetes resources associated with this resource, a user may specify extra 549 labelsets to force pods to be associated with this resource. An pod 550 will be associated with this resource if it has all of the labels in at 551 least one of the entries specified (but still also if it meets any of 552 Tilt's usual mechanisms). 553 trigger_mode: One of ``TRIGGER_MODE_AUTO`` or ``TRIGGER_MODE_MANUAL``. For more info, see the 554 `Manual Update Control docs <manual_update_control.html>`_. 555 resource_deps: A list of resources on which this resource depends. 556 See the `Resource Dependencies docs <resource_dependencies.html>`_. 557 objects: A list of Kubernetes objects to be added to this resource, specified via 558 Tilt's `Kubernetes Object Selector <tiltfile_concepts.html#kubernetes-object-selectors>`_ 559 syntax. If the ``workload`` parameter is specified, these objects will be 560 added to the existing resource; otherwise, these objects will form a new 561 resource with name ``new_name``. If an object selector matches more than 562 one Kubernetes object, or matches an object already associated with a 563 resource, ``k8s_resource`` raises an error. 564 auto_init: whether this resource runs on ``tilt up``. Defaults to ``True``. For more info, see the 565 `Manual Update Control docs <manual_update_control.html>`_. 566 pod_readiness: Possible values: 'ignore', 'wait'. Controls whether Tilt waits for 567 pods to be ready before the resource is considered healthy (and dependencies 568 can start building). By default, Tilt will wait for pods to be ready if it 569 thinks a resource has pods. 570 links: one or more links to be associated with this resource in the UI. For more info, see 571 `Accessing Resource Endpoints <accessing_resource_endpoints.html#arbitrary-links>`_. 572 labels: used to group resources in the Web UI, (e.g. you want all frontend services displayed together, while test and backend services are displayed separately). A label must start and end with an alphanumeric character, can include ``_``, ``-``, and ``.``, and must be 63 characters or less. For an example, see `Resource Grouping <tiltfile_concepts.html#resource-groups>`_. 573 discovery_strategy: Possible values: '', 'default', 'selectors-only'. When '' or 'default', Tilt both uses `extra_pod_selectors` and traces k8s owner references to identify this resource's pods. When 'selectors-only', Tilt uses only `extra_pod_selectors`. 574 """ 575 pass 576 577 def filter_yaml(yaml: Union[str, List[str], Blob], labels: dict=None, name: str=None, namespace: str=None, kind: str=None, api_version: str=None): 578 """Call this with a path to a file that contains YAML, or with a ``Blob`` of YAML. 579 (E.g. it can be called on the output of ``kustomize`` or ``helm``.) 580 581 Captures the YAML entities that meet the filter criteria and returns them as a blob; 582 returns the non-matching YAML as the second return value. 583 584 For example, if you have a file of *all* your YAML, but only want to pass a few elements to Tilt: :: 585 586 # extract all YAMLs matching labels "app=foobar" 587 foobar_yaml, rest = filter_yaml('all.yaml', labels={'app': 'foobar'}) 588 k8s_yaml(foobar_yaml) 589 590 # extract YAMLs of kind "deployment" with metadata.name regex-matching "baz", also matching "bazzoo" and "bar-baz" 591 baz_yaml, rest = filter_yaml(rest, name='baz', kind='deployment') 592 k8s_yaml(baz_yaml) 593 594 # extract YAMLs of kind "deployment" exactly matching metadata.name "foo" 595 foo_yaml, rest = filter_yaml(rest, name='^foo$', kind='deployment') 596 k8s_yaml(foo_yaml) 597 598 Args: 599 yaml: Path(s) to YAML, or YAML as a ``Blob``. 600 labels: return only entities matching these labels. (Matching entities 601 must satisfy all of the specified label constraints, though they may have additional 602 labels as well: see the `Kubernetes docs <https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/>`_ 603 for more info.) 604 name: Case-insensitive regexp specifying the ``metadata.name`` property of entities to match 605 namespace: Case-insensitive regexp specifying the ``metadata.namespace`` property of entities to match 606 kind: Case-insensitive regexp specifying the kind of entities to match (e.g. "Service", "Deployment", etc.). 607 api_version: Case-insensitive regexp specifying the apiVersion for `kind`, (e.g., "apps/v1") 608 609 Returns: 610 2-element tuple containing 611 612 - **matching** (:class:`~api.Blob`): blob of YAML entities matching given filters 613 - **rest** (:class:`~api.Blob`): the rest of the YAML entities 614 """ 615 pass 616 617 def include(path: str): 618 """Execute another Tiltfile. 619 620 Discouraged. Please use :meth:`load` or :meth:`load_dynamic`. 621 622 Example :: 623 624 include('./frontend/Tiltfile') 625 include('./backend/Tiltfile') 626 """ 627 628 def load(path: str, *args): 629 """Execute another Tiltfile, and import the named variables into the current scope. 630 631 Used when you want to define common functions or constants 632 to share across Tiltfiles. 633 634 Example :: 635 636 load('./lib/Tiltfile', 'create_namespace') 637 create_namespace('frontend') 638 639 A Tiltfile may only be executed once. If a Tiltfile is loaded multiple times, 640 the second load will use the results of the last execution. 641 642 If ``path`` starts with ``"ext://"`` the path will be treated as a `Tilt Extension <extensions.html>`_. 643 644 Example :: 645 646 load('ext://hello_world', 'hi') # Resolves to https://github.com/tilt-dev/tilt-extensions/blob/master/hello_world/Tiltfile 647 hi() # prints "Hello world!" 648 649 Note that ``load()`` is a language built-in. Read the 650 `specification <https://github.com/google/starlark-go/blob/master/doc/spec.md#load-statements>`_ 651 for its complete syntax. 652 653 Because ``load()`` is analyzed at compile-time, the first argument MUST be a string literal. 654 """ 655 656 def load_dynamic(path: str) -> Dict[str, Any]: 657 """Execute another Tiltfile, and return a dict of the global variables it creates. 658 659 Used when you want to define common functions or constants 660 to share across Tiltfiles. 661 662 Example :: 663 664 symbols = load_dynamic('./lib/Tiltfile') 665 create_namespace = symbols['create_namespace'] 666 create_namespace('frontend') 667 668 Like :meth:`load`, each Tiltfile will only be executed once. Can also be used to load a `Tilt Extension <extensions.html>`_. 669 670 Because ``load_dynamic()`` is executed at run-time, you can use it to do 671 meta-programming that you cannot do with ``load()`` (like determine which file 672 to load by running a script first). But you need to unpack the variables yourself - 673 you don't get the nice syntactic sugar of binding local variables. 674 """ 675 676 def local(command: Union[str, List[str]], 677 quiet: bool = False, 678 command_bat: Union[str, List[str]] = "", 679 echo_off: bool = False, 680 env: Dict[str, str] = {}, 681 dir: str = "", 682 stdin: Union[str, Blob, None] = None) -> Blob: 683 """Runs a command on the *host* machine, waits for it to finish, and returns its stdout as a ``Blob`` 684 685 Args: 686 command: Command to run. If a string, executed with ``sh -c`` on macOS/Linux, or ``cmd /S /C`` on Windows; 687 if a list, will be passed to the operating system as program name and args. 688 quiet: If set to True, skips printing output to log. 689 command_bat: If non-empty and on Windows, takes precedence over ``command``. Ignored on other platforms. 690 If a string, executed as a Windows batch command executed with ``cmd /S /C``; if a list, will be passed to 691 the operating system as program name and args. 692 echo_off: If set to True, skips printing command to log. 693 env: Environment variables to pass to the executed ``command``. Values specified here will override any variables passed to the Tilt parent process. 694 dir: Working directory for ``command``. Defaults to the Tiltfile's location. 695 stdin: If not ``None``, will be written to ``command``'s stdin. 696 """ 697 pass 698 699 def read_file(file_path: str, default: str = None) -> Blob: 700 """ 701 Reads file and returns its contents. 702 703 If the `file_path` does not exist and `default` is not `None`, `default` will be returned. 704 In any other case, an error reading `file_path` will be a Tiltfile load error. 705 706 Args: 707 file_path: Path to the file locally (absolute, or relative to the location of the Tiltfile). 708 default: If not `None` and the file at `file_path` does not exist, this value will be returned.""" 709 pass 710 711 def watch_file(file_path: str) -> None: 712 """Watches a file. If the file is changed a re-execution of the Tiltfile is triggered. 713 714 If the path is a directory, its contents will be recursively watched. 715 716 Args: 717 file_path: Path to the file locally (absolute, or relative to the location of the Tiltfile).""" 718 719 720 def kustomize(pathToDir: str, kustomize_bin: str = None, flags: List[str] = []) -> Blob: 721 """Run `kustomize <https://github.com/kubernetes-sigs/kustomize>`_ on a given directory and return the resulting YAML as a Blob 722 Directory is watched (see ``watch_file``). Checks for and uses separately installed kustomize first, if it exists. Otherwise, 723 uses kubectl's kustomize. See `blog post <https://blog.tilt.dev/2020/02/04/are-you-my-kustomize.html>`_. 724 725 Args: 726 pathToDir: Path to the directory locally (absolute, or relative to the location of the Tiltfile). 727 kustomize_bin: Custom path to the ``kustomize`` binary executable. Defaults to searching $PATH for kustomize. 728 flags: Additional flags to pass to ``kustomize build`` 729 """ 730 pass 731 732 def helm(pathToChartDir: str, name: str = "", namespace: str = "", values: Union[str, List[str]]=[], set: Union[str, List[str]]=[], kube_version: str = "", skip_crds: bool = False) -> Blob: 733 """Run `helm template <https://docs.helm.sh/helm/#helm-template>`_ on a given directory that contains a chart and return the fully rendered YAML as a Blob 734 Chart directory is watched (See ``watch_file``). 735 736 For more examples, see the `Helm Cookbook <helm.html>`_. 737 738 Args: 739 pathToChartDir: Path to the directory locally (absolute, or relative to the location of the Tiltfile). 740 name: The release name. Equivalent to the helm `--name` flag 741 namespace: The namespace to deploy the chart to. Equivalent to the helm `--namespace` flag 742 values: 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 <https://helm.sh/docs/chart_template_guide/#values-files>`_). 743 set: Specify one or more values. Equivalent to the Helm ``--set`` flag. 744 kube_version: Specify for which kubernetes version template will be generated. Equivalent to the Helm ``--kube-version`` flag. 745 skip_crds: If set, no CRDs will be installed. By default, CRDs are installed. 746 """ 747 pass 748 749 def blob(contents: str) -> Blob: 750 """Creates a Blob object that wraps the provided string. Useful for passing strings in to functions that expect a `Blob`, e.g. ``k8s_yaml``.""" 751 pass 752 753 def listdir(directory: str, recursive: bool = False) -> List[str]: 754 """Returns all the files of the provided directory. 755 756 If ``recursive`` is set to ``True``, the directory's contents will be recursively watched, and a change to any file will trigger a re-execution of the Tiltfile. 757 758 This function returns absolute paths. Subdirectory names are not returned. 759 760 Args: 761 directory: Path to the directory locally (absolute, or relative to the location of the Tiltfile). 762 recursive: Walk the given directory tree recursively and return all files in it; additionally, recursively watch for changes in the directory tree. 763 """ 764 pass 765 766 def k8s_kind(kind: str, api_version: str=None, *, image_json_path: Union[str, List[str]]=[], image_object_json_path: Dict=None, pod_readiness: str=""): 767 """Tells Tilt about a k8s kind. 768 769 For CRDs that use images built by Tilt: call this with `image_json_path` or 770 `image_object` to tell Tilt where in the CRD's spec the image is specified. 771 772 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 :meth:`k8s_resource` with `extra_pod_selectors` to specify which pods Tilt should associate with this resource. 773 774 (Note the `*` in the signature means `image_json_path` must be passed as a keyword, e.g., `image_json_path="{.spec.image}"`) 775 776 Example :: 777 778 # Fission has a CRD named "Environment" 779 k8s_yaml('deploy/fission.yaml') 780 k8s_kind('Environment', image_json_path='{.spec.runtime.image}') 781 782 Here's an example that specifies the image location in `a UselessMachine 783 Custom Resource 784 <https://github.com/tilt-dev/tilt/blob/master/integration/crd/Tiltfile#L8>`_. 785 786 Args: 787 kind: Case-insensitive regexp specifying he value of the `kind` field in the k8s object definition (e.g., `"Deployment"`) 788 api_version: Case-insensitive regexp specifying the apiVersion for `kind`, (e.g., "apps/v1") 789 image_json_path: Either a string or a list of string containing json path(s) within that kind's definition 790 specifying images deployed with k8s objects of that type. 791 This uses the k8s json path template syntax, described `here <https://kubernetes.io/docs/reference/kubectl/jsonpath/>`_. 792 image_object: A specifier of the form `image_object={'json_path': '{.path.to.field}', 'repo_field': 'repo', 'tag_field': 'tag'}`. 793 Used to tell Tilt how to inject images into Custom Resources that express the image repo and tag as separate fields. 794 pod_readiness: Possible values: 'ignore', 'wait'. Controls whether Tilt waits for 795 pods to be ready before the resource is considered healthy (and dependencies 796 can start building). By default, Tilt will wait for pods to be ready if it 797 thinks a resource has pods. This can be overridden on a resource-by-resource basis 798 by the `k8s_resource` function. 799 800 """ 801 pass 802 803 StructuredDataType = Union[ 804 Dict[str, Any], 805 List[Any], 806 ] 807 808 def decode_json(json: Union[str, Blob]) -> StructuredDataType: 809 """ 810 Deserializes the given JSON into a starlark object 811 812 Args: 813 json: the JSON to deserialize 814 """ 815 pass 816 817 def encode_json(obj: StructuredDataType) -> Blob: 818 """ 819 Serializes the given starlark object into JSON. 820 821 Only supports maps with string keys, lists, strings, ints, and bools. 822 823 Args: 824 obj: the object to serialize 825 """ 826 pass 827 828 def read_json(path: str, default: str = None) -> StructuredDataType: 829 """ 830 Reads the file at `path` and deserializes its contents as JSON 831 832 If the `path` does not exist and `default` is not `None`, `default` will be returned. 833 In any other case, an error reading `path` will be a Tiltfile load error. 834 835 Args: 836 path: Path to the file locally (absolute, or relative to the location of the Tiltfile). 837 default: If not `None` and the file at `path` does not exist, this value will be returned.""" 838 pass 839 840 def read_yaml(path: str, default: StructuredDataType = None) -> StructuredDataType: 841 """ 842 Reads the file at `path` and deserializes its contents into a starlark object 843 844 If the `path` does not exist and `default` is not `None`, `default` will be returned. 845 In any other case, an error reading `path` will be a Tiltfile load error. 846 847 Args: 848 path: Path to the file locally (absolute, or relative to the location of the Tiltfile). 849 default: If not `None` and the file at `path` does not exist, this value will be returned.""" 850 pass 851 852 def read_yaml_stream(path: str, default: List[StructuredDataType] = None) -> List[StructuredDataType]: 853 """ 854 Reads a yaml stream (i.e., yaml documents separated by ``"\\n---\\n"``) from the 855 file at `path` and deserializes its contents into a starlark object 856 857 If the `path` does not exist and `default` is not `None`, `default` will be returned. 858 In any other case, an error reading `path` will be a Tiltfile load error. 859 860 Args: 861 path: Path to the file locally (absolute, or relative to the location of the Tiltfile). 862 default: If not `None` and the file at `path` does not exist, this value will be returned.""" 863 pass 864 865 def decode_yaml(yaml: Union[str, Blob]) -> StructuredDataType: 866 """ 867 Deserializes the given yaml document into a starlark object 868 869 Args: 870 yaml: the yaml to deserialize 871 """ 872 pass 873 874 def decode_yaml_stream(yaml: Union[str, Blob]) -> List[StructuredDataType]: 875 """ 876 Deserializes the given yaml stream (i.e., any number of yaml 877 documents, separated by ``"\\n---\\n"``) into a list of starlark objects. 878 879 Args: 880 yaml: the yaml to deserialize 881 """ 882 pass 883 884 def encode_yaml(obj: StructuredDataType) -> Blob: 885 """ 886 Serializes the given starlark object into YAML. 887 888 Only supports maps with string keys, lists, strings, ints, and bools. 889 890 Args: 891 obj: the object to serialize 892 """ 893 pass 894 895 def encode_yaml_stream(objs: List[StructuredDataType]) -> Blob: 896 """ 897 Serializes the given starlark objects into a YAML stream (i.e., 898 multiple YAML documents, separated by ``"\\n---\\n"``). 899 900 Only supports maps with string keys, lists, strings, ints, and bools. 901 902 Args: 903 objs: the object to serialize 904 """ 905 pass 906 907 def default_registry(host: str, host_from_cluster: str = None, single_name: str = "") -> None: 908 """Specifies that any images that Tilt builds should be renamed so that they have the specified Docker registry. 909 910 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`` 911 912 For more info, see our `Using a Personal Registry Guide <personal_registry.html>`_. 913 914 Args: 915 host: host of the registry that all built images should be renamed to use. 916 host_from_cluster: 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 <personal_registry.html#different-urls-from-inside-your-cluster>`_. 917 single_name: In ECR, each repository in a registry needs to be created up-front. single_name lets you 918 set a single repository to push to (e.g., a personal dev repository), and embeds the image name in the 919 tag instead. 920 921 Images are renamed following these rules: 922 923 1. Replace ``/`` and ``@`` with ``_``. 924 925 2. Prepend the value of ``host`` and a ``/``. 926 927 e.g., with ``default_registry('gcr.io/myorg')``, an image called ``user-service`` becomes ``gcr.io/myorg/user-service``. 928 """ 929 pass 930 931 def custom_build( 932 ref: str, 933 command: Union[str, List[str]], 934 deps: List[str], 935 tag: str = "", 936 disable_push: bool = False, 937 skips_local_docker: bool = False, 938 live_update: List[LiveUpdateStep]=[], 939 match_in_env_vars: bool = False, 940 ignore: Union[str, List[str]] = [], 941 entrypoint: Union[str, List[str]] = [], 942 command_bat_val: str = "", 943 outputs_image_ref_to: str = "", 944 command_bat: Union[str, List[str]] = "", 945 image_deps: List[str] = [], 946 env: Dict[str, str] = {}, 947 dir: str = ""): 948 """Provide a custom command that will build an image. 949 950 Example :: 951 952 custom_build( 953 'gcr.io/my-project/frontend-server', 954 'docker build -t $EXPECTED_REF .', 955 ['.'], 956 ) 957 958 Please read the `Custom Image Builders Guide <custom_build.html>`_ on how to 959 use this function. 960 961 All custom build scripts build an image and put it somewhere. But there are 962 several different patterns for where they put the image, how they compute a 963 digest of the contents, and how they push the image to the 964 cluster. ``custom_build`` has many options to support different combinations 965 of each mode. The guide has some examples of common combinations. 966 967 Args: 968 ref: 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). 969 command: a command that, when run in the shell, builds an image puts it in the registry as ``ref``. In the 970 default mode, must produce an image named ``$EXPECTED_REF``. If a string, executed with ``sh -c`` on macOS/Linux, 971 or ``cmd /S /C`` on Windows; if a list, will be passed to the operating system as program name and args. 972 deps: 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. 973 tag: Some tools can't change the image tag at runtime. They need a pre-specified tag. Tilt will set ``$EXPECTED_REF = image_name:tag``, 974 then re-tag it with its own tag before pushing to your cluster. 975 disable_push: 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. 976 skips_local_docker: 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``. 977 live_update: set of steps for updating a running container (see `Live Update documentation <live_update_reference.html>`_). 978 match_in_env_vars: 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. 979 ignore: 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 <https://docs.docker.com/engine/reference/builder/#dockerignore-file>`_. 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``). 980 entrypoint: 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 <https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/>`_. 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 specified as a list, will be passed to the operating system as program name and args. Kubernetes-only. 981 command_bat_val: Deprecated, use command_bat. 982 outputs_image_ref_to: Specifies a file path. When set, the custom build command must write a content-based 983 tagged image ref to this file. Tilt will read that file after the cmd runs to get the image ref, 984 and inject that image ref into the YAML. For more on content-based tags, see `why tilt uses immutable tags <custom_build.html#why-tilt-uses-immutable-tags>`_ 985 command_bat: If non-empty and on Windows, takes precedence over ``command``. Ignored on other platforms. 986 If a string, executed as a Windows batch command executed with ``cmd /S /C``; if a list, will be passed to 987 the operating system as program name and args. 988 image_deps: a list of image builds that this deploy depends on. 989 The tagged image names will be injected into the environment of the 990 the custom build command in the form: 991 992 `TILT_IMAGE_i` - The reference to the image #i (0-based) from the point of view of the local host. 993 994 `TILT_IMAGE_MAP_i` - The name of the image map #i (0-based) with the current status of the image. 995 env: Environment variables to pass to the executed ``command``. Values specified here will override any variables passed to the Tilt parent process. 996 dir: Working directory of the executed ``command``. Defaults to the Tiltfile directory. 997 """ 998 pass 999 1000 1001 class K8sObjectID: 1002 """ 1003 Attributes: 1004 name (str): The object's name (e.g., `"my-service"`) 1005 kind (str): The object's kind (e.g., `"deployment"`) 1006 namespace (str): The object's namespace (e.g., `"default"`) 1007 group (str): The object's group (e.g., `"apps"`) 1008 """ 1009 pass 1010 1011 1012 def workload_to_resource_function(fn: Callable[[K8sObjectID], str]) -> None: 1013 """ 1014 Provide a function that will be used to name `Tilt resources <tiltfile_concepts.html#resources>`_. 1015 1016 Tilt will auto-generate resource names for you. If you do not like the names 1017 it generates, you can use this to customize how Tilt generates names. 1018 1019 Example :: 1020 1021 # name all tilt resources after the k8s object namespace + name 1022 def resource_name(id): 1023 return id.namespace + '-' + id.name 1024 workload_to_resource_function(resource_name) 1025 1026 The names it generates must be unique (i.e., two workloads can't map to the 1027 same resource name). 1028 1029 Args: 1030 fn: A function that takes a :class:`K8sObjectID` and returns a `str`. 1031 Tilt will call this function once for each workload to determine that workload's resource's name. 1032 """ 1033 1034 pass 1035 1036 def k8s_context() -> str: 1037 """Returns the name of the Kubernetes context Tilt is connecting to. 1038 1039 Example :: 1040 1041 if k8s_context() == 'prod': 1042 fail("failing early to avoid overwriting prod") 1043 """ 1044 pass 1045 1046 def k8s_namespace() -> str: 1047 """Returns the name of the Kubernetes namespace Tilt is connecting to. 1048 1049 Example :: 1050 1051 if k8s_namespace() == 'default': 1052 fail("failing early to avoid deploying to 'default' namespace") 1053 """ 1054 pass 1055 1056 def allow_k8s_contexts(contexts: Union[str, List[str]]) -> None: 1057 """Specifies that Tilt is allowed to run against the specified k8s context names. 1058 1059 To help reduce the chances you accidentally use Tilt to deploy to your 1060 production cluster, Tilt will only push to clusters that have been allowed 1061 for local development. 1062 1063 By default, Tilt automatically allows Minikube, Docker for Desktop, Microk8s, 1064 Red Hat CodeReady Containers, Kind, K3D, and Krucible. 1065 1066 To add your development cluster to the allow list, add a line in your Tiltfile:: 1067 1068 allow_k8s_contexts('context-name') 1069 1070 where 'context-name' is the name returned by `kubectl config current-context`. 1071 1072 If your team connects to many remote dev clusters, a common approach is to 1073 disable the check entirely and add your own validation:: 1074 1075 allow_k8s_contexts(k8s_context()) 1076 local('./validate-dev-cluster.sh') 1077 1078 For more on which cluster context is right for you, see `Choosing a Local Dev Cluster <choosing_clusters.html>`_. 1079 1080 Args: 1081 contexts: a string or list of strings, specifying one or more k8s context 1082 names that Tilt is allowed to run in. This list is in addition to 1083 the default of all known-local clusters. 1084 1085 Example :: 1086 1087 allow_k8s_contexts('my-staging-cluster') 1088 1089 allow_k8s_contexts([ 1090 'my-staging-cluster', 1091 'gke_my-project-name_my-dev-cluster-name' 1092 ]) 1093 1094 allow_k8s_contexts(k8s_context()) # disable check 1095 1096 """ 1097 pass 1098 1099 def enable_feature(feature_name: str) -> None: 1100 """Configures Tilt to enable non-default features (e.g., experimental or deprecated). 1101 1102 The Tilt features controlled by this are generally in an unfinished state, and 1103 not yet documented. 1104 1105 As a Tiltfile author, you don't need to worry about this function unless something 1106 else directs you to (e.g., an experimental feature doc, or a conversation with a 1107 Tilt contributor). 1108 1109 As a Tiltfile reader, you can probably ignore this, or you can ask the person 1110 who added it to the Tiltfile what it's doing there. 1111 1112 Args: 1113 feature_name: name of the feature to enable 1114 """ 1115 pass 1116 1117 def local_resource(name: str, 1118 cmd: Union[str, List[str]], 1119 deps: Union[str, List[str]] = None, 1120 trigger_mode: TriggerMode = TRIGGER_MODE_AUTO, 1121 resource_deps: List[str] = [], 1122 ignore: Union[str, List[str]] = [], 1123 auto_init: bool=True, 1124 serve_cmd: Union[str, List[str]] = "", 1125 cmd_bat: Union[str, List[str]] = "", 1126 serve_cmd_bat: Union[str, List[str]] = "", 1127 allow_parallel: bool=False, 1128 links: Union[str, Link, List[Union[str, Link]]]=[], 1129 tags: List[str] = [], 1130 env: Dict[str, str] = {}, 1131 serve_env: Dict[str, str] = {}, 1132 readiness_probe: Probe = None, 1133 dir: str = "", 1134 serve_dir: str = "", 1135 labels: List[str] = []) -> None: 1136 """Configures one or more commands to run on the *host* machine (not in a remote cluster). 1137 1138 By default, Tilt performs an update on local resources on ``tilt up`` and whenever any of their ``deps`` change. 1139 1140 When Tilt performs an update on a local resource: 1141 1142 - if `cmd` is non-empty, it is executed 1143 - if `cmd` succeeds: 1144 - Tilt kills any extant `serve_cmd` process from previous updates of this resource 1145 - if `serve_cmd` is non-empty, it is executed 1146 1147 For more info, see the `Local Resource docs <local_resource.html>`_. 1148 1149 Args: 1150 name: will be used as the new name for this resource 1151 cmd: 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. 1152 deps: 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. 1153 trigger_mode: one of ``TRIGGER_MODE_AUTO`` or ``TRIGGER_MODE_MANUAL``. For more info, see the 1154 `Manual Update Control docs <manual_update_control.html>`_. 1155 resource_deps: a list of resources on which this resource depends. 1156 See the `Resource Dependencies docs <resource_dependencies.html>`_. 1157 ignore: set of file patterns that will be ignored. Ignored files will not trigger runs. Follows the `dockerignore syntax <https://docs.docker.com/engine/reference/builder/#dockerignore-file>`_. Patterns will be evaluated relative to the Tiltfile. 1158 auto_init: whether this resource runs on ``tilt up``. Defaults to ``True``. For more info, see the 1159 `Manual Update Control docs <manual_update_control.html>`_. 1160 serve_cmd: Tilt will run this command on update and expect it to not exit. If a string, executed with 1161 ``sh -c`` on macOS/Linux, or ``cmd /S /C`` on Windows; if a list, will be passed to the operating 1162 system as program name and args. 1163 cmd_bat: If non-empty and on Windows, takes precedence over ``cmd``. Ignored on other platforms. 1164 If a string, executed as a Windows batch command executed with ``cmd /S /C``; if a list, will be passed to 1165 the operating system as program name and args. 1166 serve_cmd_bat: If non-empty and on Windows, takes precedence over ``serve_cmd``. Ignored on other platforms. 1167 If a string, executed as a Windows batch command executed with ``cmd /S /C``; if a list, will be passed to 1168 the operating system as program name and args. 1169 allow_parallel: By default, all local resources are presumed unsafe to run in parallel, due to race 1170 conditions around modifying a shared file system. Set to True to allow them to run in parallel. 1171 links: one or 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 :class:`~api.Link` objects. 1172 env: Environment variables to pass to the executed ``cmd``. Values specified here will override any variables passed to the Tilt parent process. 1173 serve_env: Environment variables to pass to the executed ``serve_cmd``. Values specified here will override any variables passed to the Tilt parent process. 1174 readiness_probe: Optional readiness probe to use for determining ``serve_cmd`` health state. Fore more info, see the :meth:`probe` function. 1175 dir: Working directory for ``cmd``. Defaults to the Tiltfile directory. 1176 serve_dir: Working directory for ``serve_cmd``. Defaults to the Tiltfile directory. 1177 labels: used to group resources in the Web UI, (e.g. you want all frontend services displayed together, while test and backend services are displayed separately). A label must start and end with an alphanumeric character, can include ``_``, ``-``, and ``.``, and must be 63 characters or less. For an example, see `Resource Grouping <tiltfile_concepts.html#resource-groups>`_. 1178 """ 1179 pass 1180 1181 def disable_snapshots() -> None: 1182 """Disables Tilt's `snapshots <snapshots.html>`_ feature, hiding it from the UI. 1183 1184 This is intended for use in projects where there might be some kind of 1185 data policy that does not allow developers to upload snapshots to TiltCloud. 1186 1187 Note that this directive does not provide any real security, since a 1188 developer can always simply edit it out of the Tiltfile, but it at least 1189 ensures a pretty high bar of intent. 1190 """ 1191 1192 def docker_prune_settings(disable: bool=False, max_age_mins: int=360, 1193 num_builds: int=0, interval_hrs: int=1, keep_recent: int=2) -> None: 1194 """ 1195 Configures Tilt's Docker Pruner, which runs occasionally in the background and prunes Docker images associated 1196 with your current project. 1197 1198 The pruner runs soon after startup (as soon as at least some resources are declared, and there are no pending builds). 1199 Subsequently, it runs after every ``num_builds`` Docker builds, or, if ``num_builds`` is not set, every ``interval_hrs`` hours. 1200 1201 The pruner will prune: 1202 - stopped containers built by Tilt that are at least ``max_age_mins`` mins old 1203 - images built by Tilt and associated with this Tilt run that are at least ``max_age_mins`` mins old, 1204 and not in the ``keep_recent`` most recent builds for that image name 1205 - dangling build caches that are at least ``max_age_mins`` mins old 1206 1207 Args: 1208 disable: if true, disable the Docker Pruner 1209 max_age_mins: maximum age, in minutes, of images/containers to retain. Defaults to 360 mins., i.e. 6 hours 1210 num_builds: number of Docker builds after which to run a prune. (If unset, the pruner instead runs every ``interval_hrs`` hours) 1211 interval_hrs: 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 1212 keep_recent: when pruning, retain at least the ``keep_recent`` most recent images for each image name. Defaults to 2 1213 """ 1214 pass 1215 1216 def analytics_settings(enable: bool) -> None: 1217 """Overrides Tilt telemetry. 1218 1219 By default, Tilt does not send telemetry. After you successfully run a Tiltfile, 1220 the Tilt web UI will nudge you to opt in or opt out of telemetry. 1221 1222 The Tiltfile can override these telemetry settings, for teams 1223 that always want telemetry enabled or disabled. 1224 1225 Args: 1226 enable: if true, telemetry will be turned on. If false, telemetry will be turned off. 1227 """ 1228 pass 1229 1230 def version_settings(check_updates: bool = True, constraint: str = "") -> None: 1231 """Controls Tilt's behavior with regard to its own version. 1232 1233 Args: 1234 check_updates: If true, Tilt will check GitHub for new versions of itself 1235 and display a notification in the web UI when an upgrade is 1236 available. 1237 constraint: If non-empty, Tilt will check its currently running version against 1238 this constraint and generate an error if it doesn't match. 1239 Examples: 1240 1241 - `<0.17.0` - less than 0.17.0 1242 - `>=0.13.2` - at least 0.13.2 1243 1244 See more at the `constraint syntax documentation <https://github.com/blang/semver#ranges>`_. 1245 """ 1246 1247 def struct(**kwargs) -> Any: 1248 """Creates an object with arbitrary fields. 1249 1250 Examples: 1251 1252 .. code-block:: python 1253 1254 x = struct(a="foo", b=6) 1255 print("%s %d" % (x.a, x.b)) # prints "foo 6" 1256 """ 1257 1258 1259 def secret_settings(disable_scrub: bool = False) -> None: 1260 """Configures Tilt's handling of Kubernetes Secrets. By default, Tilt scrubs 1261 the text of any Secrets from the logs; e.g. if Tilt applies a Secret with contents 1262 'mysecurepassword', Tilt redacts this string if ever it appears in the logs, 1263 to prevent users from accidentally sharing sensitive information in snapshots etc. 1264 1265 Args: 1266 disable_scrub: if True, Tilt will *not* scrub secrets from logs. 1267 """ 1268 1269 1270 def update_settings( 1271 max_parallel_updates: int=3, 1272 k8s_upsert_timeout_secs: int=30, 1273 suppress_unused_image_warnings: Union[str, List[str]]=None) -> None: 1274 """Configures Tilt's updates to your resources. (An update is any execution of or 1275 change to a resource. Examples of updates include: doing a docker build + deploy to 1276 Kubernetes; running a live update on an existing container; and executing 1277 a local resource command). 1278 1279 Args: 1280 max_parallel_updates: maximum number of updates Tilt will execute in parallel. Default is 3. Must be a positive integer. 1281 k8s_upsert_timeout_secs: timeout (in seconds) for Kubernetes upserts (i.e. ``create``/``apply`` calls). Minimum value is 1. 1282 suppress_unused_image_warnings: suppresses warnings about images that aren't deployed. 1283 Accepts a list of image names, or '*' to suppress warnings for all images. 1284 """ 1285 1286 def ci_settings( 1287 k8s_grace_period: str='', 1288 timeout: str='') -> None: 1289 """Configures 'tilt ci' mode. 1290 1291 Args: 1292 k8s_grace_period: Grace period given for Kubernetes resources to recover after they start failing. A duration string. 1293 timeout: Timeout for the whole CI pipeline. A duration string. Defaults to '30m'. 1294 """ 1295 1296 def watch_settings(ignore: Union[str, List[str]]) -> None: 1297 """Configures global watches. 1298 1299 May be called multiple times to add more ignore patterns. 1300 1301 Args: 1302 ignore: A string or list of strings that should not trigger updates. Equivalent to adding 1303 patterns to .tiltignore. Relative patterns are evaluated relative to the current working dir. 1304 See `Debugging File Changes <file_changes.html>`_ for more details. 1305 """ 1306 1307 1308 def warn(msg: str) -> None: 1309 """Emits a warning. 1310 1311 Warnings are both displayed in the logs and aggregated as alerts. 1312 1313 Args: 1314 msg: The message. 1315 """ 1316 1317 1318 def fail(msg: str) -> None: 1319 """Stops Tiltfile execution and raises an error. 1320 1321 Can be used anywhere in a Tiltfile. 1322 If used in a loaded Tiltfile or extension, execution will be stopped up to and including the root Tiltfile. 1323 1324 See :meth:`exit` to stop execution immediately without triggering an error. 1325 1326 Args: 1327 msg: Error message. 1328 """ 1329 pass 1330 1331 1332 def exit(code: Any) -> None: 1333 """Stops Tiltfile execution without an error. 1334 1335 Can be used anywhere in a Tiltfile. 1336 If used in a loaded Tiltfile or extension, execution will be stopped up to and including the root Tiltfile. 1337 1338 Requires Tilt v0.22.3+. 1339 1340 See :meth:`fail` to stop execution immediately and propagate an error. 1341 1342 Args: 1343 code: Message or object (will be stringified) to log before halting execution. 1344 """ 1345 1346 1347 def probe(initial_delay_secs: int=0, 1348 timeout_secs: int=1, 1349 period_secs: int=10, 1350 success_threshold: int=1, 1351 failure_threshold: int=3, 1352 exec: Optional[ExecAction]=None, 1353 http_get: Optional[HTTPGetAction]=None, 1354 tcp_socket: Optional[TCPSocketAction]=None) -> Probe: 1355 """Creates a :class:`Probe` for use with local_resource readiness checks. 1356 1357 Exactly one of exec, http_get, or tcp_socket must be specified. 1358 1359 Args: 1360 initial_delay_secs: Number of seconds after the resource has started before the probe is 1361 first initiated (default is 0). 1362 timeout_secs: Number of seconds after which probe execution is aborted and it is 1363 considered to have failed (default is 1, must be greater than 0). 1364 period_secs: How often in seconds to perform the probe (default is 10, must be greater than 0). 1365 success_threshold: Minimum number of consecutive successes for the result to be 1366 considered successful after having failed (default is 1, must be greater than 0). 1367 failure_threshold: Minimum number of consecutive failures for the result to be 1368 considered failing after having succeeded (default is 3, must be greater than 0). 1369 exec: Process execution handler to determine probe success. 1370 http_get: HTTP GET handler to determine probe success. 1371 tcp_socket: TCP socket connection handler to determine probe success. 1372 """ 1373 1374 def exec_action(command: List[str]) -> ExecAction: 1375 """Creates an :class:`ExecAction` for use with a :class:`Probe` that runs a command 1376 to determine service readiness based on exit code. 1377 1378 The probe is successful if the process terminates normally with an exit code of 0 1379 within the timeout. 1380 1381 Args: 1382 command: Command with arguments to execute. 1383 """ 1384 pass 1385 1386 1387 def http_get_action(port: int, host: str='localhost', scheme: str='http', path: str='') -> HTTPGetAction: 1388 """Creates a :class:`HTTPGetAction` for use with a :class:`Probe` that performs an HTTP GET 1389 request to determine service readiness based on response status code. 1390 1391 The probe is successful if a valid HTTP response is received within the timeout and has a 1392 status code >= 200 and < 400. 1393 1394 Args: 1395 host: Hostname to use for HTTP request. 1396 port: Port to use for HTTP request. 1397 scheme: URI scheme to use for HTTP request, valid values are `http` and `https`. 1398 path: URI path for HTTP request. 1399 """ 1400 pass 1401 1402 1403 def tcp_socket_action(port: int, host: str='localhost') -> TCPSocketAction: 1404 """Creates a :class:`TCPSocketAction` for use with a :class:`Probe` that establishes a TCP 1405 socket connection to determine service readiness. 1406 1407 The probe is successful if a TCP socket can be established within the timeout. No data is 1408 sent or read from the socket. 1409 1410 Args: 1411 host: Hostname to use for TCP socket connection. 1412 port: Port to use for TCP socket connection. 1413 """ 1414 pass