I'm pretty new to understanding a few Python things, but this is taking me hours now, so i might need a bit help. I'm creating an custom filter plugin for Ansible. This is an example Playbook:
hosts: host1:host2
tasks:
- name: random numbers between 0-10
command: shuf -i 0-10 -n 1
register: out
until: out | customfilter1(file, ansible_hostname) or out.stdout == "2"
retries: 50
delay: 0
vars:
file: ./file.json
It makes random numbers and does that until the random number is matching 2. Here is the customfilter1 which should make a nice json out of it:
#!/usr/bin/python
import os
import json
class FilterModule(object):
def filters(self):
return {
'customfilter1': self.customfilter1
}
def customfilter1(self, obj, file, ansible_hostname):
if obj["attempts"] == 1:
print(obj)
newdata = {ansible_hostname: {"Attempts": {obj["attempts"]: {"Result": obj["stdout"]}}}}
json_file = json.dumps(newdata, sort_keys=False, indent=2)
with open(file, 'a') as f:
f.write(json_file)
else:
with open(file) as f:
data = json.load(f)
data[ansible_hostname]["Attempts"][obj["attempts"]] = {"Result": obj["stdout"]}
json_file = json.dumps(data, sort_keys=False, indent=2)
with open(file, 'w') as f:
f.write(json_file)
return False
I had like 200 versions of this so this is the most recent one that is working pretty good for a single host, but when using it for multiple hosts the second one drop
fatal: [ampere]: FAILED! => {"msg": "The conditional check 'out | customfilter1(file, ansible_hostname) or out.stdout == \"2\"' failed. The error was: Extra data: line 21 column 2 (char 273)"}
The json file contains this:
{
"host1: {
"Attempts": {
"1": {
"Result": "4"
},
"2": {
"Result": "5"
},
"3": {
"Result": "7"
},
"4": {
"Result": "0"
},
"5": {
"Result": "2"
}
}
}
}{
"host2": {
"Attempts": {
"1": {
"Result": "5"
}
}
}
}
The error seems to appear in the line with the two curly brackets "}{"
It might be a different issue but is there a way to get around of this?