3 from cloudify import ctx
6 SERVICES_FILE_PARTS_SEPARATOR = '---'
9 def _import_or_install():
13 pip.main(["install", "pyaml"])
16 import cloudify_kubernetes.tasks as kubernetes_plugin
20 "https://github.com/cloudify-incubator/cloudify-kubernetes-plugin/archive/1.2.1rc1.zip"
26 pip.main(["install", "jinja2"])
30 import cloudify_kubernetes.tasks as kubernetes_plugin
32 return yaml, kubernetes_plugin, jinja2
35 def _init_jinja(jinja2):
36 return jinja2.Environment(
37 loader=jinja2.BaseLoader()
41 def _render_template(jinja_env, template_content, values):
42 template_content = template_content.replace('.Values', 'Values')
44 template = jinja_env.from_string(template_content)
45 rendered_template = template.render(Values=values)
46 return rendered_template
49 def _retrieve_resources_paths():
50 return ctx.node.properties.get('resources', [])
53 def _retrieve_services_paths():
54 return ctx.node.properties.get('services', None)
57 def _retrieve_values(yaml):
58 values_file_path = ctx.node.properties.get('values', None)
61 return yaml.load(ctx.get_resource(values_file_path))
63 ctx.logger.warn('Values file not found')
66 def _save_deployment_result(key):
67 result = ctx.instance.runtime_properties['kubernetes']
68 ctx.instance.runtime_properties[key] = result
69 ctx.instance.runtime_properties['kubernetes'] = {}
72 def _do_create_resources(kubernetes_plugin, yaml, jinja_env, values):
73 for path in _retrieve_resources_paths():
74 ctx.logger.info('Creating 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 kubernetes_plugin.resource_create(definition=content)
85 _save_deployment_result(
86 'resource_{0}'.format(content['metadata']['name'])
89 ctx.logger.info('Resources created successfully')
92 def _do_create_services(kubernetes_plugin, yaml, jinja_env, values):
93 ctx.logger.info('Creating 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 kubernetes_plugin.resource_create(definition=content)
117 _save_deployment_result(
118 'service_{0}'.format(content['metadata']['name'])
121 ctx.logger.info('Services created 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_create_resources(kubernetes_plugin, yaml, jinja_env, values)
130 _do_create_services(kubernetes_plugin, yaml, jinja_env, values)