Skip to content

Commit

Permalink
Merge pull request #207 from badele/hosts
Browse files Browse the repository at this point in the history
Add a require.network for manipulate the /etc/hosts file
  • Loading branch information
hobbestigrou committed Nov 2, 2016
2 parents 2978abb + d490e33 commit 26189aa
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions fabtools/require/__init__.py
Expand Up @@ -9,6 +9,7 @@
import fabtools.require.git
import fabtools.require.mercurial
import fabtools.require.mysql
import fabtools.require.network
import fabtools.require.nginx
import fabtools.require.nodejs
import fabtools.require.openvz
Expand Down
48 changes: 48 additions & 0 deletions fabtools/require/network.py
@@ -0,0 +1,48 @@
"""
Network packages
==================
"""
from __future__ import with_statement

import re

from fabric.api import hide
from fabric.contrib.files import sed, append

from fabtools.utils import run_as_root


def host(ipaddress, hostnames, use_sudo=False):
"""
Add a ipadress and hostname(s) in /etc/hosts file
Example::
from fabtools import require
require.network.host('127.0.0.1','hostname-a hostname-b')
"""

res = run_as_root('cat /etc/hosts | egrep "^%(ipaddress)s"' % locals())
if res.succeeded:
m = re.match('^%(ipaddress)s (.*)' % locals(), res)

# If ipadress allready exists
if m:
toadd = list()
hostnames = hostnames.split(' ')
inthehosts = m.group(1).split(' ')
for h in hostnames:
if h not in inthehosts:
toadd.append(h)

if len(toadd) > 0:
print "ADD: %s" % toadd
print res
hostline = "%s %s" % (res, ' '.join(toadd))

with hide('stdout', 'warnings'):
sed('/etc/hosts', res, hostline, use_sudo=use_sudo)
else:
hostline = "%s %s" % (res, hostnames)
append('/etc/hosts', hostline, use_sudo=use_sudo)

0 comments on commit 26189aa

Please sign in to comment.