From 318c956a22c4bebdf3613d37cd1e5eeacf869ba4 Mon Sep 17 00:00:00 2001 From: Rene Moser Date: Fri, 6 Sep 2013 13:23:53 +0200 Subject: [PATCH 1/3] added module host Add or remove entries in /etc/hosts using tasks: - host: ip=127.0.0.1 hostname=localhost aliases=foobar.com,localhost.foobar.com - host: ip=127.0.0.1 hostname=localhost state=present - host: ip=192.168.1.1 state=absent - host: hostname=localhost state=absent - host: ip=::1 hostname=localhost aliases=ip6-localhost,ip6-loopback --- system/host | 211 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 system/host diff --git a/system/host b/system/host new file mode 100644 index 00000000000..245b9404032 --- /dev/null +++ b/system/host @@ -0,0 +1,211 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# (c) 2013, René Moser +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . + +DOCUMENTATION = ''' +--- +module: host +author: René Moser +version_added: "1.3" +short_description: Add or remove entries in /etc/hosts +requirements: +description: + - Manage entries in /etc/hosts +options: + ip: + required: false + description: + - IP address. Required on state "present". + hostname: + required: false + description: + - name of host. Required on state "present". + aliases: + required: false + description: + - list of alias hostnames, comma separated. + state: + required: false + default: "present" + choices: [ present, absent ] + description: + - Whether the entries should be present or not in /etc/hosts. +''' + +EXAMPLES = ''' +# Example host command from Ansible Playbooks +- host: ip=127.0.0.1 hostname=localhost aliases=foobar.com,localhost.foobar.com +- host: ip=127.0.0.1 hostname=localhost state=present +- host: ip=192.168.1.1 state=absent +- host: hostname=localhost state=absent +- host: ip=::1 hostname=localhost aliases=ip6-localhost,ip6-loopback +''' + +import os +import tempfile +import fileinput +import syslog + +class Host(object): + + HOSTSFILE = '/etc/hosts' + + def __init__(self, module): + self.module = module + self.state = module.params['state'] + self.ip = module.params['ip'] + self.hostname = module.params['hostname'] + self.aliases = module.params['aliases'] + self.changed = False + self.ip_matches = False + self.hostname_matches = False + self.aliases_matches = False + self.has_aliases = False + self.found_on_line = -1 + self.syslogging = False + + def validate_has_hostname_on_present(self): + err = '' + if self.state == 'present' and not (self.hostname and self.ip): + err = "Error: No param 'hostnames' or 'ip' given in state 'present'." + return err + + def validate_has_ip_or_hostname_on_absent(self): + err = '' + if self.state == 'absent': + if not (self.hostname or self.ip): + err = "Error: Either param 'hostnames' or 'ip' must be given in state 'absent'." + if self.hostname and self.ip: + err = "Error: Either param 'hostnames' or 'ip' must be given in state 'absent'." + return err + + def log(self, msg): + if self.syslogging: + syslog.openlog('ansible-%s' % os.path.basename(__file__)) + syslog.syslog(syslog.LOG_NOTICE, '' + msg) + + def proceed_hosts_entries(self): + + f = open(self.HOSTSFILE,'rb') + self.lines = f.readlines() + f.close() + + for lineno, line in enumerate(self.lines): + if line.startswith("#"): + continue + + ip = line.split()[0:1] + hostname = line.split()[1:2] + aliases = ','.join(line.split()[2:]) + + if self.ip and self.ip in ip: + self.ip_matches = True + self.found_on_line = lineno + self.log(self.ip + ' found on line') + + if self.hostname and self.hostname in hostname: + self.hostname_matches = True + self.found_on_line = lineno + self.log(self.hostname + ' found on line') + + # only look at aliases if we found hostname or ip + if self.hostname_matches or self.ip_matches: + if aliases: + self.log('aliases: ' + aliases) + self.has_aliases = True + if self.aliases and self.aliases == aliases: + self.aliases_matches = True + break + + def full_entry_exists(self): + if self.has_aliases and not self.aliases_matches: + return False + return self.ip_matches and self.hostname_matches + + def entry_exists(self): + return self.ip_matches or self.hostname_matches + + def remove_entry(self): + self.lines.pop(self.found_on_line) + + def add_entry(self): + aliases = '' + if self.aliases: + aliases = self.aliases.replace(',',' ') + host_entry = self.ip + " " + self.hostname + " " + aliases + "\n" + if self.entry_exists(): + self.lines[self.found_on_line] = host_entry + else: + self.lines.extend(host_entry) + + def write_changes(self): + tmpfd, tmpfile = tempfile.mkstemp() + f = os.fdopen(tmpfd,'wb') + f.writelines(self.lines) + f.close() + self.module.atomic_move(tmpfile, self.HOSTSFILE) + self.changed = True + +def main(): + module = AnsibleModule( + argument_spec = dict( + state=dict(default='present', choices=['present', 'absent'], type='str'), + ip=dict(default=None, type='str'), + hostname=dict(default=None, type='str'), + aliases=dict(default=None, type='str'), + ), + supports_check_mode=True + ) + + result = {} + host = Host(module) + result['state'] = host.state + + err = host.validate_has_hostname_on_present() + if err: + module.fail_json(msg=err) + + err = host.validate_has_ip_or_hostname_on_absent() + if err: + module.fail_json(msg=err) + + host.proceed_hosts_entries() + if host.state == 'present': + if not host.full_entry_exists(): + host.log('Entry does not fully exist or may be missing.') + if module.check_mode: + module.exit_json(changed=True) + host.log('Adding or replacing entry.') + host.add_entry() + host.write_changes() + + elif host.state == 'absent': + if host.entry_exists(): + host.log('IP entry exists, removing.') + if module.check_mode: + module.exit_json(changed=True) + host.remove_entry() + host.write_changes() + + result['changed'] = host.changed + module.exit_json(**result) + +# include magic from lib/ansible/module_common.py +#<> +main() From 9f5d8f8482f44aa55d76f7bd5b15c2cc9b932daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Moser?= Date: Sun, 15 Sep 2013 14:55:53 +0200 Subject: [PATCH 2/3] host: updated version_added --- system/host | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/host b/system/host index 245b9404032..17c3fac9307 100644 --- a/system/host +++ b/system/host @@ -22,7 +22,7 @@ DOCUMENTATION = ''' --- module: host author: René Moser -version_added: "1.3" +version_added: "1.4" short_description: Add or remove entries in /etc/hosts requirements: description: From d2d6b20d9983ce40ed68d9f282c617c9db1e0048 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Moser?= Date: Fri, 20 Sep 2013 22:50:03 +0200 Subject: [PATCH 3/3] host: code cleanup --- system/host | 66 ++++++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/system/host b/system/host index 17c3fac9307..21f4e036a4d 100644 --- a/system/host +++ b/system/host @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2013, René Moser @@ -23,7 +23,7 @@ DOCUMENTATION = ''' module: host author: René Moser version_added: "1.4" -short_description: Add or remove entries in /etc/hosts +short_description: Add or remove entries in /etc/hosts. requirements: description: - Manage entries in /etc/hosts @@ -60,7 +60,6 @@ EXAMPLES = ''' import os import tempfile import fileinput -import syslog class Host(object): @@ -72,13 +71,12 @@ class Host(object): self.ip = module.params['ip'] self.hostname = module.params['hostname'] self.aliases = module.params['aliases'] - self.changed = False - self.ip_matches = False - self.hostname_matches = False - self.aliases_matches = False - self.has_aliases = False - self.found_on_line = -1 - self.syslogging = False + + self._ip_matches = False + self._hostname_matches = False + self._aliases_matches = False + self._has_aliases = False + self._found_on_line = -1 def validate_has_hostname_on_present(self): err = '' @@ -95,18 +93,13 @@ class Host(object): err = "Error: Either param 'hostnames' or 'ip' must be given in state 'absent'." return err - def log(self, msg): - if self.syslogging: - syslog.openlog('ansible-%s' % os.path.basename(__file__)) - syslog.syslog(syslog.LOG_NOTICE, '' + msg) - def proceed_hosts_entries(self): f = open(self.HOSTSFILE,'rb') - self.lines = f.readlines() + self._hostsfile_lines = f.readlines() f.close() - for lineno, line in enumerate(self.lines): + for lineno, line in enumerate(self._hostsfile_lines): if line.startswith("#"): continue @@ -115,34 +108,31 @@ class Host(object): aliases = ','.join(line.split()[2:]) if self.ip and self.ip in ip: - self.ip_matches = True - self.found_on_line = lineno - self.log(self.ip + ' found on line') + self._ip_matches = True + self._found_on_line = lineno if self.hostname and self.hostname in hostname: - self.hostname_matches = True - self.found_on_line = lineno - self.log(self.hostname + ' found on line') + self._hostname_matches = True + self._found_on_line = lineno # only look at aliases if we found hostname or ip - if self.hostname_matches or self.ip_matches: + if self._hostname_matches or self._ip_matches: if aliases: - self.log('aliases: ' + aliases) - self.has_aliases = True + self._has_aliases = True if self.aliases and self.aliases == aliases: - self.aliases_matches = True + self._aliases_matches = True break def full_entry_exists(self): - if self.has_aliases and not self.aliases_matches: + if self._has_aliases and not self._aliases_matches: return False - return self.ip_matches and self.hostname_matches + return self._ip_matches and self.hostname_matches def entry_exists(self): - return self.ip_matches or self.hostname_matches + return self._ip_matches or self.hostname_matches def remove_entry(self): - self.lines.pop(self.found_on_line) + self._hostsfile_lines.pop(self._found_on_line) def add_entry(self): aliases = '' @@ -150,17 +140,16 @@ class Host(object): aliases = self.aliases.replace(',',' ') host_entry = self.ip + " " + self.hostname + " " + aliases + "\n" if self.entry_exists(): - self.lines[self.found_on_line] = host_entry + self._hostsfile_lines[self._found_on_line] = host_entry else: - self.lines.extend(host_entry) + self._hostsfile_lines.extend(host_entry) def write_changes(self): tmpfd, tmpfile = tempfile.mkstemp() f = os.fdopen(tmpfd,'wb') - f.writelines(self.lines) + f.writelines(self._hostsfile_lines) f.close() self.module.atomic_move(tmpfile, self.HOSTSFILE) - self.changed = True def main(): module = AnsibleModule( @@ -176,6 +165,7 @@ def main(): result = {} host = Host(module) result['state'] = host.state + result['changed'] = false err = host.validate_has_hostname_on_present() if err: @@ -188,22 +178,20 @@ def main(): host.proceed_hosts_entries() if host.state == 'present': if not host.full_entry_exists(): - host.log('Entry does not fully exist or may be missing.') if module.check_mode: module.exit_json(changed=True) - host.log('Adding or replacing entry.') host.add_entry() host.write_changes() + result['changed'] = True elif host.state == 'absent': if host.entry_exists(): - host.log('IP entry exists, removing.') if module.check_mode: module.exit_json(changed=True) host.remove_entry() host.write_changes() + result['changed'] = True - result['changed'] = host.changed module.exit_json(**result) # include magic from lib/ansible/module_common.py