#!/usr/bin/env bash set -o pipefail -o noclobber function usage() { cat < ./$(basename "$0") [option [option...]] [file_path] ARGUMENTS file_path file path where the file will be saved; if neither this argument nor the environment variable \$ANSIBLE_CFG_PATH is provided, the content will be printed on stdout. OPTIONS -h, --help show this output -o, --overwrite allow overwriting of a pre-existing file ENVIRONMENT The following environment variables are supported for overrides: ANSIBLE_CFG_PATH: path where the ansible config file should be stored (current: "${ANSIBLE_CFG_PATH:-stdout}" or argument) TMPL_PROJECT_ROOT: path where this project is located; defaults to where '../' leads (current: "$TMPL_PROJECT_ROOT") TMPL_INVENTORY_FILE: path where the main inventory file is located (current: "$TMPL_INVENTORY_FILE") TMPL_CONNECTION_TIMEOUT: default connection timeout when connecting to hosts (current: $TMPL_CONNECTION_TIMEOUT) TMPL_PLAYBOOK_DIR: path where the playbooks are located (current: "$TMPL_PLAYBOOK_DIR") EOF } ANSIBLE_CFG_PATH=${ANSIBLE_CFG_PATH:=} OVERWRITE_CFG=0 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # Template variables TMPL_PROJECT_ROOT=$(realpath "${TMPL_PROJECT_ROOT:-"${SCRIPT_DIR}/.."}") TMPL_INVENTORY_FILE=$(realpath "${TMPL_INVENTORY_FILE:-"${TMPL_PROJECT_ROOT}/inventory/inventory.yml"}") TMPL_CONNECTION_TIMEOUT=${TMPL_CONNECTION_TIMEOUT:-30} TMPL_PLAYBOOK_DIR=$(realpath "${TMPL_PLAYBOOK_DIR:-"${TMPL_PROJECT_ROOT}/playbooks"}") OPTS=ho LONGOPTS=help,overwrite ! getopt --test > /dev/null if [[ ${PIPESTATUS[0]} -ne 4 ]]; then echo -e "Getopt is not available, please install linux-utils or a similar package and ensure your bash is up-to-date." exit 1 fi ! PARSED=$(getopt --options=${OPTS} --longoptions=${LONGOPTS} --name "$0" -- "$@") if [[ ${PIPESTATUS[0]} -ne 0 ]]; then exit 2 fi eval set -- "${PARSED}" while true; do case "$1" in -h|--help) usage exit 0 ;; -o|--overwrite) OVERWRITE_CFG=1 shift ;; --) shift break ;; *) echo "Unsupported option: ${1}" exit 2 ;; esac done if [ -n "${1}" ]; then ANSIBLE_CFG_PATH=$1 fi if [ -e "${ANSIBLE_CFG_PATH}" ] && [ $OVERWRITE_CFG -eq 0 ]; then printf "Configuration file already exists, not overwriting (file: '%s')\n" "${ANSIBLE_CFG_PATH}" exit 1 fi CFG_TEMPLATE=$(cat < "${ANSIBLE_CFG_PATH}" fi