#!/bin/bash # # sopsfile generator - designed to work with the Terraform External Data Source provider # https://www.terraform.io/docs/providers/external/data_source.html # by Armen Rostamian (StelthLabs) # # This script takes the 3 arguments as JSON-formatted stdin # It produces the file content for a sops-encrypted secrets file as JSON-formatted stdout # The JSON-formatted stdout is then written to disk as YAML by the terraform module)... # because YAML is easier on the human brain, and just as friendly to the machine # # DEBUG statements may be safely uncommented as they only output to stderr function error_exit() { echo "$1" 1>&2 exit 1 } function check_deps() { test -f $(which sops) || error_exit "sops not detected in path, please install it -> https://github.com/mozilla/sops" test -f $(which jq) || error_exit "jq not detected in path, please install it -> https://github.com/stedolan/jq" test -f $(which jo) || error_exit "jo not detected in path, please install it -> https://github.com/jpmens/jo" } function parse_input() { # jq reads from stdin so we don't have to set up any inputs, but let's validate the outputs eval "$(jq -r '@sh "export KMS_KEY_ARN=\(.kms_key_arn) ENCRYPTION_PROFILE=\(.encryption_profile) export SENSITIVE_MATERIAL=\(.sensitive_material)"')" if [[ -z "${KMS_KEY_ARN}" ]]; then export KMS_KEY_ARN=none; fi if [[ -z "${ENCRYPTION_PROFILE}" ]]; then export ENCRYPTION_PROFILE=none; fi if [[ -z "${SENSITIVE_MATERIAL}" ]]; then export SENSITIVE_MATERIAL=none else DECODED_MATERIAL=$(echo "${SENSITIVE_MATERIAL}" | base64 -d) export SENSITIVE_MATERIAL="${DECODED_MATERIAL}" fi # DEBUG EXAMPLE # echo "ENCRYPTION_PROFILE: $ENCRYPTION_PROFILE" 1>&2 } function render_data_output() { # !! READ BEFORE CHANGING !! # # Changing directories ensures that sops doesn't get confused # because its default behaviour is to traverse the filesystem (upward) # until it finds a .sops.yaml config file. # To short-circuit this behaviour we change directories to a location # like "/tmp" where we don't keep or expect to find any sops configs. cd /tmp/ || exit ENCRYPTED_DATA=$(echo "$SENSITIVE_MATERIAL" \ | sops \ --encrypt \ --kms $KMS_KEY_ARN \ --aws-profile "$AWS_PROFILE" \ --input-type json \ --output-type json \ /dev/stdin \ | base64) jo encrypted_content="$ENCRYPTED_DATA" } # Do useful work, friend... check_deps parse_input render_data_output