Exemplo n.º 1
0
def get_config(name, region=None, key=None, keyid=None, profile=None):
    """
    Get the configuration for a cache cluster.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_elasticache.get_config myelasticache
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not conn:
        return None
    try:
        cc = conn.describe_cache_clusters(name, show_cache_node_info=True)
    except boto.exception.BotoServerError as e:
        msg = "Failed to get config for cache cluster {}.".format(name)
        log.error(msg)
        log.debug(e)
        return {}
    cc = cc["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]
    cc = cc["CacheClusters"][0]
    ret = odict.OrderedDict()
    attrs = [
        "engine",
        "cache_parameter_group",
        "cache_cluster_id",
        "cache_security_groups",
        "replication_group_id",
        "auto_minor_version_upgrade",
        "num_cache_nodes",
        "preferred_availability_zone",
        "security_groups",
        "cache_subnet_group_name",
        "engine_version",
        "cache_node_type",
        "notification_configuration",
        "preferred_maintenance_window",
        "configuration_endpoint",
        "cache_cluster_status",
        "cache_nodes",
    ]
    for key, val in cc.items():
        _key = boto.utils.pythonize_name(key)
        if _key not in attrs:
            continue
        if _key == "cache_parameter_group":
            if val:
                ret[_key] = val["CacheParameterGroupName"]
            else:
                ret[_key] = None
        elif _key == "cache_nodes":
            if val:
                ret[_key] = [k for k in val]
            else:
                ret[_key] = []
        elif _key == "cache_security_groups":
            if val:
                ret[_key] = [k["CacheSecurityGroupName"] for k in val]
            else:
                ret[_key] = []
        elif _key == "configuration_endpoint":
            if val:
                ret["port"] = val["Port"]
                ret["address"] = val["Address"]
            else:
                ret["port"] = None
                ret["address"] = None
        elif _key == "notification_configuration":
            if val:
                ret["notification_topic_arn"] = val["TopicArn"]
            else:
                ret["notification_topic_arn"] = None
        else:
            ret[_key] = val
    return ret
Exemplo n.º 2
0
def describe_parameters(name,
                        Source=None,
                        MaxRecords=None,
                        Marker=None,
                        region=None,
                        key=None,
                        keyid=None,
                        profile=None):
    '''
    Returns a list of `DBParameterGroup` parameters.
    CLI example to description of parameters ::

        salt myminion boto_rds.describe_parameters parametergroupname\
            region=us-east-1
    '''
    res = __salt__['boto_rds.parameter_group_exists'](name,
                                                      tags=None,
                                                      region=region,
                                                      key=key,
                                                      keyid=keyid,
                                                      profile=profile)
    if not res.get('exists'):
        return {
            'result': False,
            'message': 'Parameter group {0} does not exist'.format(name)
        }

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {
                'result': False,
                'message': 'Could not establish a connection to RDS'
            }

        kwargs = {}
        kwargs.update({'DBParameterGroupName': name})
        for key in ('Marker', 'Source'):
            if locals()[key] is not None:
                kwargs[key] = str(locals()[key])

        if locals()['MaxRecords'] is not None:
            kwargs['MaxRecords'] = int(locals()['MaxRecords'])

        pag = conn.get_paginator('describe_db_parameters')
        pit = pag.paginate(**kwargs)

        keys = [
            'ParameterName', 'ParameterValue', 'Description', 'Source',
            'ApplyType', 'DataType', 'AllowedValues', 'IsModifieable',
            'MinimumEngineVersion', 'ApplyMethod'
        ]

        parameters = odict.OrderedDict()
        ret = {'result': True}

        for p in pit:
            for result in p['Parameters']:
                data = odict.OrderedDict()
                for k in keys:
                    data[k] = result.get(k)

                parameters[result.get('ParameterName')] = data

        ret['parameters'] = parameters
        return ret
    except ClientError as e:
        return {'error': salt.utils.boto3.get_error(e)}
Exemplo n.º 3
0
def get_record(name,
               zone,
               record_type,
               fetch_all=False,
               region=None,
               key=None,
               keyid=None,
               profile=None,
               split_dns=False,
               private_zone=False,
               identifier=None,
               retry_on_rate_limit=None,
               rate_limit_retries=None,
               retry_on_errors=True,
               error_retries=5):
    '''
    Get a record from a zone.

    CLI example::

        salt myminion boto_route53.get_record test.example.org example.org A
    '''
    if region is None:
        region = 'universal'

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if retry_on_rate_limit or rate_limit_retries is not None:
        salt.utils.versions.warn_until(
            'Neon',
            'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
            'have been deprecated in favor of \'retry_on_errors\' and '
            '\'error_retries\' respectively. Their functionality will be '
            'removed, as such, their usage is no longer required.')
        if retry_on_rate_limit is not None:
            retry_on_errors = retry_on_rate_limit
        if rate_limit_retries is not None:
            error_retries = rate_limit_retries

    while error_retries > 0:
        try:
            if split_dns:
                _zone = _get_split_zone(zone, conn, private_zone)
            else:
                _zone = conn.get_zone(zone)
            if not _zone:
                msg = 'Failed to retrieve zone {0}'.format(zone)
                log.error(msg)
                return None
            _type = record_type.upper()
            ret = odict.OrderedDict()

            name = _encode_name(name)

            _record = _zone.find_records(name,
                                         _type,
                                         all=fetch_all,
                                         identifier=identifier)

            break  # the while True

        except DNSServerError as e:
            if retry_on_errors:
                if 'Throttling' == e.code:
                    log.debug('Throttled by AWS API.')
                elif 'PriorRequestNotComplete' == e.code:
                    log.debug('The request was rejected by AWS API.\
                              Route 53 was still processing a prior request')
                time.sleep(3)
                error_retries -= 1
                continue
            raise e

    if _record:
        ret['name'] = _decode_name(_record.name)
        ret['value'] = _record.resource_records[0]
        ret['record_type'] = _record.type
        ret['ttl'] = _record.ttl
        if _record.identifier:
            ret['identifier'] = []
            ret['identifier'].append(_record.identifier)
            ret['identifier'].append(_record.weight)

    return ret
Exemplo n.º 4
0
def describe_replication_group(name,
                               region=None,
                               key=None,
                               keyid=None,
                               profile=None,
                               parameter=None):
    """
    Get replication group information.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_elasticache.describe_replication_group mygroup
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not conn:
        return None
    try:
        cc = conn.describe_replication_groups(name)
    except boto.exception.BotoServerError as e:
        msg = "Failed to get config for cache cluster {}.".format(name)
        log.error(msg)
        log.debug(e)
        return {}
    ret = odict.OrderedDict()
    cc = cc["DescribeReplicationGroupsResponse"][
        "DescribeReplicationGroupsResult"]
    cc = cc["ReplicationGroups"][0]

    attrs = [
        "status",
        "description",
        "primary_endpoint",
        "member_clusters",
        "replication_group_id",
        "pending_modified_values",
        "primary_cluster_id",
        "node_groups",
    ]
    for key, val in cc.items():
        _key = boto.utils.pythonize_name(key)
        if _key == "status":
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == "description":
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == "replication_group_id":
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == "member_clusters":
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == "node_groups":
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == "pending_modified_values":
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
    return ret
Exemplo n.º 5
0
def get_config(name, region=None, key=None, keyid=None, profile=None):
    """
    Get the configuration for an autoscale group.

    CLI example::

        salt myminion boto_asg.get_config myasg region=us-east-1
    """
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    retries = 30
    while True:
        try:
            asg = conn.get_all_groups(names=[name])
            if asg:
                asg = asg[0]
            else:
                return {}
            ret = odict.OrderedDict()
            attrs = [
                "name",
                "availability_zones",
                "default_cooldown",
                "desired_capacity",
                "health_check_period",
                "health_check_type",
                "launch_config_name",
                "load_balancers",
                "max_size",
                "min_size",
                "placement_group",
                "vpc_zone_identifier",
                "tags",
                "termination_policies",
                "suspended_processes",
            ]
            for attr in attrs:
                # Tags are objects, so we need to turn them into dicts.
                if attr == "tags":
                    _tags = []
                    for tag in asg.tags:
                        _tag = odict.OrderedDict()
                        _tag["key"] = tag.key
                        _tag["value"] = tag.value
                        _tag["propagate_at_launch"] = tag.propagate_at_launch
                        _tags.append(_tag)
                    ret["tags"] = _tags
                # Boto accepts a string or list as input for vpc_zone_identifier,
                # but always returns a comma separated list. We require lists in
                # states.
                elif attr == "vpc_zone_identifier":
                    ret[attr] = getattr(asg, attr).split(",")
                # convert SuspendedProcess objects to names
                elif attr == "suspended_processes":
                    suspended_processes = getattr(asg, attr)
                    ret[attr] = sorted(
                        [x.process_name for x in suspended_processes])
                else:
                    ret[attr] = getattr(asg, attr)
            # scaling policies
            policies = conn.get_all_policies(as_group=name)
            ret["scaling_policies"] = []
            for policy in policies:
                ret["scaling_policies"].append(
                    dict([
                        ("name", policy.name),
                        ("adjustment_type", policy.adjustment_type),
                        ("scaling_adjustment", policy.scaling_adjustment),
                        ("min_adjustment_step", policy.min_adjustment_step),
                        ("cooldown", policy.cooldown),
                    ]))
            # scheduled actions
            actions = conn.get_all_scheduled_actions(as_group=name)
            ret["scheduled_actions"] = {}
            for action in actions:
                end_time = None
                if action.end_time:
                    end_time = action.end_time.isoformat()
                ret["scheduled_actions"][action.name] = dict([
                    ("min_size", action.min_size),
                    ("max_size", action.max_size),
                    # AWS bug
                    ("desired_capacity", int(action.desired_capacity)),
                    ("start_time", action.start_time.isoformat()),
                    ("end_time", end_time),
                    ("recurrence", action.recurrence),
                ])
            return ret
        except boto.exception.BotoServerError as e:
            if retries and e.code == "Throttling":
                log.debug("Throttled by AWS API, retrying in 5 seconds...")
                time.sleep(5)
                retries -= 1
                continue
            log.error(e)
            return {}
Exemplo n.º 6
0
def describe_parameters(
    name,
    Source=None,
    MaxRecords=None,
    Marker=None,
    region=None,
    key=None,
    keyid=None,
    profile=None,
):
    """
    Returns a list of `DBParameterGroup` parameters.
    CLI example to description of parameters ::

        salt myminion boto_rds.describe_parameters parametergroupname\
            region=us-east-1
    """
    res = __salt__["boto_rds.parameter_group_exists"](name,
                                                      tags=None,
                                                      region=region,
                                                      key=key,
                                                      keyid=keyid,
                                                      profile=profile)
    if not res.get("exists"):
        return {
            "result": False,
            "message": "Parameter group {} does not exist".format(name),
        }

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {
                "result": False,
                "message": "Could not establish a connection to RDS",
            }

        kwargs = {}
        kwargs.update({"DBParameterGroupName": name})
        for key in ("Marker", "Source"):
            if locals()[key] is not None:
                kwargs[key] = str(
                    locals()[key])  # future lint: disable=blacklisted-function

        if locals()["MaxRecords"] is not None:
            kwargs["MaxRecords"] = int(locals()["MaxRecords"])

        pag = conn.get_paginator("describe_db_parameters")
        pit = pag.paginate(**kwargs)

        keys = [
            "ParameterName",
            "ParameterValue",
            "Description",
            "Source",
            "ApplyType",
            "DataType",
            "AllowedValues",
            "IsModifieable",
            "MinimumEngineVersion",
            "ApplyMethod",
        ]

        parameters = odict.OrderedDict()
        ret = {"result": True}

        for p in pit:
            for result in p["Parameters"]:
                data = odict.OrderedDict()
                for k in keys:
                    data[k] = result.get(k)

                parameters[result.get("ParameterName")] = data

        ret["parameters"] = parameters
        return ret
    except ClientError as e:
        return {"error": __utils__["boto3.get_error"](e)}
Exemplo n.º 7
0
def get_record(name,
               zone,
               record_type,
               fetch_all=False,
               region=None,
               key=None,
               keyid=None,
               profile=None,
               split_dns=False,
               private_zone=False,
               identifier=None,
               retry_on_rate_limit=True,
               rate_limit_retries=5):
    '''
    Get a record from a zone.

    CLI example::

        salt myminion boto_route53.get_record test.example.org example.org A
    '''
    if region is None:
        region = 'universal'

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    while rate_limit_retries > 0:
        try:
            if split_dns:
                _zone = _get_split_zone(zone, conn, private_zone)
            else:
                _zone = conn.get_zone(zone)
            if not _zone:
                msg = 'Failed to retrieve zone {0}'.format(zone)
                log.error(msg)
                return None
            _type = record_type.upper()
            ret = odict.OrderedDict()

            name = _encode_name(name)

            _record = _zone.find_records(name,
                                         _type,
                                         all=fetch_all,
                                         identifier=identifier)

            break  # the while True

        except DNSServerError as e:
            # if rate limit, retry:
            if retry_on_rate_limit and 'Throttling' == e.code:
                log.debug('Throttled by AWS API.')
                time.sleep(2)
                rate_limit_retries -= 1
                continue  # the while True; try again if not out of retries
            raise e

    if _record:
        ret['name'] = _decode_name(_record.name)
        ret['value'] = _record.resource_records[0]
        ret['record_type'] = _record.type
        ret['ttl'] = _record.ttl
        if _record.identifier:
            ret['identifier'] = []
            ret['identifier'].append(_record.identifier)
            ret['identifier'].append(_record.weight)

    return ret
Exemplo n.º 8
0
def get_config(name, region=None, key=None, keyid=None, profile=None):
    '''
    Get the configuration for an autoscale group.

    CLI example::

        salt myminion boto_asg.get_config myasg region=us-east-1
    '''
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return None
    try:
        asg = conn.get_all_groups(names=[name])
        if asg:
            asg = asg[0]
        else:
            return {}
        ret = odict.OrderedDict()
        attrs = [
            'name', 'availability_zones', 'default_cooldown',
            'desired_capacity', 'health_check_period', 'health_check_type',
            'launch_config_name', 'load_balancers', 'max_size', 'min_size',
            'placement_group', 'vpc_zone_identifier', 'tags',
            'termination_policies', 'suspended_processes'
        ]
        for attr in attrs:
            # Tags are objects, so we need to turn them into dicts.
            if attr == 'tags':
                _tags = []
                for tag in asg.tags:
                    _tag = odict.OrderedDict()
                    _tag['key'] = tag.key
                    _tag['value'] = tag.value
                    _tag['propagate_at_launch'] = tag.propagate_at_launch
                    _tags.append(_tag)
                ret['tags'] = _tags
            # Boto accepts a string or list as input for vpc_zone_identifier,
            # but always returns a comma separated list. We require lists in
            # states.
            elif attr == 'vpc_zone_identifier':
                ret[attr] = getattr(asg, attr).split(',')
            # convert SuspendedProcess objects to names
            elif attr == 'suspended_processes':
                suspended_processes = getattr(asg, attr)
                ret[attr] = sorted(
                    [x.process_name for x in suspended_processes])
            else:
                ret[attr] = getattr(asg, attr)
        # scaling policies
        policies = conn.get_all_policies(as_group=name)
        ret["scaling_policies"] = []
        for policy in policies:
            ret["scaling_policies"].append(
                dict([("name", policy.name),
                      ("adjustment_type", policy.adjustment_type),
                      ("scaling_adjustment", policy.scaling_adjustment),
                      ("min_adjustment_step", policy.min_adjustment_step),
                      ("cooldown", policy.cooldown)]))
        return ret
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return {}
Exemplo n.º 9
0
def get_config(name, region=None, key=None, keyid=None, profile=None):
    '''
    Get the configuration for a cache cluster.

    CLI example::

        salt myminion boto_elasticache.get_config myelasticache
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not conn:
        return None
    try:
        cc = conn.describe_cache_clusters(name, show_cache_node_info=True)
    except boto.exception.BotoServerError as e:
        msg = 'Failed to get config for cache cluster {0}.'.format(name)
        log.error(msg)
        log.debug(e)
        return {}
    cc = cc['DescribeCacheClustersResponse']['DescribeCacheClustersResult']
    cc = cc['CacheClusters'][0]
    ret = odict.OrderedDict()
    attrs = [
        'engine', 'cache_parameter_group', 'cache_cluster_id',
        'cache_security_groups', 'replication_group_id',
        'auto_minor_version_upgrade', 'num_cache_nodes',
        'preferred_availability_zone', 'security_groups',
        'cache_subnet_group_name', 'engine_version', 'cache_node_type',
        'notification_configuration', 'preferred_maintenance_window',
        'configuration_endpoint', 'cache_cluster_status', 'cache_nodes'
    ]
    for key, val in six.iteritems(cc):
        _key = boto.utils.pythonize_name(key)
        if _key not in attrs:
            continue
        if _key == 'cache_parameter_group':
            if val:
                ret[_key] = val['CacheParameterGroupName']
            else:
                ret[_key] = None
        elif _key == 'cache_nodes':
            if val:
                ret[_key] = [k for k in val]
            else:
                ret[_key] = []
        elif _key == 'cache_security_groups':
            if val:
                ret[_key] = [k['CacheSecurityGroupName'] for k in val]
            else:
                ret[_key] = []
        elif _key == 'configuration_endpoint':
            if val:
                ret['port'] = val['Port']
                ret['address'] = val['Address']
            else:
                ret['port'] = None
                ret['address'] = None
        elif _key == 'notification_configuration':
            if val:
                ret['notification_topic_arn'] = val['TopicArn']
            else:
                ret['notification_topic_arn'] = None
        else:
            ret[_key] = val
    return ret
Exemplo n.º 10
0
def get_config(name=None,
               group_id=None,
               region=None,
               key=None,
               keyid=None,
               profile=None):
    '''
    Get the configuration for a security group.

    CLI example::

        salt myminion boto_secgroup.get_config mysecgroup
    '''
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return None
    if not (name or group_id):
        return None
    try:
        if name:
            sg = conn.get_all_security_groups([name])
        else:
            sg = conn.get_all_security_groups(group_ids=[group_id])
    except boto.exception.BotoServerError as e:
        msg = 'Failed to get config for security group {0}.'.format(name)
        log.error(msg)
        log.debug(e)
        return {}
    sg = sg[0]
    ret = odict.OrderedDict()
    ret['name'] = name
    ret['group_id'] = sg.id
    ret['owner_id'] = sg.owner_id
    ret['description'] = sg.description
    # TODO: add support for tags
    _rules = []
    for rule in sg.rules:
        attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
        _rule = odict.OrderedDict()
        for attr in attrs:
            val = getattr(rule, attr)
            if not val:
                continue
            if attr == 'grants':
                _grants = []
                for grant in val:
                    g_attrs = {
                        'name': 'source_group_name',
                        'owner_id': 'source_group_owner_id',
                        'group_id': 'source_group_group_id',
                        'cidr_ip': 'cidr_ip'
                    }
                    _grant = odict.OrderedDict()
                    for g_attr, g_attr_map in g_attrs.iteritems():
                        g_val = getattr(grant, g_attr)
                        if not g_val:
                            continue
                        _grant[g_attr_map] = g_val
                    _grants.append(_grant)
                _rule['grants'] = _grants
            elif attr == 'from_port':
                _rule[attr] = int(val)
            elif attr == 'to_port':
                _rule[attr] = int(val)
            else:
                _rule[attr] = val
        _rules.append(_rule)
    ret['rules'] = _split_rules(_rules)
    return ret
Exemplo n.º 11
0
def describe_replication_group(name,
                               region=None,
                               key=None,
                               keyid=None,
                               profile=None,
                               parameter=None):
    '''
    Get replication group information.

    CLI example::

        salt myminion boto_elasticache.describe_replication_group mygroup
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not conn:
        return None
    try:
        cc = conn.describe_replication_groups(name)
    except boto.exception.BotoServerError as e:
        msg = 'Failed to get config for cache cluster {0}.'.format(name)
        log.error(msg)
        log.debug(e)
        return {}
    ret = odict.OrderedDict()
    cc = cc['DescribeReplicationGroupsResponse'][
        'DescribeReplicationGroupsResult']
    cc = cc['ReplicationGroups'][0]

    attrs = [
        'status', 'description', 'primary_endpoint', 'member_clusters',
        'replication_group_id', 'pending_modified_values',
        'primary_cluster_id', 'node_groups'
    ]
    for key, val in six.iteritems(cc):
        _key = boto.utils.pythonize_name(key)
        if _key == 'status':
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == 'description':
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == 'replication_group_id':
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == 'member_clusters':
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == 'node_groups':
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
        if _key == 'pending_modified_values':
            if val:
                ret[_key] = val
            else:
                ret[_key] = None
    return ret
Exemplo n.º 12
0
def describe_parameters(name,
                        Source=None,
                        MaxRecords=None,
                        Marker=None,
                        region=None,
                        key=None,
                        keyid=None,
                        profile=None):
    '''
    Returns a list of `DBParameterGroup` parameters.
    CLI example to description of parameters ::

        salt myminion boto_rds.describe_parameters parametergroupname\
            region=us-east-1
    '''
    res = __salt__['boto_rds.parameter_group_exists'](name,
                                                      tags=None,
                                                      region=region,
                                                      key=key,
                                                      keyid=keyid,
                                                      profile=profile)
    if not res:
        return {'exists': bool(res)}

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {'results': bool(conn)}

        kwargs = {}
        for key in ('Marker', 'Source'):
            if locals()[key] is not None:
                kwargs[key] = str(locals()[key])

        if locals()['MaxRecords'] is not None:
            kwargs['MaxRecords'] = int(locals()['MaxRecords'])

        r = conn.describe_db_parameters(DBParameterGroupName=name, **kwargs)

        if not r:
            return {
                'results':
                bool(r),
                'message':
                'Failed to get RDS parameters for group {0}.'.format(name)
            }

        results = r['Parameters']
        keys = [
            'ParameterName', 'ParameterValue', 'Description', 'Source',
            'ApplyType', 'DataType', 'AllowedValues', 'IsModifieable',
            'MinimumEngineVersion', 'ApplyMethod'
        ]

        c = 0
        p = odict.OrderedDict()
        while c < len(results):
            d = odict.OrderedDict()
            for k in keys:
                d[k] = results[c].get(k)

            p[results[c].get('ParameterName')] = d
            c += 1

        return p
    except ClientError as e:
        return {'error': salt.utils.boto3.get_error(e)}
Exemplo n.º 13
0
def get_config(name=None,
               group_id=None,
               region=None,
               key=None,
               keyid=None,
               profile=None,
               vpc_id=None):
    '''
    Get the configuration for a security group.

    CLI example::

        salt myminion boto_secgroup.get_config mysecgroup
    '''
    conn = _get_conn(region, key, keyid, profile)
    if not conn:
        return None
    sg = _get_group(conn, name, vpc_id, group_id, region)
    if sg:
        ret = odict.OrderedDict()
        ret['name'] = sg.name
        # TODO: add support for vpc_id in return
        # ret['vpc_id'] = sg.vpc_id
        ret['group_id'] = sg.id
        ret['owner_id'] = sg.owner_id
        ret['description'] = sg.description
        # TODO: add support for tags
        _rules = []
        for rule in sg.rules:
            logging.debug('examining rule {0} for group {1}'.format(
                rule, sg.id))
            attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
            _rule = odict.OrderedDict()
            for attr in attrs:
                val = getattr(rule, attr)
                if not val:
                    continue
                if attr == 'grants':
                    _grants = []
                    for grant in val:
                        logging.debug('examining grant {0} for'.format(grant))
                        g_attrs = {
                            'name': 'source_group_name',
                            'owner_id': 'source_group_owner_id',
                            'group_id': 'source_group_group_id',
                            'cidr_ip': 'cidr_ip'
                        }
                        _grant = odict.OrderedDict()
                        for g_attr, g_attr_map in g_attrs.iteritems():
                            g_val = getattr(grant, g_attr)
                            if not g_val:
                                continue
                            _grant[g_attr_map] = g_val
                        _grants.append(_grant)
                    _rule['grants'] = _grants
                elif attr == 'from_port':
                    _rule[attr] = int(val)
                elif attr == 'to_port':
                    _rule[attr] = int(val)
                else:
                    _rule[attr] = val
            _rules.append(_rule)
        ret['rules'] = _split_rules(_rules)
        return ret
    else:
        return None
Exemplo n.º 14
0
def get_record(name,
               zone,
               record_type,
               fetch_all=False,
               region=None,
               key=None,
               keyid=None,
               profile=None,
               split_dns=False,
               private_zone=False,
               identifier=None,
               retry_on_rate_limit=None,
               rate_limit_retries=None,
               retry_on_errors=True,
               error_retries=5):
    '''
    Get a record from a zone.

    CLI example::

        salt myminion boto_route53.get_record test.example.org example.org A

   retry_on_errors
        Continue to query if the zone exists after an error is
        raised. The previously used argument `retry_on_rate_limit`
        was deprecated for this argument. Users can still use
        `retry_on_rate_limit` to ensure backwards compatibility,
        but please migrate to using the favored `retry_on_errors`
        argument instead.

    error_retries
        Amount of times to attempt to query if the zone exists.
        The previously used argument `rate_limit_retries` was
        deprecated for this arguments. Users can still use
        `rate_limit_retries` to ensure backwards compatibility,
        but please migrate to using the favored `error_retries`
        argument instead.
    '''
    if region is None:
        region = 'universal'

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if retry_on_rate_limit or rate_limit_retries is not None:
        if retry_on_rate_limit is not None:
            retry_on_errors = retry_on_rate_limit
        if rate_limit_retries is not None:
            error_retries = rate_limit_retries

    while error_retries > 0:
        try:
            if split_dns:
                _zone = _get_split_zone(zone, conn, private_zone)
            else:
                _zone = conn.get_zone(zone)
            if not _zone:
                msg = 'Failed to retrieve zone {0}'.format(zone)
                log.error(msg)
                return None
            _type = record_type.upper()
            ret = odict.OrderedDict()

            name = _encode_name(name)

            _record = _zone.find_records(name,
                                         _type,
                                         all=fetch_all,
                                         identifier=identifier)

            break  # the while True

        except DNSServerError as e:
            if retry_on_errors:
                if 'Throttling' == e.code:
                    log.debug('Throttled by AWS API.')
                elif 'PriorRequestNotComplete' == e.code:
                    log.debug('The request was rejected by AWS API.\
                              Route 53 was still processing a prior request')
                time.sleep(3)
                error_retries -= 1
                continue
            six.reraise(*sys.exc_info())

    if _record:
        ret['name'] = _decode_name(_record.name)
        ret['value'] = _record.resource_records[0]
        ret['record_type'] = _record.type
        ret['ttl'] = _record.ttl
        if _record.identifier:
            ret['identifier'] = []
            ret['identifier'].append(_record.identifier)
            ret['identifier'].append(_record.weight)

    return ret
Exemplo n.º 15
0
def get_record(
    name,
    zone,
    record_type,
    fetch_all=False,
    region=None,
    key=None,
    keyid=None,
    profile=None,
    split_dns=False,
    private_zone=False,
    identifier=None,
    retry_on_rate_limit=None,
    rate_limit_retries=None,
    retry_on_errors=True,
    error_retries=5,
):
    """
    Get a record from a zone.

    CLI Example:

    .. code-block:: bash

        salt myminion boto_route53.get_record test.example.org example.org A

   retry_on_errors
        Continue to query if the zone exists after an error is
        raised. The previously used argument `retry_on_rate_limit`
        was deprecated for this argument. Users can still use
        `retry_on_rate_limit` to ensure backwards compatibility,
        but please migrate to using the favored `retry_on_errors`
        argument instead.

    error_retries
        Number of times to attempt to query if the zone exists.
        The previously used argument `rate_limit_retries` was
        deprecated for this arguments. Users can still use
        `rate_limit_retries` to ensure backwards compatibility,
        but please migrate to using the favored `error_retries`
        argument instead.
    """
    if region is None:
        region = "universal"

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if retry_on_rate_limit or rate_limit_retries is not None:
        if retry_on_rate_limit is not None:
            retry_on_errors = retry_on_rate_limit
        if rate_limit_retries is not None:
            error_retries = rate_limit_retries

    _record = None
    ret = odict.OrderedDict()
    while error_retries > 0:
        try:
            if split_dns:
                _zone = _get_split_zone(zone, conn, private_zone)
            else:
                _zone = conn.get_zone(zone)
            if not _zone:
                msg = "Failed to retrieve zone {}".format(zone)
                log.error(msg)
                return None
            _type = record_type.upper()

            name = _encode_name(name)

            _record = _zone.find_records(name,
                                         _type,
                                         all=fetch_all,
                                         identifier=identifier)

            break  # the while True

        except DNSServerError as e:
            if retry_on_errors and _is_retryable_error(e):
                if "Throttling" == e.code:
                    log.debug("Throttled by AWS API.")
                elif "PriorRequestNotComplete" == e.code:
                    log.debug("The request was rejected by AWS API.\
                              Route 53 was still processing a prior request")
                time.sleep(3)
                error_retries -= 1
                continue
            raise

    if _record:
        ret["name"] = _decode_name(_record.name)
        ret["value"] = _record.resource_records[0]
        ret["record_type"] = _record.type
        ret["ttl"] = _record.ttl
        if _record.identifier:
            ret["identifier"] = []
            ret["identifier"].append(_record.identifier)
            ret["identifier"].append(_record.weight)

    return ret