Skip to content

Instantly share code, notes, and snippets.

Forked from Faheetah/
Created April 7, 2018 12:27
Show Gist options
  • Save aeciopires/ba64d72f97966104f2fbb49a6ac04e04 to your computer and use it in GitHub Desktop.
Save aeciopires/ba64d72f97966104f2fbb49a6ac04e04 to your computer and use it in GitHub Desktop.
Ansible bash module boilerplate
# Source arguments from Ansible
# These are passed into the module as $1 with a key=value format
# Sourcing this file sets the variables defined in the Ansible module
# Note that variables that are unused in the module are silently ignored
source $1
# Helper function to fail the module with the specified error
# This can accept $@ in printf for the full error
# Be aware that this may expose more information than desired
# Can also just directly echo a failure with the same JSON structure and exit 1
fail_module() {
printf '{"failed": true, "msg": "%s"}' "$1"
exit 1
# Helper function to report changed true or false
# Can also just directly output '{"changed": trueorfalse}' and omit this function
changed() {
printf '{"changed": %s}' "$1"
# Helper function to set a default value for a variable of the given name if it is not set through Ansible
default() {
if [ -z "$1" ]
# Helper function to fail if a variable of the given name is not set
require() {
if [ -z "${!1}" ]
printf '{"failed": true, "msg": "%s must be defined"}' "$1"
exit 1
# Check whether the action needs to occur then attempt the action
# Use a conditional with the changed or fail_module helper functions
# if no_action_is_needed
# changed false
# elif output=$(try_my_action)
# changed true
# else
# fail_module "my_action failed for reason $output"
# fi
# Example usage for creating a MySQL table
# Require the arguments of "username", "password", and "table" to be set
for argument in "username password table"
require $argument
# Set a default for a few arguments
default database mydatabase
default host localhost
# Use any given bash tools to validate that the command has run successfully or failed
# Echo JSON output for changed: false or changed: true which will be reflected in Ansible output
# To preserve idempotence, test whether a command needs to run before executing a changing command
if mysql $database -u $username -p $password -h $host -e "desc $table"
changed false
elif output=$(mysql $database -u $username -p $password -h $host -e "CREATE TABLE $table(id INT)")
changed true
fail_module "Failed to create table: $table, reason: $output"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment