ntp fix.
[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 AnsibleModule
4 import os
5 import re
6
7 if __name__ == '__main__':
8     fields = {
9             "new_ntp_servers": {"required":True, "type": list},
10     }
11
12     module = AnsibleModule(argument_spec=fields)
13
14     new_ntp_servers = module.params['new_ntp_servers']
15
16     ntp_file = "/etc/ntp.conf"
17     tmp_file = "/etc/ntp.conf.mod"
18
19     try:
20         filter = re.compile('^server.*')
21         lines = []
22         with open(ntp_file, 'r') as f:
23             lines = f.readlines()
24
25         updated = []
26         if lines:
27             for line in lines:
28                 if filter.match(line):
29                     continue
30                 else:
31                     updated.append(line)
32
33             with open(tmp_file, 'w') as f:
34                 for line in updated:
35                     f.write(line)
36
37                 #append the new server configuration
38                 for server in new_ntp_servers:
39                     f.write("server " + server + "\n");
40
41             os.rename(tmp_file, ntp_file)
42
43             module.exit_json(changed=True)
44                     
45     except Exception as exp:
46         module.fail_json(msg=str(ex))