0

I wrote an ansible module is bash. It is working fine, but if want to pass arguments to that module and read them in the bash module how can I do that .. please help

- name: get top processes consuming high cpu
  gettopprocesses:
    numberofprocesses: 5

In library I have bash script library/gettopprocesses.sh

#!/bin/bash
TPCPU=$(ps aux --sort -%cpu | head -${numberofprocesses}
echo "{\"changed\": false, "\msg\": {"$TPCPU"}}"
exit 0
  • You mean read module arguments from a module written in bash ? – KrishnaR Apr 13 '22 at 08:46
  • Yes, I tried standard arguments in bash.. but in ansible module args we pass argument key and its value.. I want read both –  Apr 13 '22 at 08:48
  • could you show a sample reproductible... – Frenchy Apr 13 '22 at 08:53
  • Writting modules in bash is not part of the documentation anymore. The modern way is to write your module in python and use the dedicated libraries/modules to get your params. Meanwhile, you can find old doc/tutorials which explain how to proceed. An example [here](https://ansible-tutorial.schoolofdevops.com/custom_modules/#writing-module-with-bash). Basically, your script receives a single parameter containing all the module options. Sourcing that param (i.e. `source $1`) is suppose to create the corresponding variables in your script context. – Zeitounator Apr 13 '22 at 09:47

1 Answers1

2

I write your bask like this: you have to add source $1 to specify you have args

#!/bin/bash
source $1
NUMBERPROC=$numberofprocesses
TPCPU=$(ps aux --sort -%cpu | head -${NUMBERPROC})

printf '{"changed": %s, "msg": "%s", "contents": %s}' "false" "$TPCPU" "contents"
exit 0

You could add a test to check if right arg is given:

#!/bin/bash
source $1

if [ -z "$numberofprocesses" ]; then
    printf '{"failed": true, "msg": "missing required arguments: numberofprocesses"}'
    exit 1
fi

NUMBERPROC=$numberofprocesses
TPCPU=$(ps aux --sort -%cpu | head -${NUMBERPROC})

printf '{"changed": %s, "msg": "%s", "contents": %s}' "false" "$TPCPU" "contents"
exit 0
Dharman
  • 30,962
  • 25
  • 85
  • 135
Frenchy
  • 16,386
  • 3
  • 16
  • 39