Skip to content

Instantly share code, notes, and snippets.

@juliedavila
Created November 13, 2018 21:04
Show Gist options
  • Select an option

  • Save juliedavila/afc0783ce848ccedf75e9854207ba2a8 to your computer and use it in GitHub Desktop.

Select an option

Save juliedavila/afc0783ce848ccedf75e9854207ba2a8 to your computer and use it in GitHub Desktop.
A an example Ansible module written in bash
#!/bin/bash
### DOCUMENTATION
#######
## This is a simple module that simply appends a provided line to the specified file
## It is intended to give sufficient content in order for anyone to develop Ansible modules in bash
#######
# ARGS #
## line
## path
## create
#
###
function validate_path {
# $1 => the path to check for
# $2 => boolean, whether to create the file or not if it's absent
if [[ -d $1 ]]; then
err "Path must be a file not a directory"
elif [[ -f $1 ]]; then
return 0
elif ! [[ -f $1 ]] && [[ $2 == true ]]; then
touch $1
elif ! [[ -f $1 ]] && [[ $2 == false ]]; then
err "Path '$1' does not exist and 'create' was set to false"
fi
}
function err {
# $1 => the string message to error out with
printf '{"changed": "false", "failed": true, "msg": "%s"}' "$1"
exit 1
}
function required {
# $1 => the expanded value of the module param
# $2 => the label of the module param
if ! [[ -n "$1" ]]; then
err "'$2' is required"
fi
}
function set_default {
# $1 => the expanded value of the module param
# $2 => the label of the module param
if ! [[ -n "$1" ]]; then
echo $2
else
echo $1
fi
}
function main {
source $1
# These values are defined from the source command above this line
# $line
# $path
# $create
required "${line}" line
required "${path}" path
create=$(set_default "${create}" false)
validate_path ${path} ${create}
echo ${line} >> ${path}
printf '{"changed": "false", "path": "%s", "line": "%s"}' $path $line
}
main $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment