Skip to content

Instantly share code, notes, and snippets.

@sparkprime
Created May 31, 2016 18:29
Show Gist options
  • Save sparkprime/1d81bf1dfb574fa88aa459b22f31f899 to your computer and use it in GitHub Desktop.
Save sparkprime/1d81bf1dfb574fa88aa459b22f31f899 to your computer and use it in GitHub Desktop.
KPM-themed example of using jinja expansion in Jsonnet
local native_expand_template = std.native("expand_template");
{
expand_template(template, env): [
native_expand_template(template, std.toString(env))
],
expand_sharded_template(template, env, all_shards): [
native_expand_template(template, std.toString(env + { shard_name: shard_name }))
for shard_name in all_shards
],
}
local kpm = import "kpm.jsonnet";
function(
params={},
)
{
package: {
author: "Antoine Legrand",
description: "rabbitmq",
license: "MIT",
name: "rabbitmq/rabbitmq",
version: "3.5.6",
},
// Maybe this should actually be part of 'package', as it is metadata?
defaults: {
cookie: "Dffds9342",
data_volume: {
emptyDir: {
medium: "",
},
name: "varlibrabbitmq",
},
image: "quay.io/ant31/kubernetes-rabbitmq",
namespace: "default",
},
local all_shards = [1, 2, 3],
local env = $.defaults + params + {
all_shards: all_shards,
},
// Array of arrays of string: Flatten this and parse to yaml outside of Jsonnet.
resources: [
kpm.expand_sharded_template(importstr "templates/rabbitmq-svc.yaml", env, all_shards),
kpm.expand_template(importstr "templates/rabbitmq-all-svc.yaml", env),
kpm.expand_template(importstr "templates/rabbitmq-management-svc.yaml", env),
kpm.expand_sharded_template(importstr "templates/rabbitmq-rc.yaml", env, all_shards),
],
deploy: {
name: "$self",
},
}
import jinja2
import json
import _jsonnet
import sys
def _expand_template(template, env_json):
env = json.loads(env_json)
r = jinja2.Environment().from_string(template).render(**env)
return r.encode('utf8')
native_callbacks = {
'expand_template': (('template', 'env_json'), _expand_template),
}
if len(sys.argv) > 2:
sys.stderr.write('Usage: %s [json_blob]\n' % sys.argv[0])
sys.exit(1)
# Validate it here.
if len(sys.argv) > 1:
params = json.loads(sys.argv[1], '{}')
else:
params = {}
json_str = _jsonnet.evaluate_file(
'manifest.jsonnet',
tla_codes={'params': json.dumps(params)},
native_callbacks=native_callbacks,
)
json = json.loads(json_str)
for resource_group in json['resources']:
for r in resource_group:
print r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment