:param region: The region of AWS to connect to.
    :param EC2Credentials credentials: The credentials to use to authenticate
        with EC2.

    :return: a connection object to AWS EC2
769040
def _connect_to_ec2(region, credentials):
    
    conn = boto.ec2.connect_to_region(
        region,
        aws_access_key_id=credentials.access_key_id,
        aws_secret_access_key=credentials.secret_access_key
    )
    if conn:
        return conn
    else:
        log_red('Failure to authenticate to EC2.')
        return False
1195799
def get_boto_ses_connection():
    

    access_key_id = getattr(
        settings, 'CUCUMBER_SES_ACCESS_KEY_ID',
        getattr(settings, 'AWS_ACCESS_KEY_ID', None))
    access_key = getattr(
        settings, 'CUCUMBER_SES_SECRET_ACCESS_KEY',
        getattr(settings, 'AWS_SECRET_ACCESS_KEY', None))
    region_name = getattr(
        settings, 'CUCUMBER_SES_REGION_NAME',
        getattr(settings, 'AWS_SES_REGION_NAME', None))
    
    if region_name != None:
        return boto.ses.connect_to_region(
            region_name,
            aws_access_key_id=access_key_id,
            aws_secret_access_key=access_key,
        )
    else:
        return boto.connect_ses(
            aws_access_key_id=access_key_id,
            aws_secret_access_key=access_key,
        )
1264838
def get_connection(service, module=None, region=None, key=None, keyid=None,
                   profile=None):
    '''
    
    '''

    # future lint: disable=blacklisted-function
    module = str(module or service)
    module, submodule = (str('boto.') + module).rsplit(str('.'), 1)
    # future lint: enable=blacklisted-function

    svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule)

    cxkey, region, key, keyid = _get_profile(service, region, key,
                                             keyid, profile)
    cxkey = cxkey + ':conn'

    if cxkey in __context__:
        return __context__[cxkey]

    try:
        conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid,
                                         aws_secret_access_key=key)
        if conn is None:
            raise SaltInvocationError('Region "{0}" is not '
                                      'valid.'.format(region))
    except boto.exception.NoAuthHandlerFound:
        raise SaltInvocationError('No authentication credentials found when '
                                  'attempting to make boto {0} connection to '
                                  'region "{1}".'.format(service, region))
    __context__[cxkey] = conn
    return conn
480391
def connect_service(service, credentials, region_name = None, config = None, silent = False):
    
    api_client = None
    try:
        client_params = {}
        client_params['service_name'] = service.lower()
        session_params = {}
        session_params['aws_access_key_id'] = credentials['AccessKeyId']
        session_params['aws_secret_access_key'] = credentials['SecretAccessKey']
        session_params['aws_session_token'] = credentials['SessionToken']
        if region_name:
            client_params['region_name'] = region_name
            session_params['region_name'] = region_name
        if config:
            client_params['config'] = config
        aws_session = boto3.session.Session(**session_params)
        if not silent:
            infoMessage = 'Connecting to AWS %s' % service
            if region_name:
                infoMessage = infoMessage + ' in %s' % region_name
            printInfo('%s...' % infoMessage)
        api_client = aws_session.client(**client_params)
    except Exception as e:
        printException(e)
    return api_client
309148
def _connect(self):
        """"""
        resource = None
        try:
            resource = boto3.resource(
                'ec2',
                aws_access_key_id=self.access_key_id,
                aws_secret_access_key=self.secret_access_key,
                region_name=self.region
            )
            # boto3 resource is lazy so attempt method to test connection
            resource.meta.client.describe_account_attributes()
        except Exception:
            raise EC2CloudException(
                'Could not connect to region: %s' % self.region
            )
        return resource
976363
def validate_regions(self):
        
        for region in self.aws_regions:
            if region not in aws_regions:
                print "Error: Specified region: {} is not a valid aws_region".format(region)
                print "Valid regions are: {}".format(aws_regions)
1275517
def from_store_name(bucket_name, region=None):
    
    # Late-bind `region` for the sake of tests that inject the
    # AWS_REGION environment variable.
    if region is None:
        region = os.getenv('AWS_REGION')

    mostly_ok = _is_mostly_subdomain_compatible(bucket_name)

    if not mostly_ok:
        return CallingInfo(
            bucket_name=bucket_name,
            region=region,
            calling_format=connection.OrdinaryCallingFormat,
            ordinary_endpoint=must_resolve(region))
    else:
        if '.' in bucket_name:
            # The bucket_name might have been DNS compatible, but once
            # dots are involved TLS certificate validations will
            # certainly fail even if that's the case.
            return CallingInfo(
                bucket_name=bucket_name,
                calling_format=connection.OrdinaryCallingFormat,
                region=region,
                ordinary_endpoint=must_resolve(region))
        else:
            # If the bucket follows naming rules and has no dots in
            # the name, SubdomainCallingFormat can be used, with TLS,
            # world-wide.
            return CallingInfo(
                bucket_name=bucket_name,
                calling_format=connection.SubdomainCallingFormat,
                region=region,
                ordinary_endpoint=None)

    assert False
1153722
def get_boto_connection(aws_access_key_id, aws_secret_access_key, region=None, bucketname=None,
                        host=None):
    
    m = _AWS_ACCESS_KEY_ID_RE.match(aws_access_key_id)
    if m is None or m.group() != aws_access_key_id:
        logging.error('The provided aws_access_key_id is not in the correct format. It must \
                      be alphanumeric and contain between 16 and 32 characters.')

    if len(aws_access_key_id) > len(aws_secret_access_key):
        logging.warn("The AWS credential keys aren't in the usual size,"
                     " are you using the correct ones?")

    import boto
    from boto.s3.connection import OrdinaryCallingFormat
    extra_args = {}
    if host is not None:
        extra_args['host'] = host
    if bucketname is not None and '.' in bucketname:
        extra_args['calling_format'] = OrdinaryCallingFormat()
    if region is None:
        return boto.connect_s3(aws_access_key_id, aws_secret_access_key, **extra_args)
    return boto.s3.connect_to_region(region, aws_access_key_id=aws_access_key_id,
                                     aws_secret_access_key=aws_secret_access_key,
                                     **extra_args)
1215336
def get_credentials(self):
        
        return Credentials(access_key=self.aws_access_key_id,
                           secret_key=self.aws_secret_access_key,
                           token=self.aws_session_token)
294252
def __get_connection_cloudwatch():
    
    region = get_global_option('region')
    try:
        if (get_global_option('aws_access_key_id') and
                get_global_option('aws_secret_access_key')):
            logger.debug(
                'Authenticating to CloudWatch using '
                'credentials in configuration file')
            connection = cloudwatch.connect_to_region(
                region,
                aws_access_key_id=get_global_option('aws_access_key_id'),
                aws_secret_access_key=get_global_option(
                    'aws_secret_access_key'))
        else:
            logger.debug(
                'Authenticating using boto\'s authentication handler')
            connection = cloudwatch.connect_to_region(region)

    except Exception as err:
        logger.error('Failed connecting to CloudWatch: {0}'.format(err))
        logger.error(
            'Please report an issue at: '
            'https://github.com/sebdah/dynamic-dynamodb/issues')
        raise

    logger.debug('Connected to CloudWatch in {0}'.format(region))
    return connection
223838
def get_s3_key(self):
        
        try:
            c = s3.connect_to_region(self._region,
                                     aws_access_key_id=self._aws_access_key_id,
                                     aws_secret_access_key=self._aws_secret_access_key)
            bucket = c.get_bucket(self._s3_bucket)
            key = bucket.get_key(self._s3_name)
            self._key_file = StringIO(unicode(key.get_contents_as_string().decode()))
            self._key_file.seek(0)
            key.close()
        except NoAuthHandlerFound:
            raise SergentSshException('Boto said that you should check your credentials')
        except S3ResponseError as e:
            logger.exception(e)
            raise SergentSshException('bucket %s or key %s not found' % (self._s3_bucket, self._s3_name))
1223429
def get_elasticache_replication_groups_by_region(self, region):
        ''' '''

        # ElastiCache boto module doesn't provide a get_all_intances method,
        # that's why we need to call describe directly (it would be called by
        # the shorthand method anyway...)
        try:
            conn = elasticache.connect_to_region(region)
            if conn:
                response = conn.describe_replication_groups()

        except boto.exception.BotoServerError as e:
            error = e.reason

            if e.error_code == 'AuthFailure':
                error = self.get_auth_error_message()
            if not e.reason == "Forbidden":
                error = "Looks like AWS ElastiCache [Replication Groups] is down:\n%s" % e.message
            self.fail_with_error(error, 'getting ElastiCache clusters')

        try:
            # Boto also doesn't provide wrapper classes to ReplicationGroups
            # Because of that wo can't make use of the get_list method in the
            # AWSQueryConnection. Let's do the work manually
            replication_groups = response['DescribeReplicationGroupsResponse']['DescribeReplicationGroupsResult']['ReplicationGroups']

        except KeyError as e:
            error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)."
            self.fail_with_error(error, 'getting ElastiCache clusters')

        for replication_group in replication_groups:
            self.add_elasticache_replication_group(replication_group, region)
116243
public static FaceAPI authenticate(AzureRegions region, ServiceClientCredentials credentials) {
        return authenticate("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0/", credentials)
                .withAzureRegion(region);
    }
1248751
public function getRoleCredentials(AWSRoleCredential $credential, $region)
    {
        if (!$sts = $this->getStsWithInternalCredentials($region)) {
            return null;
        }

        $account = $credential->account();
        $role = $credential->role();
        $cacheKey = sprintf('%s_%s', $account, $role);

        $assumeRoleProvider = AWSCredentialProvider::assumeRole([
            'client' => $sts,
            'assume_role_params' => [
                'DurationSeconds' => $this->stsLifetime, # 900 - 3600
                'RoleArn' => sprintf('arn:aws:iam::%s:%s', $account, $role),
                'RoleSessionName' => 'hal-' . bin2hex(random_bytes(4)), # unique identifier for auditing
            ],
        ]);

        $provider = AWSCredentialProvider::memoize($assumeRoleProvider);
        if ($this->credentialCache) {
            $provider = AWSCredentialProvider::cache($provider, $this->credentialCache, $cacheKey);
        }

        return $provider;
    }
664077
def connect(self):
        
        requested_services = set(
            svc.lower() for svc in current_app.config.get('BOTO3_SERVICES', [])
        )

        region = current_app.config.get('BOTO3_REGION')
        sess_params = {
            'aws_access_key_id': current_app.config.get('BOTO3_ACCESS_KEY'),
            'aws_secret_access_key': current_app.config.get('BOTO3_SECRET_KEY'),
            'profile_name': current_app.config.get('BOTO3_PROFILE'),
            'region_name': region
        }
        sess = boto3.session.Session(**sess_params)

        try:
            cns = {}
            for svc in requested_services:
                # Check for optional parameters
                params = current_app.config.get(
                    'BOTO3_OPTIONAL_PARAMS', {}
                ).get(svc, {})

                # Get session params and override them with kwargs
                # `profile_name` cannot be passed to clients and resources
                kwargs = sess_params.copy()
                kwargs.update(params.get('kwargs', {}))
                del kwargs['profile_name']

                # Override the region if one is defined as an argument
                args = params.get('args', [])
                if len(args) >= 1:
                    del kwargs['region_name']

                if not(isinstance(args, list) or isinstance(args, tuple)):
                    args = [args]

                # Create resource or client
                if svc in sess.get_available_resources():
                    cns.update({svc: sess.resource(svc, *args, **kwargs)})
                else:
                    cns.update({svc: sess.client(svc, *args, **kwargs)})
        except UnknownServiceError:
            raise
        return cns
1250311
def connect_to_rackspace(region,
                         access_key_id,
                         secret_access_key):
    
    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_default_region(region)
    pyrax.set_credentials(access_key_id, secret_access_key)
    nova = pyrax.connect_to_cloudservers(region=region)
    return nova
881148
def get_region_from_metadata():
    '''
    
    '''
    global __Location__

    if __Location__ == 'do-not-get-from-metadata':
        log.debug('Previously failed to get AWS region from metadata. Not trying again.')
        return None

    # Cached region
    if __Location__ != '':
        return __Location__

    try:
        # Connections to instance meta-data must fail fast and never be proxied
        result = requests.get(
            "http://169.254.169.254/latest/dynamic/instance-identity/document",
            proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,
        )
    except requests.exceptions.RequestException:
        log.warning('Failed to get AWS region from instance metadata.', exc_info=True)
        # Do not try again
        __Location__ = 'do-not-get-from-metadata'
        return None

    try:
        region = result.json()['region']
        __Location__ = region
        return __Location__
    except (ValueError, KeyError):
        log.warning('Failed to decode JSON from instance metadata.')
        return None

    return None