Last active
January 26, 2024 18:43
-
-
Save ball6847/64a35e289df6f8249e381b9f095a2157 to your computer and use it in GitHub Desktop.
Parse ansible module args in Deno
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function parseAnsibleArgs(argsStr: string) { | |
const parsedArgs: Record<string, string | boolean | string[] | null> = {}; | |
const argRegex = /(\S+)=('[^']*'|[^ ]+)/g; | |
const matches = argsStr.matchAll(argRegex); | |
for (const match of matches) { | |
const key = match[1]; | |
let value = match[2]; | |
if (value === "None") { | |
parsedArgs[key] = null; | |
} else if (value.startsWith("'") && value.endsWith("'")) { | |
parsedArgs[key] = value.slice(1, -1); | |
} else if ( | |
value.toLowerCase() === "true" || value.toLowerCase() === "false" | |
) { | |
parsedArgs[key] = value.toLowerCase() === "true"; | |
} else if (value.startsWith("[") && value.endsWith("]")) { | |
// Remove brackets and split by comma and space | |
parsedArgs[key] = value.slice(1, -1).split(/,\s*/); | |
} else { | |
parsedArgs[key] = value; | |
} | |
} | |
return parsedArgs; | |
} | |
export function readAnsibleArgs<T = Record<string, any>>() { | |
const rawArgs = Deno.readTextFileSync(Deno.args[0]); | |
const args = parseAnsibleArgs(rawArgs); | |
return args as T; | |
} | |
export function writeAnsibleResult(result: Record<string, any>) { | |
const out = new TextEncoder().encode(JSON.stringify(result, null, 2)); | |
Deno.stdout.writeSync(out); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env -S deno run --allow-read | |
import { | |
readAnsibleArgs, | |
writeAnsibleResult, | |
} from "https://gist.githubusercontent.com/ball6847/64a35e289df6f8249e381b9f095a2157/raw/570fc05f338a5689b26f11353a8db03a791c0659/ansible.ts"; | |
type AnsibleArgs = { | |
msg: string; | |
}; | |
const args = readAnsibleArgs<AnsibleArgs>(); | |
const result = { | |
changed: false, | |
msg: "This is my output", | |
args: args.msg, | |
}; | |
writeAnsibleResult(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning, don't directly import ansible.ts directly from this gist as this could be changed anytime and for your security ofcourse.