7b694e6ab3f56b425fd7141a165ced54c3e98b60
[ta/infra-ansible.git] / roles / ntp-utils / library / change_master_servers.py
1 #!/bin/env python
2 # pylint: skip-file
3 from ansible.module_utils.basic import *
4 import os, json
5 import re, sys
6 import syslog
7 import re
8
9 if __name__ == '__main__':
10     fields = {
11             "new_ntp_servers": {"required":True, "type": list},
12     }
13
14     module = AnsibleModule(argument_spec=fields)
15
16     new_ntp_servers = module.params['new_ntp_servers']
17
18     ntp_file = "/etc/ntp.conf"
19     tmp_file = "/etc/ntp.conf.mod"
20
21     try:
22         filter = re.compile('^server.*')
23         lines = []
24         with open(ntp_file, 'r') as f:
25             lines = f.readlines()
26
27         updated = []
28         if lines:
29             for line in lines:
30                 if filter.match(line):
31                     continue
32                 else:
33                     updated.append(line)
34
35             with open(tmp_file, 'w') as f:
36                 for line in updated:
37                     f.write(line)
38
39                 #append the new server configuration
40                 for server in new_ntp_servers:
41                     f.write("server " + server + "\n");
42
43             os.rename(tmp_file, ntp_file)
44
45             module.exit_json(changed=True)
46                     
47     except Exception as exp:
48         module.fail_json(msg=str(ex))