Tiltfile 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- mode: Python -*-
  2. def namespace_yaml(name):
  3. """Returns YAML for a namespace
  4. Args:
  5. name: The namespace name. Currently not validated.
  6. Returns:
  7. The namespace YAML as a blob
  8. """
  9. return blob("""apiVersion: v1
  10. kind: Namespace
  11. metadata:
  12. name: %s
  13. """ % name)
  14. def namespace_create(name):
  15. """Creates a namespace in the current Kubernetes cluster.
  16. Args:
  17. name: The namespace name. Currently not validated.
  18. """
  19. k8s_yaml(namespace_yaml(name))
  20. def namespace_inject(x, ns):
  21. """Takes K8s yaml, sets its namespace to `ns`, and returns it as a blob.
  22. This modifies the yaml in two ways:
  23. 1. Sets .metadata.namespace to `ns`
  24. 2. Sets ..template.metadata.namespace to `ns`
  25. This ensures the namespace in, e.g., Deployment Pod Template Specs is
  26. set, but might have false positives if you have a CRD with some other
  27. element named 'template'.
  28. Args:
  29. x: K8s yaml. Either a filename (string) or the yaml itself (Blob)
  30. ns: The namespace to set the K8s objects to.
  31. Returns:
  32. Blob containing the K8s objects as yaml, with namespaces set to `ns`.
  33. """
  34. return _mutate_yaml(x, lambda o: _set_k8s_yaml_namespace(o, ns))
  35. def _mutate_yaml(x, f):
  36. if type(x) == 'string':
  37. objects = read_yaml_stream(x)
  38. elif type(x) == 'blob':
  39. objects = decode_yaml_stream(x)
  40. else:
  41. fail('only takes string or blob, got: %s' % type(x))
  42. return encode_yaml_stream([f(o) for o in objects])
  43. def _set_k8s_yaml_namespace(o, ns):
  44. o['metadata']['namespace'] = ns
  45. _set_template_namespace(o, ns)
  46. return o
  47. def _set_template_namespace(o, ns):
  48. if type(o) == 'dict':
  49. for k, v in o.items():
  50. if k == 'template' and type(v) == 'dict' and type(v.get('metadata', None)) == 'dict':
  51. v['metadata']['namespace'] = ns
  52. if type(v) == 'dict' or type(v) == 'list':
  53. _set_template_namespace(v, ns)
  54. elif type(o) == 'list':
  55. for v in o:
  56. _set_template_namespace(v, ns)