如何获取用 bash 编写的 ansible 模块的参数?

How to get args for an ansible module written in bash?

我写了一个ansible模块是bash。它工作正常,但如果想将参数传递给该模块并在 bash 模块中读取它们,我该怎么做......请帮助

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

在库中我有 bash 脚本 library/gettopprocesses.sh

#!/bin/bash
TPCPU=$(ps aux --sort -%cpu | head -${numberofprocesses}
echo "{\"changed\": false, "\msg\": {"$TPCPU"}}"
exit 0

我这样写你的 bask:你必须添加 source $1 来指定你有 args

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

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

您可以添加一个测试来检查是否给出了正确的 arg:

#!/bin/bash
source 

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