Skip to content

Instantly share code, notes, and snippets.

@iinm
Created May 14, 2021 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iinm/f0004f20190278ac09a7808e30c5661b to your computer and use it in GitHub Desktop.
Save iinm/f0004f20190278ac09a7808e30c5661b to your computer and use it in GitHub Desktop.
Ansible module template in Bash
#!/usr/bin/env bash
# cp <module_name>.sh ./library/
# ansible localhost -M ./library/ -m <module_name> -a 'arg1=foo' --check -vvv
set -eu -o pipefail
# Arguments are passed as a file
arg_file="$(dirname "${BASH_SOURCE[0]}")/args"
# Check mode?
is_check_mode=yes
if grep -q '_ansible_check_mode=False' "$arg_file"; then
is_check_mode=no
fi
# Get arguments
arg1=$(sed -E 's,.* foo=([^ ]+).*,\1,' "$arg_file")
# FIXME
changed=true
before=foo
after=bar
escape_json_string() {
local double_quote_escaped
double_quote_escaped="$(cat - | sed -E 's,",\\",g')"
echo -n "${double_quote_escaped/$'\n'/\\n}"
}
cat << JSON
{
"changed": $changed,
"failed": false,
"msg": "Hello, World!",
"diff": {
"before": "$(escape_json_string <<< $before)",
"after": "$(escape_json_string <<< $after)"
}
}
JSON
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment