Files
infisical-cli-docker/dist/scripts/src/fetch-secrets.sh

79 lines
2.5 KiB
Bash
Raw Normal View History

2025-05-29 17:34:58 +02:00
#!/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
2025-05-29 17:34:58 +02:00
# 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
2025-05-29 17:34:58 +02:00
printf "Error: jq is required but not installed\n" >&2
return 1
fi
if [[ ! -f ${config_file} ]]; then
2025-05-29 17:34:58 +02:00
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
2025-05-29 17:34:58 +02:00
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
2025-05-29 21:12:48 +02:00
output_file="${secrets_dir}/${filename}"
fi
2025-05-29 17:34:58 +02:00
2025-06-01 23:45:52 +02:00
if [[ ${env} == "null" ]]; then
2025-06-01 23:47:07 +02:00
printf "Warning: Environment not specified for secret %s, assuming 'dev'\n" "${local_secret}" >&2
env="dev"
2025-05-29 17:34:58 +02:00
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 "$@"