Created
August 12, 2021 15:42
-
-
Save parsley42/9e9e44529093f82ca5e44c26f20d1c7c to your computer and use it in GitHub Desktop.
Terraform Completion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bash Terraform completion | |
# Originally adapted from: https://gist.github.com/cornfeedhobo/8bc08747ec3add1fc5adb2edb7cd68d3 | |
# Adapted from: https://gist.github.com/zish/85dccece461e050077997ff5d7d9c9d4 by Jeremy Melanson | |
# | |
#--- Get options listing from Terraform command. | |
_terraform_completion_get_opts () { | |
local CMD_EXEC="${1}" | |
local TF_OPT="${2}" | |
local IFS=$'\n' | |
#-- "terraform -help" | |
if [[ "${TF_OPT}" == "" ]]; then | |
for O in $(${CMD_EXEC} -help); do | |
if [[ "${O}" =~ ^\ +([^\ ]+) ]]; then | |
echo "${BASH_REMATCH[1]}" | |
fi | |
done | |
#-- "terraform -help XXXX" | |
else | |
for O in $(${CMD_EXEC} -help ${TF_OPT}); do | |
if [[ "${O}" =~ ^\ +(-[^\ =]+=?) ]]; then | |
echo -e "${BASH_REMATCH[1]}" | |
fi | |
done | |
fi | |
} | |
#--- This function is passed to 'complete' for handling completion. | |
_terraform_completion () { | |
local cur prev words cword opts | |
_init_completion -s || return | |
_get_comp_words_by_ref -n : cur prev words cword | |
COMPREPLY=() | |
opts="" | |
if [[ ${cur} == -* ]] ; then | |
compopt -o nospace | |
fi | |
local CMD_EXEC="terraform" | |
if [[ ${cword} -eq 1 ]] ; then | |
if [[ ${cur} == -* ]] ; then | |
opts="--help --version" | |
else | |
opts="$(_terraform_completion_get_opts ${CMD_EXEC})" | |
fi | |
elif [[ ${cword} -gt 1 ]]; then | |
if [[ ${cword} -eq 2 && ${prev} =~ \-\-?help ]]; then | |
opts="$(_terraform_completion_get_opts ${CMD_EXEC})" | |
else | |
local TF_COMMAND="${words[1]}" | |
opts="$(_terraform_completion_get_opts ${CMD_EXEC} ${TF_COMMAND})" | |
fi | |
fi | |
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) | |
return 0 | |
} | |
alias tf=terraform | |
complete -F _terraform_completion terraform | |
complete -F _terraform_completion tf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment