Skip to content

Instantly share code, notes, and snippets.

@mhutter
Last active February 27, 2025 07:35
Show Gist options
  • Save mhutter/62b8c5a8e2cd3db46cc3819bf7f4ac30 to your computer and use it in GitHub Desktop.
Save mhutter/62b8c5a8e2cd3db46cc3819bf7f4ac30 to your computer and use it in GitHub Desktop.
Sort Kubernetes Pod environment variables according to their references
// Find dependencies on `names` in `str`
//
// For `name` in `names`, find whether `str` contains `$(name)`
local extractDeps(names) = function(str)
std.filter(
function(m)
local pat = std.format('$(%s)', m);
std.member(str, pat),
names,
);
// Calculate the dependency depth for the given variable name.
//
// Expects `deps` to be a map of variable names to dependency names
local calculateDepth = function(name, deps)
if std.length(deps[name]) == 0 then
0
else
1 + std.foldl(
function(acc, depName) std.max(acc, calculateDepth(depName, deps)),
deps[name],
0,
);
local sortDeps = function(items)
// collect valid variable names
local names = std.map(function(m) m.name, items);
local extractDepsWithNames = extractDeps(names);
// collect the dependencies for each variable name, or an empty list if the
// variable is not a plain value (e.g. for secret or field ref values)
local deps = std.foldl(
function(acc, i)
local deps = if std.objectHas(i, 'value') then
extractDepsWithNames(i.value)
else
[];
acc { [i.name]: deps },
items,
{},
);
local itemsWithDepth = std.map(
function(i) i {
depth:: if std.objectHas(i, 'value')
then calculateDepth(i.name, deps)
else -1,
},
items,
);
std.sort(
itemsWithDepth,
function(i) i.depth,
);
local items = [
{ name: 'ONE', value: '$(TWO).$(THREE)' },
{ name: 'TWO', value: '$(THREE)' },
{ name: 'THREE', value: '$(FOUR)' },
{ name: 'FOUR', value: '4' },
{ name: 'FIVE', value: '5' },
{ name: 'SIX', valueFrom: { secretRef: { name: 'some secret', key: 'SOME_KEY' } } },
{ name: 'SEVEN', valueFrom: { fieldRef: { fieldPath: 'some.field' } } },
];
sortDeps(items)
[
{
"name": "SIX",
"valueFrom": {
"secretRef": {
"key": "SOME_KEY",
"name": "some secret"
}
}
},
{
"name": "SEVEN",
"valueFrom": {
"fieldRef": {
"fieldPath": "some.field"
}
}
},
{
"name": "FOUR",
"value": "4"
},
{
"name": "FIVE",
"value": "5"
},
{
"name": "THREE",
"value": "$(FOUR)"
},
{
"name": "TWO",
"value": "$(THREE)"
},
{
"name": "ONE",
"value": "$(TWO).$(THREE)"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment