Last active
April 9, 2020 20:08
-
-
Save maiamcc/a563f827024a13368bebd64d366f2b3a to your computer and use it in GitHub Desktop.
rough attempt at Tiltfile function for adding a namespace to all passed YAML (via Matt Landis: http://github.com/landism)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Originally by Matt Landis: http://github.com/landism | |
| def mutate_yaml(x, f): | |
| if type(x) == 'string': | |
| o = read_yaml(x) | |
| elif type(x) == 'Blob': | |
| o = decode_yaml(x) | |
| else: | |
| fail('only takes string or Blob') | |
| return encode_yaml(f(o)) | |
| def yaml_with_namespace(x, ns): | |
| """ | |
| Takes K8s yaml, sets its namespace to `ns`, and returns it as a blob. | |
| This modifies the yaml in two ways: | |
| 1. Sets .metadata.namespace to `ns` | |
| 2. Sets ..template.metadata.namespace to `ns` | |
| This ensures the namespace in, e.g., Deployment Pod Template Specs is | |
| set, but might have false positives if you have a CRD with some other | |
| element named 'template'. | |
| Args: | |
| x: K8s yaml. Either a filename (string) or the yaml itself (Blob) | |
| ns: The namespace to set the K8s objects to. | |
| Returns: | |
| Blob containing the K8s object as yaml, with namespaces set to `ns`. | |
| """ | |
| return mutate_yaml(x, lambda o: set_k8s_yaml_namespace(o, ns)) | |
| # return 6 | |
| def set_k8s_yaml_namespace(o, ns): | |
| o['metadata']['namespace'] = ns | |
| _set_template_namespace(o, ns) | |
| return o | |
| def _set_template_namespace(o, ns): | |
| if type(o) == 'dict': | |
| for k, v in o.items(): | |
| if k == 'template': | |
| v['metadata']['namespace'] = ns | |
| if type(v) == 'dict' or type(v) == 'list': | |
| _set_template_namespace(v, ns) | |
| elif type(o) == 'list': | |
| for v in o: | |
| _set_template_namespace(v, ns) | |
| else: | |
| print('skipping object of type %s' % type(o)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment