-
Notifications
You must be signed in to change notification settings - Fork 1
/
simplefile.py
107 lines (85 loc) · 2.71 KB
/
simplefile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import os
from tempfile import gettempdir
from ansible.module_utils.basic import AnsibleModule
class BasicFile(object):
def __init__(self, path):
self.path = path
def exists(self):
return os.path.exists(self.path)
def touch(self):
pass
def remove(self):
pass
class CheckModeFile(BasicFile):
def __init__(self, path):
super(CheckModeFile, self).__init__(path)
def touch(self):
return not self.exists()
def remove(self):
return self.exists()
class File(BasicFile):
def __init__(self, path):
super(File, self).__init__(path)
def touch(self):
with open(self.path, 'a'):
os.utime(self.path, None)
def remove(self):
if self.exists():
os.remove(self.path)
return True
else:
return False
class SimpleFileModule(object):
def __init__(self, expected, check_mode):
self.expected = expected
self.check_mode = check_mode
self.file = self.__file(expected['path'])
def __file(self, path):
if self.check_mode:
return CheckModeFile(path)
else:
return File(path)
def ensure(self):
if self.expected['state'] == 'present':
return self.__ensure_present()
else:
return self.__ensure_absent()
def __ensure_present(self):
diff = self.__create_diff()
if self.file.exists():
return (False, diff, self.expected)
else:
self.file.touch()
return (True, diff, self.expected)
def __ensure_absent(self):
diff = self.__create_diff()
return (self.file.remove(), diff, self.expected)
def __create_diff(self):
path = self.expected['path']
act_state, exp_state = self.__file_state(), self.expected['state']
diff = dict(before=dict(path=path), after=dict(path=path))
if act_state != exp_state:
diff['before']['state'] = act_state
diff['after']['state'] = exp_state
return diff
def __file_state(self):
return 'present' if self.file.exists() else 'absent'
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(required=True, type='path'),
state=dict(choices=['present', 'absent'], default=None)
),
supports_check_mode=True
)
simplefile = SimpleFileModule(
expected=dict(
path=module.params['path'],
state=module.params['state']
),
check_mode=module.check_mode
)
changed, diff, params = simplefile.ensure()
module.exit_json(changed=changed, diff=diff, simplefile=params)
if __name__ == '__main__':
main()