def install_crd(plural, singular, kind): crd = get(f'crd {plural}.stable.viderum.com', required=False) version = 'v1' if crd: assert crd['spec']['versions'][0]['name'] == version print(f'{kind} custom resource definitions are up-to-date') else: print(f'Creating {kind} {version} custom resource definition') crd = {'apiVersion': 'apiextensions.k8s.io/v1beta1', 'kind': 'CustomResourceDefinition', 'metadata': { 'name': f'{plural}.stable.viderum.com' }, 'spec': { 'versions': [{ 'name': version, 'served': True, 'storage': True }], 'group': 'stable.viderum.com', 'scope': 'Namespaced', 'names': { 'plural': plural, 'singular': singular, 'kind': kind } }} logs.subprocess_run('kubectl create -f -', input=yaml.dump(crd).encode())
def set_secrets(self, key_values): for key in key_values: assert key in self.SECRET_ANNOTATIONS, 'unknown secret annotation: {key}' secret = getattr(self, '_secret', None) cur_data = secret.get('data', {}) if secret and secret != __NONE__ else {} secret = get( f'secret {self.resource_kind}-{self.resource_id}-annotations', required=False) if not secret: secret = {'data': {}} secret['data'].update(**cur_data) for key, value in key_values.items(): secret['data'][key] = base64.b64encode(value.encode()).decode() secret = { 'apiVersion': 'v1', 'kind': 'Secret', 'metadata': { 'name': f'{self.resource_kind}-{self.resource_id}-annotations', 'namespace': 'ckan-cloud', 'labels': self.get_secret_labels() }, 'type': 'Opaque', 'data': secret['data'] } logs.subprocess_run(f'kubectl apply -f -', input=yaml.dump(secret).encode()) self._secret = secret
def create(resource, is_yaml=False): if is_yaml: resource = yaml.load(resource) try: logs.subprocess_run('kubectl create -f -', input=yaml.dump(resource).encode()) except: logging.exception('Failed to create resource\n%s', yaml.dump(resource, default_flow_style=False)) raise
def apply(resource, is_yaml=False, reconcile=False, dry_run=False): if is_yaml: resource = yaml.load(resource) cmd = 'auth reconcile' if reconcile else 'apply' args = [] if dry_run: args.append('--dry-run') args = " ".join(args) try: logs.subprocess_run(f'kubectl {cmd} {args} -f -', input=yaml.dump(resource).encode()) except: logging.exception('Failed to apply resource\n%s', yaml.dump(resource, default_flow_style=False)) raise if dry_run: print(yaml.dump(resource, default_flow_style=False))