A comprehensive guide to Jsonnet's powerful features and common patterns
// Local variables
local name = 'Alice';
local age = 25;
{
person: {
name: name,
age: age,
},
}
// Local block
{
local service = {
name: 'web',
port: 8080,
},
deployment: {
name: service.name,
containerPort: service.port,
},
}
// Basic function
local greeting(name) = 'Hello ' + name;
// Function with default parameters
local createPod(name, image='nginx:latest') = {
apiVersion: 'v1',
kind: 'Pod',
metadata: {
name: name,
},
spec: {
containers: [{
name: name,
image: image,
}],
},
};
// Object merging
local base = {
name: 'app',
replicas: 1,
};
local override = {
replicas: 3,
image: 'nginx',
};
// Merge with override
local result = base + override;
// Hidden fields
{
local privateVar = 'hidden',
publicVar: 'visible',
}
// Array comprehension
local numbers = [1, 2, 3, 4, 5];
local doubled = [x * 2 for x in numbers];
// Conditional comprehension
local evens = [
x for x in numbers
if x % 2 == 0
];
// Object comprehension
local users = ['alice', 'bob'];
{
[name + '_role']: 'user'
for name in users
}
// If expressions
local status = if uptime > 90 then 'healthy' else 'degraded';
// Error handling
local divide(a, b) =
if b == 0 then
error 'Division by zero'
else
a / b;
// Assert statements
{
name: 'app',
replicas: assert replicas > 0 : 'Replicas must be positive'; replicas,
}
// Import files
local config = import 'config.jsonnet';
local lib = import 'lib.libsonnet';
// Import multiple files
local k = import 'k.libsonnet';
local utils = import 'utils.libsonnet';
{
deployment: k.deployment.new(name='web', image='nginx'),
service: k.service.new(name='web', port=80),
}
// String concatenation
local name = 'web';
local fullName = name + '-service';
// String formatting
local template = 'Hello %s!';
local greeting = std.format(template, ['World']);
// Multiline strings
local yaml = |||
apiVersion: v1
kind: Service
metadata:
name: %s
|||;
// Environment configuration
local env = std.extVar('env');
local config = {
dev: { replicas: 1 },
prod: { replicas: 3 },
};
// Template functions
local makeService(name, port) = {
apiVersion: 'v1',
kind: 'Service',
metadata: { name: name },
spec: {
ports: [{ port: port }],
},
};