3 from cloudify import ctx
4 from cloudify.exceptions import NonRecoverableError
7 SERVICES_FILE_PARTS_SEPARATOR = '---'
10 def _import_or_install():
14 pip.main(["install", "pyaml"])
17 import cloudify_kubernetes.tasks as kubernetes_plugin
21 "https://github.com/cloudify-incubator/cloudify-kubernetes-plugin/archive/1.2.1rc1.zip"
27 pip.main(["install", "jinja2"])
31 import cloudify_kubernetes.tasks as kubernetes_plugin
33 return yaml, kubernetes_plugin, jinja2
36 def _init_jinja(jinja2):
37 return jinja2.Environment(
38 loader=jinja2.BaseLoader()
42 def _render_template(jinja_env, template_content, values):
43 template_content = template_content.replace('.Values', 'Values')
45 template = jinja_env.from_string(template_content)
46 rendered_template = template.render(Values=values)
47 return rendered_template
50 def _retrieve_resources_paths():
51 return ctx.node.properties.get('resources', [])
54 def _retrieve_services_paths():
55 return ctx.node.properties.get('services', None)
58 def _retrieve_values(yaml):
59 values_file_path = ctx.node.properties.get('values', None)
62 return yaml.load(ctx.get_resource(values_file_path))
64 ctx.logger.warn('Values file not found')
67 def _set_deployment_result(key):
68 result = ctx.instance.runtime_properties.pop(key)
69 ctx.instance.runtime_properties['kubernetes'] = result
72 def _do_delete_resources(kubernetes_plugin, yaml, jinja_env, values):
73 for path in _retrieve_resources_paths():
74 ctx.logger.info('Deleting resource defined in: {0}'.format(path))
76 template_content = ctx.get_resource(path)
77 yaml_content = _render_template(
82 content = yaml.load(yaml_content)
84 _set_deployment_result(
85 'resource_{0}'.format(content['metadata']['name'])
87 kubernetes_plugin.resource_delete(definition=content)
89 ctx.logger.info('Resources deleted successfully')
92 def _do_delete_services(kubernetes_plugin, yaml, jinja_env, values):
93 ctx.logger.info('Deleting services')
94 services_file_path = _retrieve_services_paths()
96 if not services_file_path:
98 'Service file is not defined. Skipping services provisioning !'
103 template_content = ctx.get_resource(services_file_path)
104 yaml_content = _render_template(
110 yaml_content_parts = \
111 yaml_content.split(SERVICES_FILE_PARTS_SEPARATOR)
113 for yaml_content_part in yaml_content_parts:
114 content = yaml.load(yaml_content_part)
116 _set_deployment_result(
117 'service_{0}'.format(content['metadata']['name'])
119 kubernetes_plugin.resource_delete(definition=content)
121 ctx.logger.info('Services deleted successfully')
124 if __name__ == '__main__':
125 yaml, kubernetes_plugin, jinja2 = _import_or_install()
126 jinja_env = _init_jinja(jinja2)
127 values = _retrieve_values(yaml)
129 _do_delete_services(kubernetes_plugin, yaml, jinja_env, values)
130 _do_delete_resources(kubernetes_plugin, yaml, jinja_env, values)