Add backups to lineinfile

This commit is contained in:
Daniel Hokka Zakrisson 2012-09-04 14:20:52 +02:00
parent dfcb9d3c2d
commit 2a8b92954f

View file

@ -21,7 +21,7 @@
import re import re
import os import os
def present(module, name, regexp, line, insertafter): def present(module, name, regexp, line, insertafter, backup):
f = open(name, 'rb') f = open(name, 'rb')
lines = f.readlines() lines = f.readlines()
f.close() f.close()
@ -69,13 +69,15 @@ def present(module, name, regexp, line, insertafter):
changed = True changed = True
if changed: if changed:
if backup:
module.backuplocal(name)
f = open(name, 'wb') f = open(name, 'wb')
f.writelines(lines) f.writelines(lines)
f.close() f.close()
module.exit_json(changed=changed, msg=msg) module.exit_json(changed=changed, msg=msg)
def absent(module, name, regexp): def absent(module, name, regexp, backup):
f = open(name, 'rb') f = open(name, 'rb')
lines = f.readlines() lines = f.readlines()
f.close() f.close()
@ -90,6 +92,8 @@ def absent(module, name, regexp):
lines = filter(matcher, lines) lines = filter(matcher, lines)
changed = len(found) > 0 changed = len(found) > 0
if changed: if changed:
if backup:
module.backuplocal(name)
f = open(name, 'wb') f = open(name, 'wb')
f.writelines(lines) f.writelines(lines)
f.close() f.close()
@ -103,18 +107,20 @@ def main():
regexp=dict(required=True), regexp=dict(required=True),
line=dict(aliases=['value']), line=dict(aliases=['value']),
insertafter=dict(default='EOF'), insertafter=dict(default='EOF'),
backup=dict(default=False, choices=BOOLEANS),
), ),
) )
params = module.params params = module.params
backup = module.boolean(module.params.get('backup', False))
if params['state'] == 'present': if params['state'] == 'present':
if 'line' not in params: if 'line' not in params:
module.fail_json(msg='line= is required with state=present') module.fail_json(msg='line= is required with state=present')
present(module, params['name'], params['regexp'], params['line'], present(module, params['name'], params['regexp'], params['line'],
params['insertafter']) params['insertafter'], backup)
else: else:
absent(module, params['name'], params['regexp']) absent(module, params['name'], params['regexp'], backup)
# this is magic, see lib/ansible/module_common.py # this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>> #<<INCLUDE_ANSIBLE_MODULE_COMMON>>