Skip to content

Instantly share code, notes, and snippets.

@Faheetah
Last active March 18, 2022 01:01
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Faheetah/3dba8d86bb55a4e35726 to your computer and use it in GitHub Desktop.
Save Faheetah/3dba8d86bb55a4e35726 to your computer and use it in GitHub Desktop.
Ansible bash module boilerplate
#!/bin/bash
# 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" ]
then
${!1}=$2
fi
}
# Helper function to fail if a variable of the given name is not set
require() {
if [ -z "${!1}" ]
then
printf '{"failed": true, "msg": "%s must be defined"}' "$1"
exit 1
fi
}
# 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"
do
require $argument
done
# 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"
then
changed false
elif output=$(mysql $database -u $username -p $password -h $host -e "CREATE TABLE $table(id INT)")
changed true
else
fail_module "Failed to create table: $table, reason: $output"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment