Ejemplo n.º 1
0
 def ensure_sudo_dir(self, path, sudo_base="/etc/sudoers"):
     # Ensure the dir is included and that
     # it actually exists as a directory
     sudoers_contents = ""
     base_exists = False
     if os.path.exists(sudo_base):
         sudoers_contents = util.load_file(sudo_base)
         base_exists = True
     found_include = False
     for line in sudoers_contents.splitlines():
         line = line.strip()
         include_match = re.search(r"^[#|@]includedir\s+(.*)$", line)
         if not include_match:
             continue
         included_dir = include_match.group(1).strip()
         if not included_dir:
             continue
         included_dir = os.path.abspath(included_dir)
         if included_dir == path:
             found_include = True
             break
     if not found_include:
         try:
             if not base_exists:
                 lines = [
                     "# See sudoers(5) for more information"
                     ' on "#include" directives:',
                     "",
                     util.make_header(base="added"),
                     "#includedir %s" % (path),
                     "",
                 ]
                 sudoers_contents = "\n".join(lines)
                 util.write_file(sudo_base, sudoers_contents, 0o440)
             else:
                 lines = [
                     "",
                     util.make_header(base="added"),
                     "#includedir %s" % (path),
                     "",
                 ]
                 sudoers_contents = "\n".join(lines)
                 util.append_file(sudo_base, sudoers_contents)
             LOG.debug("Added '#includedir %s' to %s", path, sudo_base)
         except IOError as e:
             util.logexc(LOG, "Failed to write %s", sudo_base)
             raise e
     util.ensure_dir(path, 0o750)
Ejemplo n.º 2
0
def get_template_params(iid, chef_cfg, log):
    params = CHEF_RB_TPL_DEFAULTS.copy()
    # Allow users to overwrite any of the keys they want (if they so choose),
    # when a value is None, then the value will be set to None and no boolean
    # or string version will be populated...
    for (k, v) in chef_cfg.items():
        if k not in CHEF_RB_TPL_KEYS:
            log.debug("Skipping unknown chef template key '%s'", k)
            continue
        if v is None:
            params[k] = None
        else:
            # This will make the value a boolean or string...
            if k in CHEF_RB_TPL_BOOL_KEYS:
                params[k] = util.get_cfg_option_bool(chef_cfg, k)
            else:
                params[k] = util.get_cfg_option_str(chef_cfg, k)
    # These ones are overwritten to be exact values...
    params.update({
        'generated_by':
        util.make_header(),
        'node_name':
        util.get_cfg_option_str(chef_cfg, 'node_name', default=iid),
        'environment':
        util.get_cfg_option_str(chef_cfg, 'environment', default='_default'),
        # These two are mandatory...
        'server_url':
        chef_cfg['server_url'],
        'validation_name':
        chef_cfg['validation_name'],
    })
    return params
Ejemplo n.º 3
0
def get_template_params(iid, chef_cfg, log):
    params = CHEF_RB_TPL_DEFAULTS.copy()
    # Allow users to overwrite any of the keys they want (if they so choose),
    # when a value is None, then the value will be set to None and no boolean
    # or string version will be populated...
    for (k, v) in chef_cfg.items():
        if k not in CHEF_RB_TPL_KEYS:
            log.debug("Skipping unknown chef template key '%s'", k)
            continue
        if v is None:
            params[k] = None
        else:
            # This will make the value a boolean or string...
            if k in CHEF_RB_TPL_BOOL_KEYS:
                params[k] = util.get_cfg_option_bool(chef_cfg, k)
            else:
                params[k] = util.get_cfg_option_str(chef_cfg, k)
    # These ones are overwritten to be exact values...
    params.update({
        'generated_by': util.make_header(),
        'node_name': util.get_cfg_option_str(chef_cfg, 'node_name',
                                             default=iid),
        'environment': util.get_cfg_option_str(chef_cfg, 'environment',
                                               default='_default'),
        # These two are mandatory...
        'server_url': chef_cfg['server_url'],
        'validation_name': chef_cfg['validation_name'],
    })
    return params
Ejemplo n.º 4
0
    def write_sudo_rules(self, user, rules, sudo_file=None):
        if not sudo_file:
            sudo_file = self.ci_sudoers_fn

        lines = ["", "# User rules for %s" % user]
        if isinstance(rules, (list, tuple)):
            for rule in rules:
                lines.append("%s %s" % (user, rule))
        elif isinstance(rules, (basestring, str)):
            lines.append("%s %s" % (user, rules))
        else:
            msg = "Can not create sudoers rule addition with type %r"
            raise TypeError(msg % (type_utils.obj_name(rules)))
        content = "\n".join(lines)
        content += "\n"  # trailing newline

        self.ensure_sudo_dir(os.path.dirname(sudo_file))
        if not os.path.exists(sudo_file):
            contents = [util.make_header(), content]
            try:
                util.write_file(sudo_file, "\n".join(contents), 0440)
            except IOError as e:
                util.logexc(LOG, "Failed to write sudoers file %s", sudo_file)
                raise e
        else:
            try:
                util.append_file(sudo_file, content)
            except IOError as e:
                util.logexc(LOG, "Failed to append sudoers file %s", sudo_file)
                raise e
Ejemplo n.º 5
0
 def apply_locale(self, locale, out_fn=None):
     if not out_fn:
         out_fn = self.locale_conf_fn
     util.subp(["locale-gen", locale], capture=False)
     util.subp(["update-locale", locale], capture=False)
     # "" provides trailing newline during join
     lines = [util.make_header(), 'LANG="%s"' % (locale), ""]
     util.write_file(out_fn, "\n".join(lines))
Ejemplo n.º 6
0
 def ensure_sudo_dir(self, path, sudo_base="/etc/sudoers"):
     # Ensure the dir is included and that
     # it actually exists as a directory
     sudoers_contents = ""
     base_exists = False
     if os.path.exists(sudo_base):
         sudoers_contents = util.load_file(sudo_base)
         base_exists = True
     found_include = False
     for line in sudoers_contents.splitlines():
         line = line.strip()
         include_match = re.search(r"^#includedir\s+(.*)$", line)
         if not include_match:
             continue
         included_dir = include_match.group(1).strip()
         if not included_dir:
             continue
         included_dir = os.path.abspath(included_dir)
         if included_dir == path:
             found_include = True
             break
     if not found_include:
         try:
             if not base_exists:
                 lines = [
                     ("# See sudoers(5) for more information" ' on "#include" directives:'),
                     "",
                     util.make_header(base="added"),
                     "#includedir %s" % (path),
                     "",
                 ]
                 sudoers_contents = "\n".join(lines)
                 util.write_file(sudo_base, sudoers_contents, 0440)
             else:
                 lines = ["", util.make_header(base="added"), "#includedir %s" % (path), ""]
                 sudoers_contents = "\n".join(lines)
                 util.append_file(sudo_base, sudoers_contents)
             LOG.debug("Added '#includedir %s' to %s" % (path, sudo_base))
         except IOError as e:
             util.logexc(LOG, "Failed to write %s", sudo_base)
             raise e
     util.ensure_dir(path, 0750)
Ejemplo n.º 7
0
 def set_timezone(self, tz):
     tz_file = self._find_tz_file(tz)
     # Note: "" provides trailing newline during join
     tz_lines = [
         util.make_header(),
         str(tz),
         "",
     ]
     util.write_file(self.tz_conf_fn, "\n".join(tz_lines))
     # This ensures that the correct tz will be used for the system
     util.copy(tz_file, self.tz_local_fn)
Ejemplo n.º 8
0
 def apply_locale(self, locale, out_fn=None):
     if not out_fn:
         out_fn = self.locale_conf_fn
     util.subp(['locale-gen', '-G', locale], capture=False)
     # "" provides trailing newline during join
     lines = [
         util.make_header(),
         'LANG="%s"' % (locale),
         "",
     ]
     util.write_file(out_fn, "\n".join(lines))
Ejemplo n.º 9
0
 def set_timezone(self, tz):
     tz_file = self._find_tz_file(tz)
     # Note: "" provides trailing newline during join
     tz_lines = [
         util.make_header(),
         str(tz),
         "",
     ]
     util.write_file(self.tz_conf_fn, "\n".join(tz_lines))
     # This ensures that the correct tz will be used for the system
     util.copy(tz_file, self.tz_local_fn)
Ejemplo n.º 10
0
 def apply_locale(self, locale, out_fn=None):
     if out_fn is not None and out_fn != "/etc/locale.conf":
         LOG.warning("Invalid locale_configfile %s, only supported "
                     "value is /etc/locale.conf", out_fn)
     lines = [
         util.make_header(),
         # Hard-coding the charset isn't ideal, but there is no other way.
         '%s UTF-8' % (locale),
         "",
     ]
     util.write_file(self.locale_gen_fn, "\n".join(lines))
     subp.subp(['locale-gen'], capture=False)
     # In the future systemd can handle locale-gen stuff:
     # https://github.com/systemd/systemd/pull/9864
     subp.subp(['localectl', 'set-locale', locale], capture=False)
Ejemplo n.º 11
0
def update_sysconfig_file(fn, adjustments, allow_empty=False):
    if not adjustments:
        return
    (exists, contents) = read_sysconfig_file(fn)
    updated_am = 0
    for (k, v) in adjustments.items():
        if v is None:
            continue
        v = str(v)
        if len(v) == 0 and not allow_empty:
            continue
        contents[k] = v
        updated_am += 1
    if updated_am:
        lines = [str(contents)]
        if not exists:
            lines.insert(0, util.make_header())
        util.write_file(fn, "\n".join(lines) + "\n", 0644)
Ejemplo n.º 12
0
 def update_etc_hosts(self, hostname, fqdn):
     header = ''
     if os.path.exists(self.hosts_fn):
         eh = hosts.HostsConf(util.load_file(self.hosts_fn))
     else:
         eh = hosts.HostsConf('')
         header = util.make_header(base="added")
     local_ip = self._get_localhost_ip()
     prev_info = eh.get_entry(local_ip)
     need_change = False
     if not prev_info:
         eh.add_entry(local_ip, fqdn, hostname)
         need_change = True
     else:
         need_change = True
         for entry in prev_info:
             entry_fqdn = None
             entry_aliases = []
             if len(entry) >= 1:
                 entry_fqdn = entry[0]
             if len(entry) >= 2:
                 entry_aliases = entry[1:]
             if entry_fqdn is not None and entry_fqdn == fqdn:
                 if hostname in entry_aliases:
                     # Exists already, leave it be
                     need_change = False
         if need_change:
             # Doesn't exist, add that entry in...
             new_entries = list(prev_info)
             new_entries.append([fqdn, hostname])
             eh.del_entries(local_ip)
             for entry in new_entries:
                 if len(entry) == 1:
                     eh.add_entry(local_ip, entry[0])
                 elif len(entry) >= 2:
                     eh.add_entry(local_ip, *entry)
     if need_change:
         contents = StringIO()
         if header:
             contents.write("%s\n" % (header))
         contents.write("%s\n" % (eh))
         util.write_file(self.hosts_fn, contents.getvalue(), mode=0o644)
Ejemplo n.º 13
0
 def update_etc_hosts(self, hostname, fqdn):
     header = ''
     if os.path.exists(self.hosts_fn):
         eh = hosts.HostsConf(util.load_file(self.hosts_fn))
     else:
         eh = hosts.HostsConf('')
         header = util.make_header(base="added")
     local_ip = self._get_localhost_ip()
     prev_info = eh.get_entry(local_ip)
     need_change = False
     if not prev_info:
         eh.add_entry(local_ip, fqdn, hostname)
         need_change = True
     else:
         need_change = True
         for entry in prev_info:
             entry_fqdn = None
             entry_aliases = []
             if len(entry) >= 1:
                 entry_fqdn = entry[0]
             if len(entry) >= 2:
                 entry_aliases = entry[1:]
             if entry_fqdn is not None and entry_fqdn == fqdn:
                 if hostname in entry_aliases:
                     # Exists already, leave it be
                     need_change = False
         if need_change:
             # Doesn't exist, add that entry in...
             new_entries = list(prev_info)
             new_entries.append([fqdn, hostname])
             eh.del_entries(local_ip)
             for entry in new_entries:
                 if len(entry) == 1:
                     eh.add_entry(local_ip, entry[0])
                 elif len(entry) >= 2:
                     eh.add_entry(local_ip, *entry)
     if need_change:
         contents = StringIO()
         if header:
             contents.write("%s\n" % (header))
         contents.write("%s\n" % (eh))
         util.write_file(self.hosts_fn, contents.getvalue(), mode=0o644)
Ejemplo n.º 14
0
def update_sysconfig_file(fn, adjustments, allow_empty=False):
    if not adjustments:
        return
    (exists, contents) = read_sysconfig_file(fn)
    updated_am = 0
    for (k, v) in adjustments.items():
        if v is None:
            continue
        v = str(v)
        if len(v) == 0 and not allow_empty:
            continue
        contents[k] = v
        updated_am += 1
    if updated_am:
        lines = [
            str(contents),
        ]
        if not exists:
            lines.insert(0, util.make_header())
        util.write_file(fn, "\n".join(lines) + "\n", 0o644)
Ejemplo n.º 15
0
    def write_sudo_rules(self, user, rules, sudo_file=None):
        if not sudo_file:
            sudo_file = self.ci_sudoers_fn

        lines = [
            '',
            "# User rules for %s" % user,
        ]
        if isinstance(rules, (list, tuple)):
            for rule in rules:
                lines.append("%s %s" % (user, rule))
        elif isinstance(rules, str):
            lines.append("%s %s" % (user, rules))
        else:
            msg = "Can not create sudoers rule addition with type %r"
            raise TypeError(msg % (type_utils.obj_name(rules)))
        content = "\n".join(lines)
        content += "\n"  # trailing newline

        self.ensure_sudo_dir(os.path.dirname(sudo_file))
        if not os.path.exists(sudo_file):
            contents = [
                util.make_header(),
                content,
            ]
            try:
                util.write_file(sudo_file, "\n".join(contents), 0o440)
            except IOError as e:
                util.logexc(LOG, "Failed to write sudoers file %s", sudo_file)
                raise e
        else:
            try:
                util.append_file(sudo_file, content)
            except IOError as e:
                util.logexc(LOG, "Failed to append sudoers file %s", sudo_file)
                raise e