Instantiates an AWS API client

    :param service:
    :param credentials:
    :param region_name:
    :param config:
    :param silent:

    :return:
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
42250
def __WaitForCredentialsLive(self, iam_aws_id, iam_aws_secret):
    
    print 'waiting for credentials to go live...'
    for region in core.tested_region_names:
      core.WaitForEc2Connection(iam_aws_id, iam_aws_secret, region)
    core.WaitForS3Connection(iam_aws_id, iam_aws_secret)
    
    print 'done'
    return
1104317
def conn_aws(cred, crid):
    """"""
    driver = get_driver(Provider.EC2)
    try:
        aws_obj = driver(cred['aws_access_key_id'],
                         cred['aws_secret_access_key'],
                         region=cred['aws_default_region'])
    except SSLError as e:
        abort_err("\r SSL Error with AWS: {}".format(e))
    except InvalidCredsError as e:
        abort_err("\r Error with AWS Credentials: {}".format(e))
    return {crid: aws_obj}
947851
@GuardedBy("monitor")
  @VisibleForTesting
  static MetricServiceClient createMetricServiceClient(@Nullable Credentials credentials)
      throws IOException {
    MetricServiceSettings.Builder settingsBuilder =
        MetricServiceSettings.newBuilder()
            .setTransportChannelProvider(
                InstantiatingGrpcChannelProvider.newBuilder()
                    .setHeaderProvider(OPENCENSUS_USER_AGENT_HEADER_PROVIDER)
                    .build());
    if (credentials != null) {
      settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
    }
    return MetricServiceClient.create(settingsBuilder.build());
  }
266322
def load_credentials(self, boto_session=None, profile_name=None):
        
        # Automatically load credentials from config or environment
        if not boto_session:

            # If provided, use the supplied profile name.
            if profile_name:
                self.boto_session = boto3.Session(profile_name=profile_name, region_name=self.aws_region)
            elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
                region_name = os.environ.get('AWS_DEFAULT_REGION') or self.aws_region
                session_kw = {
                    "aws_access_key_id": os.environ.get('AWS_ACCESS_KEY_ID'),
                    "aws_secret_access_key": os.environ.get('AWS_SECRET_ACCESS_KEY'),
                    "region_name": region_name,
                }

                # If we're executing in a role, AWS_SESSION_TOKEN will be present, too.
                if os.environ.get("AWS_SESSION_TOKEN"):
                    session_kw["aws_session_token"] = os.environ.get("AWS_SESSION_TOKEN")

                self.boto_session = boto3.Session(**session_kw)
            else:
                self.boto_session = boto3.Session(region_name=self.aws_region)

            logger.debug("Loaded boto session from config: %s", boto_session)
        else:
            logger.debug("Using provided boto session: %s", boto_session)
            self.boto_session = boto_session

        # use provided session's region in case it differs
        self.aws_region = self.boto_session.region_name

        if self.boto_session.region_name not in LAMBDA_REGIONS:
            print("Warning! AWS Lambda may not be available in this AWS Region!")

        if self.boto_session.region_name not in API_GATEWAY_REGIONS:
            print("Warning! AWS API Gateway may not be available in this AWS Region!")
226600
def connect_to_region(region_name):
    
    logging.debug("Connecting to AWS region '%s'" % region_name)
    con = boto.vpc.connect_to_region(region_name)
    if not con:
        raise VpcRouteSetError("Could not establish connection to "
                               "region '%s'." % region_name)
    return con
1165141
def initialise_api(
    debug=False,
    host=None,
    key=None,
    proxy=None,
    user_agent=None,
    headers=None,
    rate_limit=True,
    rate_limit_callback=None,
    error_retry_max=None,
    error_retry_backoff=None,
    error_retry_codes=None,
):
    """"""
    config = cloudsmith_api.Configuration()
    config.debug = debug
    config.host = host if host else config.host
    config.proxy = proxy if proxy else config.proxy
    config.user_agent = user_agent
    config.headers = headers
    config.rate_limit = rate_limit
    config.rate_limit_callback = rate_limit_callback
    config.error_retry_max = error_retry_max
    config.error_retry_backoff = error_retry_backoff
    config.error_retry_codes = error_retry_codes

    if headers:
        if "Authorization" in config.headers:
            encoded = config.headers["Authorization"].split(" ")[1]
            decoded = base64.b64decode(encoded)
            values = decoded.decode("utf-8")
            config.username, config.password = values.split(":")

    set_api_key(config, key)
    return config
847772
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args):
    '''
    
    '''
    auth(profile, **connection_args)
    services = service_list(profile, **connection_args)
    if service not in services:
        return {'Error': 'Could not find the specified service'}
    service_id = services[service]['id']
    endpoints = endpoint_list(profile, **connection_args)

    e = [_f for _f in [e
          if e['service_id'] == service_id and
            (e['region'] == region if region else True) and
            (e['interface'] == interface if interface else True)
            else None for e in endpoints.values()] if _f]
    if len(e) > 1:
        return {'Error': 'Multiple endpoints found ({0}) for the {1} service. Please specify region.'.format(e, service)}
    if len(e) == 1:
        return e[0]
    return {'Error': 'Could not find endpoint for the specified service'}
394209
def create_client(self) -> "google.cloud.storage.Client":
        
        # Client should be imported here because grpc starts threads during import
        # and if you call fork after that, a child process will be hang during exit
        from google.cloud.storage import Client
        if self.credentials:
            client = Client.from_service_account_json(self.credentials)
        else:
            client = Client()
        return 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
1269608
def _init_az_api(self):
        
        with self.__lock:
            if self._resource_client is None:
                log.debug("Making Azure `ServicePrincipalcredentials` object"
                          " with tenant=%r, client_id=%r, secret=%r ...",
                          self.tenant_id, self.client_id,
                          ('<redacted>' if self.secret else None))
                credentials = ServicePrincipalCredentials(
                    tenant=self.tenant_id,
                    client_id=self.client_id,
                    secret=self.secret,
                )
                log.debug("Initializing Azure `ComputeManagementclient` ...")
                self._compute_client = ComputeManagementClient(credentials, self.subscription_id)
                log.debug("Initializing Azure `NetworkManagementclient` ...")
                self._network_client = NetworkManagementClient(credentials, self.subscription_id)
                log.debug("Initializing Azure `ResourceManagementclient` ...")
                self._resource_client = ResourceManagementClient(credentials, self.subscription_id)
                log.info("Azure API clients initialized.")
579681
def service_region(self, service_name):
    
    if not self.services()[service_name].has_key("region"):
      return EFConfig.DEFAULT_REGION
    else:
      return self.services()[service_name]["region"]
252391
def _credentials(self):
        

        if self.aws_account_id and self.aws_arn_role_name:
            return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
                id=self.aws_account_id,
                role=self.aws_arn_role_name
            )
        elif self.aws_access_key_id and self.aws_secret_access_key:
            return 'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'.format(
                key=self.aws_access_key_id,
                secret=self.aws_secret_access_key,
                opt=';token={}'.format(self.aws_session_token) if self.aws_session_token else ''
            )
        else:
            raise NotImplementedError("Missing Credentials. "
                                      "Ensure one of the pairs of auth args below are set "
                                      "in a configuration file, environment variables or by "
                                      "being overridden in the task: "
                                      "'aws_access_key_id' AND 'aws_secret_access_key' OR "
                                      "'aws_account_id' AND 'aws_arn_role_name'")
1059268
def set_credential_file(self, credential_file, region=None,
            tenant_id=None, authenticate=False):
        
        self._creds_file = credential_file
        cfg = ConfigParser.SafeConfigParser()
        try:
            if not cfg.read(credential_file):
                # If the specified file does not exist, the parser returns an
                # empty list.
                raise exc.FileNotFound("The specified credential file '%s' "
                        "does not exist" % credential_file)
        except ConfigParser.MissingSectionHeaderError as e:
            # The file exists, but doesn't have the correct format.
            raise exc.InvalidCredentialFile(e)
        try:
            self._read_credential_file(cfg)
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
            raise exc.InvalidCredentialFile(e)
        if region:
            self.region = region
        if authenticate:
            self.authenticate()
967842
def create_api_key(awsclient, api_name, api_key_name):
    
    _sleep()
    client_api = awsclient.get_client('apigateway')
    print('create api key: %s' % api_key_name)

    response = client_api.create_api_key(
        name=api_key_name,
        description='Created for ' + api_name,
        enabled=True
    )

    #print(json2table(response))

    print('Add this api key \'%s\' to your api.conf' % response['id'])
    return response['id']
175985
def get_client(self, region):
        
        ep = self._ep_for_region(region)
        if not ep:
            raise exc.NoEndpointForRegion("There is no endpoint defined for the "
                    "region '%s' for the '%s' service." % (region,
                    self.service_type))
        return ep.client
820527
def _get_sqs_conn(profile, region=None, key=None, keyid=None):
    '''
    
    '''
    if profile:
        if isinstance(profile, six.string_types):
            _profile = __opts__[profile]
        elif isinstance(profile, dict):
            _profile = profile
        key = _profile.get('key', None)
        keyid = _profile.get('keyid', None)
        region = _profile.get('region', None)

    if not region:
        region = __opts__.get('sqs.region', 'us-east-1')
    if not key:
        key = __opts__.get('sqs.key', None)
    if not keyid:
        keyid = __opts__.get('sqs.keyid', None)
    try:
        conn = boto.sqs.connect_to_region(region, aws_access_key_id=keyid,
                                          aws_secret_access_key=key)
    except boto.exception.NoAuthHandlerFound:
        log.error('No authentication credentials found when attempting to'
                  ' make sqs_event engine connection to AWS.')
        return None
    return conn