78 lines
2.4 KiB
Bash
Executable File
78 lines
2.4 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
fetch_secret() {
|
|
local target_secret="${1:?Target secret local_secret is required}"
|
|
local env="${2:?Environment is required}"
|
|
local output_file="${3:?}"
|
|
|
|
if command -v infisical &>/dev/null; then
|
|
# If infisical CLI command is available, use it directly
|
|
infisical secrets --plain get "${target_secret}" --env "${env}" >"${output_file}"
|
|
else
|
|
script -q /dev/null \
|
|
-c "docker compose run --rm -t cli infisical secrets --plain get ""${target_secret}"" --env ""${env}""" \
|
|
>"${output_file}"
|
|
fi
|
|
|
|
# Check if file is empty
|
|
if [[ ! -s ${output_file} ]]; then
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
main() {
|
|
local config_file="${1:-./secrets.json}"
|
|
local secrets_dir="${2:-./secrets}"
|
|
|
|
if ! command -v jq &>/dev/null; then
|
|
printf "Error: jq is required but not installed\n" >&2
|
|
return 1
|
|
fi
|
|
|
|
if [[ ! -f ${config_file} ]]; then
|
|
printf "Error: Config file %s not found\n" "${config_file}" >&2
|
|
return 1
|
|
fi
|
|
|
|
mkdir -p "${secrets_dir}"
|
|
|
|
mapfile -t entries < <(jq -c '.[]' "${config_file}")
|
|
|
|
local local_secret target_secret filename env obj
|
|
|
|
for obj in "${entries[@]}"; do
|
|
local_secret="$(jq -r .secret_name <<<"${obj}")"
|
|
target_secret="$(jq -r .target_secret <<<"${obj}")"
|
|
env="$(jq -r .env <<<"${obj}")"
|
|
filename="$(jq -r .filename <<<"${obj}")"
|
|
|
|
if [[ ${local_secret} == "null" || ${target_secret} == "null" ]]; then
|
|
printf "Error: Missing required fields in entry: %s\n" "${obj}" >&2
|
|
continue
|
|
fi
|
|
|
|
# Default output file name
|
|
output_file="${secrets_dir}/${local_secret}"
|
|
|
|
# If filename is specified in json, use it; otherwise, use the local_secret as the filename
|
|
if [[ -n ${filename} && ${filename} != "null" ]]; then
|
|
output_file="${secrets_dir}/${filename}"
|
|
fi
|
|
|
|
if [[ -z ${env} ]]; then
|
|
printf "Warning: Environment not specified for secret %s, assuming 'prod'\n" "${local_secret}" >&2
|
|
fi
|
|
|
|
printf "Processing %s -> %s (%s)\n" "${local_secret}" "${target_secret}" "${env}"
|
|
if fetch_secret "${target_secret}" "${env}" "${output_file}"; then
|
|
printf "✔ saved to %s\n" "${output_file}"
|
|
continue
|
|
fi
|
|
|
|
rm -f "${output_file}" # Clean up if fetch failed
|
|
printf "✘ failed to fetch %s\n" "${target_secret}" >&2
|
|
done
|
|
}
|
|
|
|
main "$@"
|