Beispiel #1
0
def to_ini(o):
    if not isinstance(o, MutableMapping):
        raise AnsibleFilterError('to_ini requires a dict, got %s' % type(o))
    data = copy.deepcopy(o)
    defaults = configparser.RawConfigParser(data.pop('DEFAULT', {}))
    parser = configparser.RawConfigParser()
    parser.optionxform = partial(to_text, errors='surrogate_or_strict')
    for section, items in data.items():
        parser.add_section(section)
        for k, v in items.items():
            parser.set(section, k, v)
    out = StringIO()
    defaults.write(out)
    parser.write(out)
    return out.getvalue().rstrip()
Beispiel #2
0
    def get_credentials(self):
        """
        Get user_id and key from module configuration, environment, or dotfile.
        Order of priority is module, environment, dotfile.

        To set in environment:

            export MCP_USER='******'
            export MCP_PASSWORD='******'

        To set in dot file place a file at ~/.dimensiondata with
        the following contents:

            [dimensiondatacloud]
            MCP_USER: myusername
            MCP_PASSWORD: mypassword
        """

        if not HAS_LIBCLOUD:
            self.module.fail_json(msg='libcloud is required for this module.')

        user_id = None
        key = None

        # First, try the module configuration
        if 'mcp_user' in self.module.params:
            if 'mcp_password' not in self.module.params:
                self.module.fail_json(
                    msg='"mcp_user" parameter was specified, but not "mcp_password" (either both must be specified, or neither).'
                )

            user_id = self.module.params['mcp_user']
            key = self.module.params['mcp_password']

        # Fall back to environment
        if not user_id or not key:
            user_id = os.environ.get('MCP_USER', None)
            key = os.environ.get('MCP_PASSWORD', None)

        # Finally, try dotfile (~/.dimensiondata)
        if not user_id or not key:
            home = expanduser('~')
            config = configparser.RawConfigParser()
            config.read("%s/.dimensiondata" % home)

            try:
                user_id = config.get("dimensiondatacloud", "MCP_USER")
                key = config.get("dimensiondatacloud", "MCP_PASSWORD")
            except (configparser.NoSectionError, configparser.NoOptionError):
                pass

        # One or more credentials not found. Function can't recover from this
        # so it has to raise an error instead of fail silently.
        if not user_id:
            raise MissingCredentialsError("Dimension Data user id not found")
        elif not key:
            raise MissingCredentialsError("Dimension Data key not found")

        # Both found, return data
        return dict(user_id=user_id, key=key)
def load_mongocnf():
    config = configparser.RawConfigParser()
    mongocnf = os.path.expanduser('~/.mongodb.cnf')

    try:
        config.readfp(open(mongocnf))
        creds = dict(user=config.get('client', 'user'),
                     password=config.get('client', 'pass'))
    except (configparser.NoOptionError, IOError):
        return False

    return creds
Beispiel #4
0
def from_ini(o):
    if not isinstance(o, string_types):
        raise AnsibleFilterError('from_ini requires a string, got %s' %
                                 type(o))
    parser = configparser.RawConfigParser()
    parser.optionxform = partial(to_text, errors='surrogate_or_strict')
    parser.readfp(StringIO(o))
    d = dict(parser._sections)
    for k in d:
        d[k] = dict(d[k])
        d[k].pop('__name__', None)
    d['DEFAULT'] = dict(parser._defaults)
    return d
class YumRepo(object):
    # Class global variables
    module = None
    params = None
    section = None
    repofile = configparser.RawConfigParser()

    # List of parameters which will be allowed in the repo file output
    allowed_params = [
        'async',
        'bandwidth',
        'baseurl',
        'cost',
        'deltarpm_metadata_percentage',
        'deltarpm_percentage',
        'enabled',
        'enablegroups',
        'exclude',
        'failovermethod',
        'gpgcakey',
        'gpgcheck',
        'gpgkey',
        'http_caching',
        'include',
        'includepkgs',
        'ip_resolve',
        'keepalive',
        'keepcache',
        'metadata_expire',
        'metadata_expire_filter',
        'metalink',
        'mirrorlist',
        'mirrorlist_expire',
        'name',
        'password',
        'priority',
        'protect',
        'proxy',
        'proxy_password',
        'proxy_username',
        'repo_gpgcheck',
        'retries',
        's3_enabled',
        'skip_if_unavailable',
        'sslcacert',
        'ssl_check_cert_permissions',
        'sslclientcert',
        'sslclientkey',
        'sslverify',
        'throttle',
        'timeout',
        'ui_repoid_vars',
        'username']

    # List of parameters which can be a list
    list_params = ['exclude', 'includepkgs']

    def __init__(self, module):
        # To be able to use fail_json
        self.module = module
        # Shortcut for the params
        self.params = self.module.params
        # Section is always the repoid
        self.section = self.params['repoid']

        # Check if repo directory exists
        repos_dir = self.params['reposdir']
        if not os.path.isdir(repos_dir):
            self.module.fail_json(
                msg="Repo directory '%s' does not exist." % repos_dir)

        # Set dest; also used to set dest parameter for the FS attributes
        self.params['dest'] = os.path.join(
            repos_dir, "%s.repo" % self.params['file'])

        # Read the repo file if it exists
        if os.path.isfile(self.params['dest']):
            self.repofile.read(self.params['dest'])

    def add(self):
        # Remove already existing repo and create a new one
        if self.repofile.has_section(self.section):
            self.repofile.remove_section(self.section)

        # Add section
        self.repofile.add_section(self.section)

        # Baseurl/mirrorlist is not required because for removal we need only
        # the repo name. This is why we check if the baseurl/mirrorlist is
        # defined.
        req_params = (self.params['baseurl'], self.params['metalink'], self.params['mirrorlist'])
        if req_params == (None, None, None):
            self.module.fail_json(
                msg="Parameter 'baseurl', 'metalink' or 'mirrorlist' is required for "
                    "adding a new repo.")

        # Set options
        for key, value in sorted(self.params.items()):
            if key in self.list_params and isinstance(value, list):
                # Join items into one string for specific parameters
                value = ' '.join(value)
            elif isinstance(value, bool):
                # Convert boolean value to integer
                value = int(value)

            # Set the value only if it was defined (default is None)
            if value is not None and key in self.allowed_params:
                self.repofile.set(self.section, key, value)

    def save(self):
        if len(self.repofile.sections()):
            # Write data into the file
            try:
                with open(self.params['dest'], 'w') as fd:
                    self.repofile.write(fd)
            except IOError as e:
                self.module.fail_json(
                    msg="Problems handling file %s." % self.params['dest'],
                    details=to_native(e))
        else:
            # Remove the file if there are not repos
            try:
                os.remove(self.params['dest'])
            except OSError as e:
                self.module.fail_json(
                    msg=(
                        "Cannot remove empty repo file %s." %
                        self.params['dest']),
                    details=to_native(e))

    def remove(self):
        # Remove section if exists
        if self.repofile.has_section(self.section):
            self.repofile.remove_section(self.section)

    def dump(self):
        repo_string = ""

        # Compose the repo file
        for section in sorted(self.repofile.sections()):
            repo_string += "[%s]\n" % section

            for key, value in sorted(self.repofile.items(section)):
                repo_string += "%s = %s\n" % (key, value)

            repo_string += "\n"

        return repo_string