Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #207 from badele/hosts
Add a require.network for manipulate the /etc/hosts file
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) |