summaryrefslogtreecommitdiff
path: root/cloudinit/CloudConfig
diff options
context:
space:
mode:
Diffstat (limited to 'cloudinit/CloudConfig')
-rw-r--r--cloudinit/CloudConfig/__init__.py89
-rw-r--r--cloudinit/CloudConfig/cc_apt_update_upgrade.py55
-rw-r--r--cloudinit/CloudConfig/cc_bootcmd.py6
-rw-r--r--cloudinit/CloudConfig/cc_byobu.py9
-rw-r--r--cloudinit/CloudConfig/cc_chef.py39
-rw-r--r--cloudinit/CloudConfig/cc_disable_ec2_metadata.py4
-rw-r--r--cloudinit/CloudConfig/cc_final_message.py10
-rw-r--r--cloudinit/CloudConfig/cc_foo.py2
-rw-r--r--cloudinit/CloudConfig/cc_grub_dpkg.py25
-rw-r--r--cloudinit/CloudConfig/cc_keys_to_console.py10
-rw-r--r--cloudinit/CloudConfig/cc_landscape.py2
-rw-r--r--cloudinit/CloudConfig/cc_locale.py7
-rw-r--r--cloudinit/CloudConfig/cc_mcollective.py32
-rw-r--r--cloudinit/CloudConfig/cc_mounts.py52
-rw-r--r--cloudinit/CloudConfig/cc_phone_home.py12
-rw-r--r--cloudinit/CloudConfig/cc_puppet.py18
-rw-r--r--cloudinit/CloudConfig/cc_resizefs.py17
-rw-r--r--cloudinit/CloudConfig/cc_rightscale_userdata.py10
-rw-r--r--cloudinit/CloudConfig/cc_rsyslog.py9
-rw-r--r--cloudinit/CloudConfig/cc_runcmd.py6
-rw-r--r--cloudinit/CloudConfig/cc_scripts_per_boot.py2
-rw-r--r--cloudinit/CloudConfig/cc_scripts_per_instance.py2
-rw-r--r--cloudinit/CloudConfig/cc_scripts_per_once.py2
-rw-r--r--cloudinit/CloudConfig/cc_scripts_user.py2
-rw-r--r--cloudinit/CloudConfig/cc_set_hostname.py6
-rw-r--r--cloudinit/CloudConfig/cc_set_passwords.py34
-rw-r--r--cloudinit/CloudConfig/cc_ssh.py30
-rw-r--r--cloudinit/CloudConfig/cc_ssh_import_id.py9
-rw-r--r--cloudinit/CloudConfig/cc_timezone.py9
-rw-r--r--cloudinit/CloudConfig/cc_update_etc_hosts.py6
-rw-r--r--cloudinit/CloudConfig/cc_update_hostname.py17
31 files changed, 302 insertions, 231 deletions
diff --git a/cloudinit/CloudConfig/__init__.py b/cloudinit/CloudConfig/__init__.py
index f5c4143c..76cafebd 100644
--- a/cloudinit/CloudConfig/__init__.py
+++ b/cloudinit/CloudConfig/__init__.py
@@ -25,7 +25,7 @@ import os
import subprocess
import time
-per_instance= cloudinit.per_instance
+per_instance = cloudinit.per_instance
per_always = cloudinit.per_always
per_once = cloudinit.per_once
@@ -33,7 +33,7 @@ class CloudConfig():
cfgfile = None
cfg = None
- def __init__(self,cfgfile, cloud=None, ds_deps=None):
+ def __init__(self, cfgfile, cloud=None, ds_deps=None):
if cloud == None:
self.cloud = cloudinit.CloudInit(ds_deps)
self.cloud.get_data_source()
@@ -41,15 +41,17 @@ class CloudConfig():
self.cloud = cloud
self.cfg = self.get_config_obj(cfgfile)
- def get_config_obj(self,cfgfile):
+ def get_config_obj(self, cfgfile):
try:
cfg = util.read_conf(cfgfile)
except:
# TODO: this 'log' could/should be passed in
- cloudinit.log.critical("Failed loading of cloud config '%s'. Continuing with empty config\n" % cfgfile)
+ cloudinit.log.critical("Failed loading of cloud config '%s'. "
+ "Continuing with empty config\n" % cfgfile)
cloudinit.log.debug(traceback.format_exc() + "\n")
cfg = None
- if cfg is None: cfg = { }
+ if cfg is None:
+ cfg = { }
try:
ds_cfg = self.cloud.datasource.get_config_obj()
@@ -57,12 +59,12 @@ class CloudConfig():
ds_cfg = { }
cfg = util.mergedict(cfg, ds_cfg)
- return(util.mergedict(cfg,self.cloud.cfg))
+ return(util.mergedict(cfg, self.cloud.cfg))
def handle(self, name, args, freq=None):
try:
- mod = __import__("cc_" + name.replace("-","_"),globals())
- def_freq = getattr(mod, "frequency",per_instance)
+ mod = __import__("cc_" + name.replace("-", "_"), globals())
+ def_freq = getattr(mod, "frequency", per_instance)
handler = getattr(mod, "handle")
if not freq:
@@ -75,23 +77,24 @@ class CloudConfig():
# reads a cloudconfig module list, returns
# a 2 dimensional array suitable to pass to run_cc_modules
-def read_cc_modules(cfg,name):
- if name not in cfg: return([])
+def read_cc_modules(cfg, name):
+ if name not in cfg:
+ return([])
module_list = []
# create 'module_list', an array of arrays
# where array[0] = config
# array[1] = freq
# array[2:] = arguemnts
for item in cfg[name]:
- if isinstance(item,str):
+ if isinstance(item, str):
module_list.append((item,))
- elif isinstance(item,list):
+ elif isinstance(item, list):
module_list.append(item)
else:
raise TypeError("failed to read '%s' item in config")
return(module_list)
-def run_cc_modules(cc,module_list,log):
+def run_cc_modules(cc, module_list, log):
failures = []
for cfg_mod in module_list:
name = cfg_mod[0]
@@ -109,7 +112,7 @@ def run_cc_modules(cc,module_list,log):
except:
log.warn(traceback.format_exc())
log.error("config handling of %s, %s, %s failed\n" %
- (name,freq,run_args))
+ (name, freq, run_args))
failures.append(name)
return(failures)
@@ -126,24 +129,27 @@ def run_cc_modules(cc,module_list,log):
# None if if none is given
def get_output_cfg(cfg, mode="init"):
ret = [ None, None ]
- if not 'output' in cfg: return ret
+ if not 'output' in cfg:
+ return ret
outcfg = cfg['output']
if mode in outcfg:
modecfg = outcfg[mode]
else:
- if 'all' not in outcfg: return ret
+ if 'all' not in outcfg:
+ return ret
# if there is a 'all' item in the output list
# then it applies to all users of this (init, config, final)
modecfg = outcfg['all']
# if value is a string, it specifies stdout and stderr
- if isinstance(modecfg,str):
+ if isinstance(modecfg, str):
ret = [ modecfg, modecfg ]
# if its a list, then we expect (stdout, stderr)
- if isinstance(modecfg,list):
- if len(modecfg) > 0: ret[0] = modecfg[0]
+ if isinstance(modecfg, list):
+ if len(modecfg) > 0:
+ ret[0] = modecfg[0]
if len(modecfg) > 1:
ret[1] = modecfg[1]
@@ -157,16 +163,18 @@ def get_output_cfg(cfg, mode="init"):
# if err's entry == "&1", then make it same as stdout
# as in shell syntax of "echo foo >/dev/null 2>&1"
- if ret[1] == "&1": ret[1] = ret[0]
+ if ret[1] == "&1":
+ ret[1] = ret[0]
swlist = [ ">>", ">", "|" ]
for i in range(len(ret)):
- if not ret[i]: continue
+ if not ret[i]:
+ continue
val = ret[i].lstrip()
found = False
for s in swlist:
if val.startswith(s):
- val = "%s %s" % (s,val[len(s):].strip())
+ val = "%s %s" % (s, val[len(s):].strip())
found = True
break
if not found:
@@ -186,12 +194,13 @@ def get_output_cfg(cfg, mode="init"):
#
# with a '|', arguments are passed to shell, so one level of
# shell escape is required.
-def redirect_output(outfmt,errfmt, o_out=sys.stdout, o_err=sys.stderr):
+def redirect_output(outfmt, errfmt, o_out=sys.stdout, o_err=sys.stderr):
if outfmt:
- (mode, arg) = outfmt.split(" ",1)
+ (mode, arg) = outfmt.split(" ", 1)
if mode == ">" or mode == ">>":
owith = "ab"
- if mode == ">": owith = "wb"
+ if mode == ">":
+ owith = "wb"
new_fp = open(arg, owith)
elif mode == "|":
proc = subprocess.Popen(arg, shell=True, stdin=subprocess.PIPE)
@@ -206,10 +215,11 @@ def redirect_output(outfmt,errfmt, o_out=sys.stdout, o_err=sys.stderr):
return
if errfmt:
- (mode, arg) = errfmt.split(" ",1)
+ (mode, arg) = errfmt.split(" ", 1)
if mode == ">" or mode == ">>":
owith = "ab"
- if mode == ">": owith = "wb"
+ if mode == ">":
+ owith = "wb"
new_fp = open(arg, owith)
elif mode == "|":
proc = subprocess.Popen(arg, shell=True, stdin=subprocess.PIPE)
@@ -222,31 +232,32 @@ def redirect_output(outfmt,errfmt, o_out=sys.stdout, o_err=sys.stderr):
return
def run_per_instance(name, func, args, clear_on_fail=False):
- semfile = "%s/%s" % (cloudinit.get_ipath_cur("data"),name)
- if os.path.exists(semfile): return
+ semfile = "%s/%s" % (cloudinit.get_ipath_cur("data"), name)
+ if os.path.exists(semfile):
+ return
- util.write_file(semfile,str(time.time()))
+ util.write_file(semfile, str(time.time()))
try:
func(*args)
except:
- if clear_on_fail: os.unlink(semfile)
+ if clear_on_fail:
+ os.unlink(semfile)
raise
# apt_get top level command (install, update...), and args to pass it
-def apt_get(tlc,args=None):
+def apt_get(tlc, args=None):
if args is None:
args = []
- e=os.environ.copy()
- e['DEBIAN_FRONTEND']='noninteractive'
- cmd=[ 'apt-get',
- '--option', 'Dpkg::Options::=--force-confold', '--assume-yes',
- tlc ]
+ e = os.environ.copy()
+ e['DEBIAN_FRONTEND'] = 'noninteractive'
+ cmd = ['apt-get', '--option', 'Dpkg::Options::=--force-confold',
+ '--assume-yes', tlc]
cmd.extend(args)
- subprocess.check_call(cmd,env=e)
+ subprocess.check_call(cmd, env=e)
def update_package_sources():
run_per_instance("update-sources", apt_get, ("update",))
def install_packages(pkglist):
update_package_sources()
- apt_get("install",pkglist)
+ apt_get("install", pkglist)
diff --git a/cloudinit/CloudConfig/cc_apt_update_upgrade.py b/cloudinit/CloudConfig/cc_apt_update_upgrade.py
index 0cbe02d4..dea89d25 100644
--- a/cloudinit/CloudConfig/cc_apt_update_upgrade.py
+++ b/cloudinit/CloudConfig/cc_apt_update_upgrade.py
@@ -22,7 +22,7 @@ import os
import glob
import cloudinit.CloudConfig as cc
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
update = util.get_cfg_option_bool(cfg, 'apt_update', False)
upgrade = util.get_cfg_option_bool(cfg, 'apt_upgrade', False)
@@ -35,7 +35,7 @@ def handle(_name,cfg,cloud,log,_args):
if not util.get_cfg_option_bool(cfg, \
'apt_preserve_sources_list', False):
generate_sources_list(release, mirror)
- old_mir = util.get_cfg_option_str(cfg,'apt_old_mirror', \
+ old_mir = util.get_cfg_option_str(cfg, 'apt_old_mirror', \
"archive.ubuntu.com/ubuntu")
rename_apt_lists(old_mir, mirror)
@@ -46,7 +46,7 @@ def handle(_name,cfg,cloud,log,_args):
if proxy:
try:
contents = "Acquire::HTTP::Proxy \"%s\";\n"
- with open(proxy_filename,"w") as fp:
+ with open(proxy_filename, "w") as fp:
fp.write(contents % proxy)
except Exception as e:
log.warn("Failed to write proxy to %s" % proxy_filename)
@@ -69,7 +69,7 @@ def handle(_name,cfg,cloud,log,_args):
log.error("Failed to run debconf-set-selections")
log.debug(traceback.format_exc())
- pkglist = util.get_cfg_option_list_or_str(cfg,'packages',[])
+ pkglist = util.get_cfg_option_list_or_str(cfg, 'packages', [])
errors = [ ]
if update or len(pkglist) or upgrade:
@@ -102,26 +102,29 @@ def handle(_name,cfg,cloud,log,_args):
return(True)
def mirror2lists_fileprefix(mirror):
- string=mirror
+ string = mirror
# take of http:// or ftp://
- if string.endswith("/"): string=string[0:-1]
- pos=string.find("://")
+ if string.endswith("/"):
+ string = string[0:-1]
+ pos = string.find("://")
if pos >= 0:
- string=string[pos+3:]
- string=string.replace("/","_")
+ string = string[pos+3:]
+ string = string.replace("/", "_")
return string
-def rename_apt_lists(omirror,new_mirror,lists_d="/var/lib/apt/lists"):
+def rename_apt_lists(omirror, new_mirror, lists_d="/var/lib/apt/lists"):
- oprefix="%s/%s" % (lists_d,mirror2lists_fileprefix(omirror))
- nprefix="%s/%s" % (lists_d,mirror2lists_fileprefix(new_mirror))
- if(oprefix==nprefix): return
- olen=len(oprefix)
+ oprefix = "%s/%s" % (lists_d, mirror2lists_fileprefix(omirror))
+ nprefix = "%s/%s" % (lists_d, mirror2lists_fileprefix(new_mirror))
+ if(oprefix == nprefix):
+ return
+ olen = len(oprefix)
for filename in glob.glob("%s_*" % oprefix):
- os.rename(filename,"%s%s" % (nprefix, filename[olen:]))
+ os.rename(filename, "%s%s" % (nprefix, filename[olen:]))
def get_release():
- stdout, _stderr = subprocess.Popen(['lsb_release', '-cs'], stdout=subprocess.PIPE).communicate()
+ stdout, _stderr = subprocess.Popen(['lsb_release', '-cs'],
+ stdout=subprocess.PIPE).communicate()
return(stdout.strip())
def generate_sources_list(codename, mirror):
@@ -141,9 +144,10 @@ def add_sources(srclist, searchList=None):
elst.append([ "", "missing source" ])
continue
- source=ent['source']
+ source = ent['source']
if source.startswith("ppa:"):
- try: util.subp(["add-apt-repository",source])
+ try:
+ util.subp(["add-apt-repository", source])
except:
elst.append([source, "add-apt-repository failed"])
continue
@@ -151,7 +155,7 @@ def add_sources(srclist, searchList=None):
source = util.render_string(source, searchList)
if not ent.has_key('filename'):
- ent['filename']='cloud_config_sources.list'
+ ent['filename'] = 'cloud_config_sources.list'
if not ent['filename'].startswith("/"):
ent['filename'] = "%s/%s" % \
@@ -159,19 +163,22 @@ def add_sources(srclist, searchList=None):
if ( ent.has_key('keyid') and not ent.has_key('key') ):
ks = "keyserver.ubuntu.com"
- if ent.has_key('keyserver'): ks = ent['keyserver']
+ if ent.has_key('keyserver'):
+ ks = ent['keyserver']
try:
ent['key'] = util.getkeybyid(ent['keyid'], ks)
except:
- elst.append([source,"failed to get key from %s" % ks])
+ elst.append([source, "failed to get key from %s" % ks])
continue
if ent.has_key('key'):
- try: util.subp(('apt-key', 'add', '-'), ent['key'])
+ try:
+ util.subp(('apt-key', 'add', '-'), ent['key'])
except:
elst.append([source, "failed add key"])
- try: util.write_file(ent['filename'], source + "\n", omode="ab")
+ try:
+ util.write_file(ent['filename'], source + "\n", omode="ab")
except:
elst.append([source, "failed write to file %s" % ent['filename']])
@@ -189,7 +196,7 @@ def find_apt_mirror(cloud, cfg):
}
mirror = None
- cfg_mirror = cfg.get("apt_mirror",None)
+ cfg_mirror = cfg.get("apt_mirror", None)
if cfg_mirror:
mirror = cfg["apt_mirror"]
elif cfg.has_key("apt_mirror_search"):
diff --git a/cloudinit/CloudConfig/cc_bootcmd.py b/cloudinit/CloudConfig/cc_bootcmd.py
index fc925447..98a7a747 100644
--- a/cloudinit/CloudConfig/cc_bootcmd.py
+++ b/cloudinit/CloudConfig/cc_bootcmd.py
@@ -21,7 +21,7 @@ import tempfile
from cloudinit.CloudConfig import per_always
frequency = per_always
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
if not cfg.has_key("bootcmd"):
return
@@ -35,8 +35,8 @@ def handle(_name,cfg,cloud,log,_args):
raise
try:
- env=os.environ.copy()
- env['INSTANCE_ID']=cloud.get_instance_id()
+ env = os.environ.copy()
+ env['INSTANCE_ID'] = cloud.get_instance_id()
subprocess.check_call(['/bin/sh'], env=env, stdin=tmpf)
tmpf.close()
except:
diff --git a/cloudinit/CloudConfig/cc_byobu.py b/cloudinit/CloudConfig/cc_byobu.py
index dd510dda..04825521 100644
--- a/cloudinit/CloudConfig/cc_byobu.py
+++ b/cloudinit/CloudConfig/cc_byobu.py
@@ -19,13 +19,14 @@ import cloudinit.util as util
import subprocess
import traceback
-def handle(_name,cfg,_cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
if len(args) != 0:
value = args[0]
else:
- value = util.get_cfg_option_str(cfg,"byobu_by_default","")
+ value = util.get_cfg_option_str(cfg, "byobu_by_default", "")
- if not value: return
+ if not value:
+ return
if value == "user" or value == "system":
value = "enable-%s" % value
@@ -50,7 +51,7 @@ def handle(_name,cfg,_cloud,log,args):
shcmd = ""
if mod_user:
- user = util.get_cfg_option_str(cfg,"user","ubuntu")
+ user = util.get_cfg_option_str(cfg, "user", "ubuntu")
shcmd += " sudo -Hu \"%s\" byobu-launcher-%s" % (user, bl_inst)
shcmd += " || X=$(($X+1)); "
if mod_sys:
diff --git a/cloudinit/CloudConfig/cc_chef.py b/cloudinit/CloudConfig/cc_chef.py
index 977fe80f..4f740aff 100644
--- a/cloudinit/CloudConfig/cc_chef.py
+++ b/cloudinit/CloudConfig/cc_chef.py
@@ -23,9 +23,10 @@ import cloudinit.util as util
ruby_version_default = "1.8"
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
# If there isn't a chef key in the configuration don't do anything
- if not cfg.has_key('chef'): return
+ if not cfg.has_key('chef'):
+ return
chef_cfg = cfg['chef']
# ensure the chef directories we use exist
@@ -35,7 +36,8 @@ def handle(_name,cfg,cloud,log,_args):
# set the validation key based on the presence of either 'validation_key'
# or 'validation_cert'. In the case where both exist, 'validation_key'
# takes precedence
- if chef_cfg.has_key('validation_key') or chef_cfg.has_key('validation_cert'):
+ if (chef_cfg.has_key('validation_key') or
+ chef_cfg.has_key('validation_cert')):
validation_key = util.get_cfg_option_str(chef_cfg, 'validation_key',
chef_cfg['validation_cert'])
with open('/etc/chef/validation.pem', 'w') as validation_key_fh:
@@ -43,12 +45,12 @@ def handle(_name,cfg,cloud,log,_args):
# create the chef config from template
util.render_to_file('chef_client.rb', '/etc/chef/client.rb',
- {'server_url': chef_cfg['server_url'],
- 'node_name': util.get_cfg_option_str(chef_cfg, 'node_name',
- cloud.datasource.get_instance_id()),
- 'environment': util.get_cfg_option_str(chef_cfg, 'environment',
- '_default'),
- 'validation_name': chef_cfg['validation_name']})
+ {'server_url': chef_cfg['server_url'],
+ 'node_name': util.get_cfg_option_str(chef_cfg, 'node_name',
+ cloud.datasource.get_instance_id()),
+ 'environment': util.get_cfg_option_str(chef_cfg, 'environment',
+ '_default'),
+ 'validation_name': chef_cfg['validation_name']})
# set the firstboot json
with open('/etc/chef/firstboot.json', 'w') as firstboot_json_fh:
@@ -57,12 +59,14 @@ def handle(_name,cfg,cloud,log,_args):
initial_json['run_list'] = chef_cfg['run_list']
if chef_cfg.has_key('initial_attributes'):
initial_attributes = chef_cfg['initial_attributes']
- for k in initial_attributes.keys(): initial_json[k] = initial_attributes[k]
+ for k in initial_attributes.keys():
+ initial_json[k] = initial_attributes[k]
firstboot_json_fh.write(json.dumps(initial_json))
# If chef is not installed, we install chef based on 'install_type'
if not os.path.isfile('/usr/bin/chef-client'):
- install_type = util.get_cfg_option_str(chef_cfg, 'install_type', 'packages')
+ install_type = util.get_cfg_option_str(chef_cfg, 'install_type',
+ 'packages')
if install_type == "gems":
# this will install and run the chef-client from gems
chef_version = util.get_cfg_option_str(chef_cfg, 'version', None)
@@ -71,7 +75,8 @@ def handle(_name,cfg,cloud,log,_args):
install_chef_from_gems(ruby_version, chef_version)
# and finally, run chef-client
log.debug('running chef-client')
- subprocess.check_call(['/usr/bin/chef-client', '-d', '-i', '1800', '-s', '20'])
+ subprocess.check_call(['/usr/bin/chef-client', '-d', '-i', '1800',
+ '-s', '20'])
else:
# this will install and run the chef-client from packages
cc.install_packages(('chef',))
@@ -90,13 +95,13 @@ def install_chef_from_gems(ruby_version, chef_version = None):
if not os.path.exists('/usr/bin/ruby'):
os.symlink('/usr/bin/ruby%s' % ruby_version, '/usr/bin/ruby')
if chef_version:
- subprocess.check_call(['/usr/bin/gem','install','chef',
+ subprocess.check_call(['/usr/bin/gem', 'install', 'chef',
'-v %s' % chef_version, '--no-ri',
- '--no-rdoc','--bindir','/usr/bin','-q'])
+ '--no-rdoc', '--bindir', '/usr/bin', '-q'])
else:
- subprocess.check_call(['/usr/bin/gem','install','chef',
- '--no-ri','--no-rdoc','--bindir',
- '/usr/bin','-q'])
+ subprocess.check_call(['/usr/bin/gem', 'install', 'chef',
+ '--no-ri', '--no-rdoc', '--bindir',
+ '/usr/bin', '-q'])
def ensure_dir(d):
if not os.path.exists(d):
diff --git a/cloudinit/CloudConfig/cc_disable_ec2_metadata.py b/cloudinit/CloudConfig/cc_disable_ec2_metadata.py
index f06d4dfc..383e3b0c 100644
--- a/cloudinit/CloudConfig/cc_disable_ec2_metadata.py
+++ b/cloudinit/CloudConfig/cc_disable_ec2_metadata.py
@@ -21,7 +21,7 @@ from cloudinit.CloudConfig import per_always
frequency = per_always
-def handle(_name,cfg,_cloud,_log,_args):
+def handle(_name, cfg, _cloud, _log, _args):
if util.get_cfg_option_bool(cfg, "disable_ec2_metadata", False):
- fwall="route add -host 169.254.169.254 reject"
+ fwall = "route add -host 169.254.169.254 reject"
subprocess.call(fwall.split(' '))
diff --git a/cloudinit/CloudConfig/cc_final_message.py b/cloudinit/CloudConfig/cc_final_message.py
index c8631d01..7930bab5 100644
--- a/cloudinit/CloudConfig/cc_final_message.py
+++ b/cloudinit/CloudConfig/cc_final_message.py
@@ -24,15 +24,15 @@ frequency = per_always
final_message = "cloud-init boot finished at $TIMESTAMP. Up $UPTIME seconds"
-def handle(_name,cfg,_cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
if len(args) != 0:
msg_in = args[0]
else:
- msg_in = util.get_cfg_option_str(cfg,"final_message",final_message)
+ msg_in = util.get_cfg_option_str(cfg, "final_message", final_message)
try:
- uptimef=open("/proc/uptime")
- uptime=uptimef.read().split(" ")[0]
+ uptimef = open("/proc/uptime")
+ uptime = uptimef.read().split(" ")[0]
uptimef.close()
except IOError as e:
log.warn("unable to open /proc/uptime\n")
@@ -40,7 +40,7 @@ def handle(_name,cfg,_cloud,log,args):
try:
- ts = time.strftime("%a, %d %b %Y %H:%M:%S %z",time.gmtime())
+ ts = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.gmtime())
except:
ts = "na"
diff --git a/cloudinit/CloudConfig/cc_foo.py b/cloudinit/CloudConfig/cc_foo.py
index 48d20e5b..82a44baf 100644
--- a/cloudinit/CloudConfig/cc_foo.py
+++ b/cloudinit/CloudConfig/cc_foo.py
@@ -22,5 +22,5 @@ from cloudinit.CloudConfig import per_instance
frequency = per_instance
-def handle(_name,_cfg,_cloud,_log,_args):
+def handle(_name, _cfg, _cloud, _log, _args):
print "hi"
diff --git a/cloudinit/CloudConfig/cc_grub_dpkg.py b/cloudinit/CloudConfig/cc_grub_dpkg.py
index 97d79bdb..1437d481 100644
--- a/cloudinit/CloudConfig/cc_grub_dpkg.py
+++ b/cloudinit/CloudConfig/cc_grub_dpkg.py
@@ -20,23 +20,26 @@ import cloudinit.util as util
import traceback
import os
-def handle(_name,cfg,_cloud,log,_args):
+def handle(_name, cfg, _cloud, log, _args):
- idevs=None
- idevs_empty=None
+ idevs = None
+ idevs_empty = None
if "grub-dpkg" in cfg:
- idevs=util.get_cfg_option_str(cfg["grub-dpkg"],
- "grub-pc/install_devices",None)
- idevs_empty=util.get_cfg_option_str(cfg["grub-dpkg"],
- "grub-pc/install_devices_empty",None)
+ idevs = util.get_cfg_option_str(cfg["grub-dpkg"],
+ "grub-pc/install_devices", None)
+ idevs_empty = util.get_cfg_option_str(cfg["grub-dpkg"],
+ "grub-pc/install_devices_empty", None)
if (( os.path.exists("/dev/sda1") and not os.path.exists("/dev/sda") ) or
( os.path.exists("/dev/xvda1") and not os.path.exists("/dev/xvda") )):
- if idevs == None: idevs=""
- if idevs_empty == None: idevs_empty="true"
+ if idevs == None:
+ idevs = ""
+ if idevs_empty == None:
+ idevs_empty = "true"
else:
- if idevs_empty == None: idevs_empty="false"
+ if idevs_empty == None:
+ idevs_empty = "false"
if idevs == None:
idevs = "/dev/sda"
for dev in ( "/dev/sda", "/dev/vda", "/dev/sda1", "/dev/vda1"):
@@ -50,7 +53,7 @@ def handle(_name,cfg,_cloud,log,_args):
dconf_sel = "grub-pc grub-pc/install_devices string %s\n" % idevs + \
"grub-pc grub-pc/install_devices_empty boolean %s\n" % idevs_empty
log.debug("setting grub debconf-set-selections with '%s','%s'" %
- (idevs,idevs_empty))
+ (idevs, idevs_empty))
try:
util.subp(('debconf-set-selections'), dconf_sel)
diff --git a/cloudinit/CloudConfig/cc_keys_to_console.py b/cloudinit/CloudConfig/cc_keys_to_console.py
index 08e8f085..d462a0a8 100644
--- a/cloudinit/CloudConfig/cc_keys_to_console.py
+++ b/cloudinit/CloudConfig/cc_keys_to_console.py
@@ -21,12 +21,14 @@ import subprocess
frequency = per_instance
-def handle(_name,cfg,_cloud,log,_args):
+def handle(_name, cfg, _cloud, log, _args):
cmd = [ '/usr/lib/cloud-init/write-ssh-key-fingerprints' ]
- fp_blacklist = util.get_cfg_option_list_or_str(cfg, "ssh_fp_console_blacklist", [])
- key_blacklist = util.get_cfg_option_list_or_str(cfg, "ssh_key_console_blacklist", ["ssh-dss"])
+ fp_blacklist = util.get_cfg_option_list_or_str(cfg,
+ "ssh_fp_console_blacklist", [])
+ key_blacklist = util.get_cfg_option_list_or_str(cfg,
+ "ssh_key_console_blacklist", ["ssh-dss"])
try:
- confp = open('/dev/console',"wb")
+ confp = open('/dev/console', "wb")
cmd.append(','.join(fp_blacklist))
cmd.append(','.join(key_blacklist))
subprocess.call(cmd, stdout=confp)
diff --git a/cloudinit/CloudConfig/cc_landscape.py b/cloudinit/CloudConfig/cc_landscape.py
index 22a90665..d2d2bd19 100644
--- a/cloudinit/CloudConfig/cc_landscape.py
+++ b/cloudinit/CloudConfig/cc_landscape.py
@@ -32,7 +32,7 @@ lsc_builtincfg = {
}
}
-def handle(_name,cfg,_cloud,log,_args):
+def handle(_name, cfg, _cloud, log, _args):
"""
Basically turn a top level 'landscape' entry with a 'client' dict
and render it to ConfigObj format under '[client]' section in
diff --git a/cloudinit/CloudConfig/cc_locale.py b/cloudinit/CloudConfig/cc_locale.py
index 8e91d3bf..991f5861 100644
--- a/cloudinit/CloudConfig/cc_locale.py
+++ b/cloudinit/CloudConfig/cc_locale.py
@@ -28,16 +28,17 @@ def apply_locale(locale, cfgfile):
util.render_to_file('default-locale', cfgfile, { 'locale' : locale })
-def handle(_name,cfg,cloud,log,args):
+def handle(_name, cfg, cloud, log, args):
if len(args) != 0:
locale = args[0]
else:
- locale = util.get_cfg_option_str(cfg,"locale",cloud.get_locale())
+ locale = util.get_cfg_option_str(cfg, "locale", cloud.get_locale())
locale_cfgfile = util.get_cfg_option_str(cfg, "locale_configfile",
"/etc/default/locale")
- if not locale: return
+ if not locale:
+ return
log.debug("setting locale to %s" % locale)
diff --git a/cloudinit/CloudConfig/cc_mcollective.py b/cloudinit/CloudConfig/cc_mcollective.py
index 38fe4a3c..8ad8caab 100644
--- a/cloudinit/CloudConfig/cc_mcollective.py
+++ b/cloudinit/CloudConfig/cc_mcollective.py
@@ -34,13 +34,17 @@ class FakeSecHead(object):
self.sechead = '[nullsection]\n'
def readline(self):
if self.sechead:
- try: return self.sechead
- finally: self.sechead = None
- else: return self.fp.readline()
+ try:
+ return self.sechead
+ finally:
+ self.sechead = None
+ else:
+ return self.fp.readline()
-def handle(_name,cfg,_cloud,_log,_args):
+def handle(_name, cfg, _cloud, _log, _args):
# If there isn't a mcollective key in the configuration don't do anything
- if not cfg.has_key('mcollective'): return
+ if not cfg.has_key('mcollective'):
+ return
mcollective_cfg = cfg['mcollective']
# Start by installing the mcollective package ...
cc.install_packages(("mcollective",))
@@ -49,27 +53,30 @@ def handle(_name,cfg,_cloud,_log,_args):
if mcollective_cfg.has_key('conf'):
# Create object for reading server.cfg values
mcollective_config = ConfigParser.ConfigParser()
- # Read server.cfg values from original file in order to be able to mix the rest up
- mcollective_config.readfp(FakeSecHead(open('/etc/mcollective/server.cfg')))
+ # Read server.cfg values from original file in order to be able to mix
+ # the rest up
+ mcollective_config.readfp(FakeSecHead(open('/etc/mcollective/'
+ 'server.cfg')))
for cfg_name, cfg in mcollective_cfg['conf'].iteritems():
if cfg_name == 'public-cert':
util.write_file(pubcert_file, cfg, mode=0644)
mcollective_config.set(cfg_name,
'plugin.ssl_server_public', pubcert_file)
- mcollective_config.set(cfg_name,'securityprovider','ssl')
+ mcollective_config.set(cfg_name, 'securityprovider', 'ssl')
elif cfg_name == 'private-cert':
util.write_file(pricert_file, cfg, mode=0600)
mcollective_config.set(cfg_name,
'plugin.ssl_server_private', pricert_file)
- mcollective_config.set(cfg_name,'securityprovider','ssl')
+ mcollective_config.set(cfg_name, 'securityprovider', 'ssl')
else:
# Iterate throug the config items, we'll use ConfigParser.set
# to overwrite or create new items as needed
for o, v in cfg.iteritems():
- mcollective_config.set(cfg_name,o,v)
+ mcollective_config.set(cfg_name, o, v)
# We got all our config as wanted we'll rename
# the previous server.cfg and create our new one
- os.rename('/etc/mcollective/server.cfg','/etc/mcollective/server.cfg.old')
+ os.rename('/etc/mcollective/server.cfg',
+ '/etc/mcollective/server.cfg.old')
outputfile = StringIO.StringIO()
mcollective_config.write(outputfile)
# Now we got the whole file, write to disk except first line
@@ -79,7 +86,8 @@ def handle(_name,cfg,_cloud,_log,_args):
# search and replace of '=' with ':' could be problematic though.
# this most likely needs fixing.
util.write_file('/etc/mcollective/server.cfg',
- outputfile.getvalue().replace('[nullsection]\n','').replace(' =',':'),
+ outputfile.getvalue().replace('[nullsection]\n', '').replace(' =',
+ ':'),
mode=0644)
# Start mcollective
diff --git a/cloudinit/CloudConfig/cc_mounts.py b/cloudinit/CloudConfig/cc_mounts.py
index a3036d5a..f7d8c702 100644
--- a/cloudinit/CloudConfig/cc_mounts.py
+++ b/cloudinit/CloudConfig/cc_mounts.py
@@ -31,7 +31,7 @@ def is_mdname(name):
return True
return False
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
# fs_spec, fs_file, fs_vfstype, fs_mntops, fs-freq, fs_passno
defvals = [ None, None, "auto", "defaults,nobootwait", "0", "2" ]
defvals = cfg.get("mount_default_fields", defvals)
@@ -50,7 +50,8 @@ def handle(_name,cfg,cloud,log,_args):
for i in range(len(cfgmnt)):
# skip something that wasn't a list
- if not isinstance(cfgmnt[i],list): continue
+ if not isinstance(cfgmnt[i], list):
+ continue
# workaround, allow user to specify 'ephemeral'
# rather than more ec2 correct 'ephemeral0'
@@ -75,7 +76,7 @@ def handle(_name,cfg,cloud,log,_args):
# but do not convert None to 'None' (LP: #898365)
for j in range(len(cfgmnt[i])):
if isinstance(cfgmnt[i][j], int):
- cfgmnt[i][j]=str(cfgmnt[i][j])
+ cfgmnt[i][j] = str(cfgmnt[i][j])
for i in range(len(cfgmnt)):
# fill in values with defaults from defvals above
@@ -98,7 +99,8 @@ def handle(_name,cfg,cloud,log,_args):
# entry has the same device name
for defmnt in defmnts:
devname = cloud.device_name_to_device(defmnt[0])
- if devname is None: continue
+ if devname is None:
+ continue
if devname.startswith("/"):
defmnt[0] = devname
else:
@@ -110,7 +112,8 @@ def handle(_name,cfg,cloud,log,_args):
cfgmnt_has = True
break
- if cfgmnt_has: continue
+ if cfgmnt_has:
+ continue
cfgmnt.append(defmnt)
@@ -118,26 +121,30 @@ def handle(_name,cfg,cloud,log,_args):
# if the second field is None (not the string, the value) we skip it
actlist = [x for x in cfgmnt if x[1] is not None]
- if len(actlist) == 0: return
+ if len(actlist) == 0:
+ return
- comment="comment=cloudconfig"
+ comment = "comment=cloudconfig"
cc_lines = [ ]
needswap = False
dirs = [ ]
for line in actlist:
# write 'comment' in the fs_mntops, entry, claiming this
- line[3]="%s,comment=cloudconfig" % line[3]
- if line[2] == "swap": needswap = True
- if line[1].startswith("/"): dirs.append(line[1])
+ line[3] = "%s,comment=cloudconfig" % line[3]
+ if line[2] == "swap":
+ needswap = True
+ if line[1].startswith("/"):
+ dirs.append(line[1])
cc_lines.append('\t'.join(line))
fstab_lines = [ ]
- fstab=open("/etc/fstab","r+")
+ fstab = open("/etc/fstab", "r+")
ws = re.compile("[%s]+" % string.whitespace)
for line in fstab.read().splitlines():
try:
toks = ws.split(line)
- if toks[3].find(comment) != -1: continue
+ if toks[3].find(comment) != -1:
+ continue
except:
pass
fstab_lines.append(line)
@@ -150,13 +157,20 @@ def handle(_name,cfg,cloud,log,_args):
fstab.close()
if needswap:
- try: util.subp(("swapon", "-a"))
- except: log.warn("Failed to enable swap")
+ try:
+ util.subp(("swapon", "-a"))
+ except:
+ log.warn("Failed to enable swap")
for d in dirs:
- if os.path.exists(d): continue
- try: os.makedirs(d)
- except: log.warn("Failed to make '%s' config-mount\n",d)
+ if os.path.exists(d):
+ continue
+ try:
+ os.makedirs(d)
+ except:
+ log.warn("Failed to make '%s' config-mount\n", d)
- try: util.subp(("mount","-a"))
- except: log.warn("'mount -a' failed")
+ try:
+ util.subp(("mount", "-a"))
+ except:
+ log.warn("'mount -a' failed")
diff --git a/cloudinit/CloudConfig/cc_phone_home.py b/cloudinit/CloudConfig/cc_phone_home.py
index 7897d31b..05caf8eb 100644
--- a/cloudinit/CloudConfig/cc_phone_home.py
+++ b/cloudinit/CloudConfig/cc_phone_home.py
@@ -20,7 +20,8 @@ import cloudinit.util as util
from time import sleep
frequency = per_instance
-post_list_all = [ 'pub_key_dsa', 'pub_key_rsa', 'pub_key_ecdsa', 'instance_id', 'hostname' ]
+post_list_all = ['pub_key_dsa', 'pub_key_rsa', 'pub_key_ecdsa', 'instance_id',
+ 'hostname']
# phone_home:
# url: http://my.foo.bar/$INSTANCE/
@@ -31,11 +32,12 @@ post_list_all = [ 'pub_key_dsa', 'pub_key_rsa', 'pub_key_ecdsa', 'instance_id',
# url: http://my.foo.bar/$INSTANCE_ID/
# post: [ pub_key_dsa, pub_key_rsa, pub_key_ecdsa, instance_id
#
-def handle(_name,cfg,cloud,log,args):
+def handle(_name, cfg, cloud, log, args):
if len(args) != 0:
ph_cfg = util.readconf(args[0])
else:
- if not 'phone_home' in cfg: return
+ if not 'phone_home' in cfg:
+ return
ph_cfg = cfg['phone_home']
if 'url' not in ph_cfg:
@@ -44,7 +46,7 @@ def handle(_name,cfg,cloud,log,args):
url = ph_cfg['url']
post_list = ph_cfg.get('post', 'all')
- tries = ph_cfg.get('tries',10)
+ tries = ph_cfg.get('tries', 10)
try:
tries = int(tries)
except:
@@ -83,7 +85,7 @@ def handle(_name,cfg,cloud,log,args):
url = util.render_string(url, { 'INSTANCE_ID' : all_keys['instance_id'] })
last_e = None
- for i in range(0,tries):
+ for i in range(0, tries):
try:
util.readurl(url, submit_keys)
log.debug("succeeded submit to %s on try %i" % (url, i+1))
diff --git a/cloudinit/CloudConfig/cc_puppet.py b/cloudinit/CloudConfig/cc_puppet.py
index 3748559a..5fb0c1ee 100644
--- a/cloudinit/CloudConfig/cc_puppet.py
+++ b/cloudinit/CloudConfig/cc_puppet.py
@@ -25,9 +25,10 @@ import ConfigParser
import cloudinit.CloudConfig as cc
import cloudinit.util as util
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
# If there isn't a puppet key in the configuration don't do anything
- if not cfg.has_key('puppet'): return
+ if not cfg.has_key('puppet'):
+ return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package ...
cc.install_packages(("puppet",))
@@ -38,8 +39,10 @@ def handle(_name,cfg,cloud,log,_args):
puppet_conf_fh = open('/etc/puppet/puppet.conf', 'r')
# Create object for reading puppet.conf values
puppet_config = ConfigParser.ConfigParser()
- # Read puppet.conf values from original file in order to be able to mix the rest up
- puppet_config.readfp(StringIO.StringIO(''.join(i.lstrip() for i in puppet_conf_fh.readlines())))
+ # Read puppet.conf values from original file in order to be able to
+ # mix the rest up
+ puppet_config.readfp(StringIO.StringIO(''.join(i.lstrip() for i in
+ puppet_conf_fh.readlines())))
# Close original file, no longer needed
puppet_conf_fh.close()
for cfg_name, cfg in puppet_cfg['conf'].iteritems():
@@ -63,7 +66,8 @@ def handle(_name,cfg,cloud,log,_args):
util.restorecon_if_possible('/var/lib/puppet', recursive=True)
else:
#puppet_conf_fh.write("\n[%s]\n" % (cfg_name))
- # If puppet.conf already has this section we don't want to write it again
+ # If puppet.conf already has this section we don't want to
+ # write it again
if puppet_config.has_section(cfg_name) == False:
puppet_config.add_section(cfg_name)
# Iterate throug the config items, we'll use ConfigParser.set
@@ -77,11 +81,11 @@ def handle(_name,cfg,cloud,log,_args):
cloud.datasource.get_instance_id())
# certname needs to be downcase
v = v.lower()
- puppet_config.set(cfg_name,o,v)
+ puppet_config.set(cfg_name, o, v)
#puppet_conf_fh.write("%s=%s\n" % (o, v))
# We got all our config as wanted we'll rename
# the previous puppet.conf and create our new one
- os.rename('/etc/puppet/puppet.conf','/etc/puppet/puppet.conf.old')
+ os.rename('/etc/puppet/puppet.conf', '/etc/puppet/puppet.conf.old')
with open('/etc/puppet/puppet.conf', 'wb') as configfile:
puppet_config.write(configfile)
util.restorecon_if_possible('/etc/puppet/puppet.conf')
diff --git a/cloudinit/CloudConfig/cc_resizefs.py b/cloudinit/CloudConfig/cc_resizefs.py
index adec70be..d960afd5 100644
--- a/cloudinit/CloudConfig/cc_resizefs.py
+++ b/cloudinit/CloudConfig/cc_resizefs.py
@@ -25,15 +25,16 @@ from cloudinit.CloudConfig import per_always
frequency = per_always
-def handle(_name,cfg,_cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
if len(args) != 0:
resize_root = False
if str(args[0]).lower() in [ 'true', '1', 'on', 'yes']:
resize_root = True
else:
- resize_root = util.get_cfg_option_bool(cfg,"resize_rootfs",True)
+ resize_root = util.get_cfg_option_bool(cfg, "resize_rootfs", True)
- if not resize_root: return
+ if not resize_root:
+ return
# this really only uses the filename from mktemp, then we mknod into it
(fd, devpth) = tempfile.mkstemp()
@@ -41,8 +42,8 @@ def handle(_name,cfg,_cloud,log,args):
os.close(fd)
try:
- st_dev=os.stat("/").st_dev
- dev=os.makedev(os.major(st_dev),os.minor(st_dev))
+ st_dev = os.stat("/").st_dev
+ dev = os.makedev(os.major(st_dev), os.minor(st_dev))
os.mknod(devpth, 0400 | stat.S_IFBLK, dev)
except:
if util.islxc():
@@ -53,7 +54,7 @@ def handle(_name,cfg,_cloud,log,args):
cmd = [ 'blkid', '-c', '/dev/null', '-sTYPE', '-ovalue', devpth ]
try:
- (fstype,_err) = util.subp(cmd)
+ (fstype, _err) = util.subp(cmd)
except subprocess.CalledProcessError as e:
log.warn("Failed to get filesystem type of maj=%s, min=%s via: %s" %
(os.major(st_dev), os.minor(st_dev), cmd))
@@ -62,9 +63,9 @@ def handle(_name,cfg,_cloud,log,args):
raise
log.debug("resizing root filesystem (type=%s, maj=%i, min=%i)" %
- (fstype.rstrip("\n"), os.major(st_dev), os.minor(st_dev)))
+ (str(fstype).rstrip("\n"), os.major(st_dev), os.minor(st_dev)))
- if fstype.startswith("ext"):
+ if str(fstype).startswith("ext"):
resize_cmd = [ 'resize2fs', devpth ]
elif fstype == "xfs":
resize_cmd = [ 'xfs_growfs', devpth ]
diff --git a/cloudinit/CloudConfig/cc_rightscale_userdata.py b/cloudinit/CloudConfig/cc_rightscale_userdata.py
index 2b43023c..61aa89d1 100644
--- a/cloudinit/CloudConfig/cc_rightscale_userdata.py
+++ b/cloudinit/CloudConfig/cc_rightscale_userdata.py
@@ -42,7 +42,7 @@ frequency = per_instance
my_name = "cc_rightscale_userdata"
my_hookname = 'CLOUD_INIT_REMOTE_HOOK'
-def handle(_name,_cfg,cloud,log,_args):
+def handle(_name, _cfg, cloud, log, _args):
try:
ud = cloud.get_userdata_raw()
except:
@@ -51,7 +51,8 @@ def handle(_name,_cfg,cloud,log,_args):
try:
mdict = parse_qs(ud)
- if not my_hookname in mdict: return
+ if not my_hookname in mdict:
+ return
except:
log.warn("failed to urlparse.parse_qa(userdata_raw())")
raise
@@ -60,13 +61,14 @@ def handle(_name,_cfg,cloud,log,_args):
i = 0
first_e = None
for url in mdict[my_hookname]:
- fname = "%s/rightscale-%02i" % (scripts_d,i)
+ fname = "%s/rightscale-%02i" % (scripts_d, i)
i = i +1
try:
content = util.readurl(url)
util.write_file(fname, content, mode=0700)
except Exception as e:
- if not first_e: first_e = None
+ if not first_e:
+ first_e = None
log.warn("%s failed to read %s: %s" % (my_name, url, e))
if first_e:
diff --git a/cloudinit/CloudConfig/cc_rsyslog.py b/cloudinit/CloudConfig/cc_rsyslog.py
index ab85a6d8..e5f38c36 100644
--- a/cloudinit/CloudConfig/cc_rsyslog.py
+++ b/cloudinit/CloudConfig/cc_rsyslog.py
@@ -24,7 +24,7 @@ import traceback
DEF_FILENAME = "20-cloud-config.conf"
DEF_DIR = "/etc/rsyslog.d"
-def handle(_name,cfg,_cloud,log,_args):
+def handle(_name, cfg, _cloud, log, _args):
# rsyslog:
# - "*.* @@192.158.1.1"
# - content: "*.* @@192.0.2.1:10514"
@@ -33,7 +33,8 @@ def handle(_name,cfg,_cloud,log,_args):
# *.* @@syslogd.example.com
# process 'rsyslog'
- if not 'rsyslog' in cfg: return
+ if not 'rsyslog' in cfg:
+ return
def_dir = cfg.get('rsyslog_dir', DEF_DIR)
def_fname = cfg.get('rsyslog_filename', DEF_FILENAME)
@@ -41,7 +42,7 @@ def handle(_name,cfg,_cloud,log,_args):
files = [ ]
elst = [ ]
for ent in cfg['rsyslog']:
- if isinstance(ent,dict):
+ if isinstance(ent, dict):
if not "content" in ent:
elst.append((ent, "no 'content' entry"))
continue
@@ -52,7 +53,7 @@ def handle(_name,cfg,_cloud,log,_args):
filename = def_fname
if not filename.startswith("/"):
- filename = "%s/%s" % (def_dir,filename)
+ filename = "%s/%s" % (def_dir, filename)
omode = "ab"
# truncate filename first time you see it
diff --git a/cloudinit/CloudConfig/cc_runcmd.py b/cloudinit/CloudConfig/cc_runcmd.py
index d255223b..3c9baa6f 100644
--- a/cloudinit/CloudConfig/cc_runcmd.py
+++ b/cloudinit/CloudConfig/cc_runcmd.py
@@ -18,12 +18,12 @@
import cloudinit.util as util
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
if not cfg.has_key("runcmd"):
return
- outfile="%s/runcmd" % cloud.get_ipath('scripts')
+ outfile = "%s/runcmd" % cloud.get_ipath('scripts')
try:
content = util.shellify(cfg["runcmd"])
- util.write_file(outfile,content,0700)
+ util.write_file(outfile, content, 0700)
except:
log.warn("failed to open %s for runcmd" % outfile)
diff --git a/cloudinit/CloudConfig/cc_scripts_per_boot.py b/cloudinit/CloudConfig/cc_scripts_per_boot.py
index fb643c6d..ee79f0a3 100644
--- a/cloudinit/CloudConfig/cc_scripts_per_boot.py
+++ b/cloudinit/CloudConfig/cc_scripts_per_boot.py
@@ -23,7 +23,7 @@ from cloudinit import get_cpath
frequency = per_always
runparts_path = "%s/%s" % (get_cpath(), "scripts/per-boot")
-def handle(_name,_cfg,_cloud,log,_args):
+def handle(_name, _cfg, _cloud, log, _args):
try:
util.runparts(runparts_path)
except:
diff --git a/cloudinit/CloudConfig/cc_scripts_per_instance.py b/cloudinit/CloudConfig/cc_scripts_per_instance.py
index b0f0601a..499829ec 100644
--- a/cloudinit/CloudConfig/cc_scripts_per_instance.py
+++ b/cloudinit/CloudConfig/cc_scripts_per_instance.py
@@ -23,7 +23,7 @@ from cloudinit import get_cpath
frequency = per_instance
runparts_path = "%s/%s" % (get_cpath(), "scripts/per-instance")
-def handle(_name,_cfg,_cloud,log,_args):
+def handle(_name, _cfg, _cloud, log, _args):
try:
util.runparts(runparts_path)
except:
diff --git a/cloudinit/CloudConfig/cc_scripts_per_once.py b/cloudinit/CloudConfig/cc_scripts_per_once.py
index 2ab81840..6c43c6f0 100644
--- a/cloudinit/CloudConfig/cc_scripts_per_once.py
+++ b/cloudinit/CloudConfig/cc_scripts_per_once.py
@@ -23,7 +23,7 @@ from cloudinit import get_cpath
frequency = per_once
runparts_path = "%s/%s" % (get_cpath(), "scripts/per-once")
-def handle(_name,_cfg,_cloud,log,_args):
+def handle(_name, _cfg, _cloud, log, _args):
try:
util.runparts(runparts_path)
except:
diff --git a/cloudinit/CloudConfig/cc_scripts_user.py b/cloudinit/CloudConfig/cc_scripts_user.py
index 9c7f2322..3db3c7a6 100644
--- a/cloudinit/CloudConfig/cc_scripts_user.py
+++ b/cloudinit/CloudConfig/cc_scripts_user.py
@@ -23,7 +23,7 @@ from cloudinit import get_ipath_cur
frequency = per_instance
runparts_path = "%s/%s" % (get_ipath_cur(), "scripts")
-def handle(_name,_cfg,_cloud,log,_args):
+def handle(_name, _cfg, _cloud, log, _args):
try:
util.runparts(runparts_path)
except:
diff --git a/cloudinit/CloudConfig/cc_set_hostname.py b/cloudinit/CloudConfig/cc_set_hostname.py
index 4f19b0c8..18189ed0 100644
--- a/cloudinit/CloudConfig/cc_set_hostname.py
+++ b/cloudinit/CloudConfig/cc_set_hostname.py
@@ -18,8 +18,8 @@
import cloudinit.util as util
-def handle(_name,cfg,cloud,log,_args):
- if util.get_cfg_option_bool(cfg,"preserve_hostname",False):
+def handle(_name, cfg, cloud, log, _args):
+ if util.get_cfg_option_bool(cfg, "preserve_hostname", False):
log.debug("preserve_hostname is set. not setting hostname")
return(True)
@@ -34,5 +34,5 @@ def handle(_name,cfg,cloud,log,_args):
def set_hostname(hostname, log):
util.subp(['hostname', hostname])
- util.write_file("/etc/hostname","%s\n" % hostname, 0644)
+ util.write_file("/etc/hostname", "%s\n" % hostname, 0644)
log.debug("populated /etc/hostname with %s on first boot", hostname)
diff --git a/cloudinit/CloudConfig/cc_set_passwords.py b/cloudinit/CloudConfig/cc_set_passwords.py
index 07e3ca1b..15533460 100644
--- a/cloudinit/CloudConfig/cc_set_passwords.py
+++ b/cloudinit/CloudConfig/cc_set_passwords.py
@@ -21,14 +21,14 @@ import sys
import random
import string
-def handle(_name,cfg,_cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
if len(args) != 0:
# if run from command line, and give args, wipe the chpasswd['list']
password = args[0]
if 'chpasswd' in cfg and 'list' in cfg['chpasswd']:
del cfg['chpasswd']['list']
else:
- password = util.get_cfg_option_str(cfg,"password",None)
+ password = util.get_cfg_option_str(cfg, "password", None)
expire = True
pw_auth = "no"
@@ -37,11 +37,11 @@ def handle(_name,cfg,_cloud,log,args):
if 'chpasswd' in cfg:
chfg = cfg['chpasswd']
- plist = util.get_cfg_option_str(chfg,'list',plist)
- expire = util.get_cfg_option_bool(chfg,'expire', expire)
+ plist = util.get_cfg_option_str(chfg, 'list', plist)
+ expire = util.get_cfg_option_bool(chfg, 'expire', expire)
if not plist and password:
- user = util.get_cfg_option_str(cfg,"user","ubuntu")
+ user = util.get_cfg_option_str(cfg, "user", "ubuntu")
plist = "%s:%s" % (user, password)
errors = []
@@ -50,11 +50,11 @@ def handle(_name,cfg,_cloud,log,args):
randlist = []
users = []
for line in plist.splitlines():
- u,p = line.split(':',1)
+ u, p = line.split(':', 1)
if p == "R" or p == "RANDOM":
p = rand_user_password()
- randlist.append("%s:%s" % (u,p))
- plist_in.append("%s:%s" % (u,p))
+ randlist.append("%s:%s" % (u, p))
+ plist_in.append("%s:%s" % (u, p))
users.append(u)
ch_in = '\n'.join(plist_in)
@@ -70,7 +70,7 @@ def handle(_name,cfg,_cloud,log,args):
'\n'.join(randlist) ))
if expire:
- enum=len(errors)
+ enum = len(errors)
for u in users:
try:
util.subp(['passwd', '--expire', u])
@@ -83,13 +83,13 @@ def handle(_name,cfg,_cloud,log,args):
if 'ssh_pwauth' in cfg:
val = str(cfg['ssh_pwauth']).lower()
if val in ( "true", "1", "yes"):
- pw_auth="yes"
- change_pwauth=True
+ pw_auth = "yes"
+ change_pwauth = True
elif val in ( "false", "0", "no"):
- pw_auth="no"
- change_pwauth=True
+ pw_auth = "no"
+ change_pwauth = True
else:
- change_pwauth=False
+ change_pwauth = False
if change_pwauth:
pa_s = "\(#*\)\(PasswordAuthentication[[:space:]]\+\)\(yes\|no\)"
@@ -118,7 +118,7 @@ def rand_str(strlen=32, select_from=string.letters+string.digits):
return("".join([random.choice(select_from) for _x in range(0, strlen)]))
def rand_user_password(pwlen=9):
- selfrom=(string.letters.translate(None,'loLOI') +
- string.digits.translate(None,'01'))
- return(rand_str(pwlen,select_from=selfrom))
+ selfrom = (string.letters.translate(None, 'loLOI') +
+ string.digits.translate(None, '01'))
+ return(rand_str(pwlen, select_from=selfrom))
diff --git a/cloudinit/CloudConfig/cc_ssh.py b/cloudinit/CloudConfig/cc_ssh.py
index 0aad2187..b6ac1edb 100644
--- a/cloudinit/CloudConfig/cc_ssh.py
+++ b/cloudinit/CloudConfig/cc_ssh.py
@@ -21,20 +21,24 @@ import os
import glob
import subprocess
-DISABLE_ROOT_OPTS="no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command=\"echo \'Please login as the user \\\"$USER\\\" rather than the user \\\"root\\\".\';echo;sleep 10\""
+DISABLE_ROOT_OPTS = "no-port-forwarding,no-agent-forwarding," \
+"no-X11-forwarding,command=\"echo \'Please login as the user \\\"$USER\\\" " \
+"rather than the user \\\"root\\\".\';echo;sleep 10\""
global_log = None
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
global global_log
global_log = log
# remove the static keys from the pristine image
if cfg.get("ssh_deletekeys", True):
for f in glob.glob("/etc/ssh/ssh_host_*key*"):
- try: os.unlink(f)
- except: pass
+ try:
+ os.unlink(f)
+ except:
+ pass
if cfg.has_key("ssh_keys"):
# if there are keys in cloud-config, use them
@@ -47,17 +51,18 @@ def handle(_name,cfg,cloud,log,_args):
"ecdsa_public" : ("/etc/ssh/ssh_host_ecdsa_key.pub", 0644),
}
- for key,val in cfg["ssh_keys"].items():
+ for key, val in cfg["ssh_keys"].items():
if key2file.has_key(key):
- util.write_file(key2file[key][0],val,key2file[key][1])
+ util.write_file(key2file[key][0], val, key2file[key][1])
priv2pub = { 'rsa_private':'rsa_public', 'dsa_private':'dsa_public',
'ecdsa_private': 'ecdsa_public', }
cmd = 'o=$(ssh-keygen -yf "%s") && echo "$o" root@localhost > "%s"'
- for priv,pub in priv2pub.iteritems():
- if pub in cfg['ssh_keys'] or not priv in cfg['ssh_keys']: continue
- pair=(key2file[priv][0], key2file[pub][0])
+ for priv, pub in priv2pub.iteritems():
+ if pub in cfg['ssh_keys'] or not priv in cfg['ssh_keys']:
+ continue
+ pair = (key2file[priv][0], key2file[pub][0])
subprocess.call(('sh', '-xc', cmd % pair))
log.debug("generated %s from %s" % pair)
else:
@@ -72,7 +77,7 @@ def handle(_name,cfg,cloud,log,_args):
util.restorecon_if_possible('/etc/ssh', recursive=True)
try:
- user = util.get_cfg_option_str(cfg,'user')
+ user = util.get_cfg_option_str(cfg, 'user')
disable_root = util.get_cfg_option_bool(cfg, "disable_root", True)
disable_root_opts = util.get_cfg_option_str(cfg, "disable_root_opts",
DISABLE_ROOT_OPTS)
@@ -82,12 +87,13 @@ def handle(_name,cfg,cloud,log,_args):
cfgkeys = cfg["ssh_authorized_keys"]
keys.extend(cfgkeys)
- apply_credentials(keys,user,disable_root, disable_root_opts)
+ apply_credentials(keys, user, disable_root, disable_root_opts)
except:
util.logexc(log)
log.warn("applying credentials failed!\n")
-def apply_credentials(keys, user, disable_root, disable_root_opts=DISABLE_ROOT_OPTS, log=global_log):
+def apply_credentials(keys, user, disable_root,
+ disable_root_opts=DISABLE_ROOT_OPTS, log=global_log):
keys = set(keys)
if user:
sshutil.setup_user_keys(keys, user, '', log)
diff --git a/cloudinit/CloudConfig/cc_ssh_import_id.py b/cloudinit/CloudConfig/cc_ssh_import_id.py
index 7e7a54a1..efcd4296 100644
--- a/cloudinit/CloudConfig/cc_ssh_import_id.py
+++ b/cloudinit/CloudConfig/cc_ssh_import_id.py
@@ -19,17 +19,18 @@ import cloudinit.util as util
import subprocess
import traceback
-def handle(_name,cfg,_cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
if len(args) != 0:
user = args[0]
ids = [ ]
if len(args) > 1:
ids = args[1:]
else:
- user = util.get_cfg_option_str(cfg,"user","ubuntu")
- ids = util.get_cfg_option_list_or_str(cfg,"ssh_import_id",[])
+ user = util.get_cfg_option_str(cfg, "user", "ubuntu")
+ ids = util.get_cfg_option_list_or_str(cfg, "ssh_import_id", [])
- if len(ids) == 0: return
+ if len(ids) == 0:
+ return
cmd = [ "sudo", "-Hu", user, "ssh-import-id" ] + ids
diff --git a/cloudinit/CloudConfig/cc_timezone.py b/cloudinit/CloudConfig/cc_timezone.py
index 26b2796d..87855503 100644
--- a/cloudinit/CloudConfig/cc_timezone.py
+++ b/cloudinit/CloudConfig/cc_timezone.py
@@ -24,13 +24,14 @@ import shutil
frequency = per_instance
tz_base = "/usr/share/zoneinfo"
-def handle(_name,cfg,_cloud,log,args):
+def handle(_name, cfg, _cloud, log, args):
if len(args) != 0:
timezone = args[0]
else:
- timezone = util.get_cfg_option_str(cfg,"timezone",False)
+ timezone = util.get_cfg_option_str(cfg, "timezone", False)
- if not timezone: return
+ if not timezone:
+ return
tz_file = "%s/%s" % (tz_base , timezone)
@@ -39,7 +40,7 @@ def handle(_name,cfg,_cloud,log,args):
raise Exception("Invalid timezone %s" % tz_file)
try:
- fp=open("/etc/timezone","wb")
+ fp = open("/etc/timezone", "wb")
fp.write("%s\n" % timezone)
fp.close()
except:
diff --git a/cloudinit/CloudConfig/cc_update_etc_hosts.py b/cloudinit/CloudConfig/cc_update_etc_hosts.py
index 1c245e67..66f0537c 100644
--- a/cloudinit/CloudConfig/cc_update_etc_hosts.py
+++ b/cloudinit/CloudConfig/cc_update_etc_hosts.py
@@ -21,10 +21,10 @@ import StringIO
frequency = per_always
-def handle(_name,cfg,cloud,log,_args):
+def handle(_name, cfg, cloud, log, _args):
( hostname, fqdn ) = util.get_hostname_fqdn(cfg, cloud)
- manage_hosts = util.get_cfg_option_bool(cfg,"manage_etc_hosts", False)
+ manage_hosts = util.get_cfg_option_bool(cfg, "manage_etc_hosts", False)
if manage_hosts in ("True", "true", True, "template"):
# render from template file
try:
@@ -76,7 +76,7 @@ def update_etc_hosts(hostname, fqdn, _log):
new_etchosts.write("%s%s" % (header, hosts_line))
need_write = True
if need_write == True:
- new_etcfile = open ('/etc/hosts','wb')
+ new_etcfile = open('/etc/hosts', 'wb')
new_etcfile.write(new_etchosts.getvalue())
new_etcfile.close()
new_etchosts.close()
diff --git a/cloudinit/CloudConfig/cc_update_hostname.py b/cloudinit/CloudConfig/cc_update_hostname.py
index 4bc1cb2b..893c99e0 100644
--- a/cloudinit/CloudConfig/cc_update_hostname.py
+++ b/cloudinit/CloudConfig/cc_update_hostname.py
@@ -22,14 +22,14 @@ from cloudinit.CloudConfig import per_always
frequency = per_always
-def handle(_name,cfg,cloud,log,_args):
- if util.get_cfg_option_bool(cfg,"preserve_hostname",False):
+def handle(_name, cfg, cloud, log, _args):
+ if util.get_cfg_option_bool(cfg, "preserve_hostname", False):
log.debug("preserve_hostname is set. not updating hostname")
return
( hostname, _fqdn ) = util.get_hostname_fqdn(cfg, cloud)
try:
- prev ="%s/%s" % (cloud.get_cpath('data'),"previous-hostname")
+ prev ="%s/%s" % (cloud.get_cpath('data'), "previous-hostname")
update_hostname(hostname, prev, log)
except Exception:
log.warn("failed to set hostname\n")
@@ -40,7 +40,7 @@ def handle(_name,cfg,cloud,log,_args):
# if file doesn't exist, or no contents, return default
def read_hostname(filename, default=None):
try:
- fp = open(filename,"r")
+ fp = open(filename, "r")
lines = fp.readlines()
fp.close()
for line in lines:
@@ -51,7 +51,8 @@ def read_hostname(filename, default=None):
if line:
return line
except IOError as e:
- if e.errno != errno.ENOENT: raise
+ if e.errno != errno.ENOENT:
+ raise
return default
def update_hostname(hostname, prev_file, log):
@@ -80,14 +81,14 @@ def update_hostname(hostname, prev_file, log):
try:
for fname in update_files:
- util.write_file(fname,"%s\n" % hostname, 0644)
- log.debug("wrote %s to %s" % (hostname,fname))
+ util.write_file(fname, "%s\n" % hostname, 0644)
+ log.debug("wrote %s to %s" % (hostname, fname))
except:
log.warn("failed to write hostname to %s" % fname)
if hostname_in_etc and hostname_prev and hostname_in_etc != hostname_prev:
log.debug("%s differs from %s. assuming user maintained" %
- (prev_file,etc_file))
+ (prev_file, etc_file))
if etc_file in update_files:
log.debug("setting hostname to %s" % hostname)