diff --git a/scripts/util/sanitize_node.sh b/scripts/util/sanitize_node.sh new file mode 100755 index 0000000..99d4ec3 --- /dev/null +++ b/scripts/util/sanitize_node.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Strip the top-level "override" and "default" attributes from Chef node JSON files. +# +# Usage: +# ./scripts/util/strip_node_attrs.sh [ ...] +# ./scripts/util/strip_node_attrs.sh --all +# +# A may be a bare node name (e.g. "prometheus-1"), a path relative to the +# repository root (e.g. "nodes/prometheus-1.json"), or an absolute path. +# +# Exit codes: +# 0 - all target files processed successfully +# 1 - one or more targets could not be processed (missing args, missing jq, +# file not found, invalid JSON, or write failure) + +set -uo pipefail + +command -v jq >/dev/null 2>&1 || exit 1 + +root="$(git rev-parse --show-toplevel 2>/dev/null)" || root="$(pwd)" + +targets=() +if [ "$#" -eq 0 ]; then + exit 1 +fi + +for arg in "$@"; do + if [ "$arg" = "--all" ]; then + shopt -s nullglob + for f in "$root"/nodes/*.json; do + targets+=("$f") + done + shopt -u nullglob + continue + fi + + if [[ "$arg" == */* ]]; then + if [[ "$arg" = /* ]]; then + targets+=("$arg") + else + targets+=("$root/$arg") + fi + else + targets+=("$root/nodes/$arg.json") + fi +done + +if [ "${#targets[@]}" -eq 0 ]; then + exit 1 +fi + +rc=0 +for file in "${targets[@]}"; do + [ -f "$file" ] || { rc=1; continue; } + + jq -e . "$file" >/dev/null 2>&1 || { rc=1; continue; } + + tmp="$(mktemp "${file}.XXXXXX")" || { rc=1; continue; } + if jq --indent 2 'del(.override, .default)' "$file" > "$tmp" 2>/dev/null; then + truncate -s -1 "$tmp" 2>/dev/null || true + mv "$tmp" "$file" || { rm -f "$tmp"; rc=1; continue; } + else + rm -f "$tmp" + rc=1 + continue + fi +done + +exit "$rc"