Python botocore.session.get_session() Examples

The following are 8 code examples of botocore.session.get_session(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module botocore.session , or try the search function .
Example #1
Source File: cli.py    From python-aada with MIT License 6 votes vote down vote up
def main(self):
        parser = self._create_parser()
        self._parsed_args = parser.parse_args(self.args)

        if self._parsed_args.profile:
            self._session = Session(profile=self._parsed_args.profile)
        else:
            self._session = get_session()

        if self._parsed_args.debug:
            self._debug = True

        if self._parsed_args.no_headless:
            self._headless = False

        if self._parsed_args.role:
            self._role = self._parsed_args.role

        if self._parsed_args.account:
            self._account = self._parsed_args.account

        return self.__getattribute__('_{}'.format(self._parsed_args.command))() 
Example #2
Source File: amazonpolly.py    From tts-ros1 with Apache License 2.0 5 votes vote down vote up
def _get_polly_client(self, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None,
                          region_name=None, with_service_model_patch=False):
        """Note we get a new botocore session each time this function is called.
        This is to avoid potential problems caused by inner state of the session.
        """
        botocore_session = get_session()

        if with_service_model_patch:
            # Older versions of botocore don't have polly. We can possibly fix it by appending
            # extra path with polly service model files to the search path.
            current_dir = os.path.dirname(os.path.abspath(__file__))
            service_model_path = os.path.join(current_dir, 'data', 'models')
            botocore_session.set_config_variable('data_path', service_model_path)
            rospy.loginfo('patching service model data path: {}'.format(service_model_path))

        botocore_session.get_component('credential_provider').insert_after('boto-config', AwsIotCredentialProvider())

        botocore_session.user_agent_extra = self._generate_user_agent_suffix()

        session = Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key,
                          aws_session_token=aws_session_token, region_name=region_name,
                          botocore_session=botocore_session)

        try:
            return session.client("polly")
        except UnknownServiceError:
            # the first time we reach here, we try to fix the problem
            if not with_service_model_patch:
                return self._get_polly_client(aws_access_key_id, aws_secret_access_key, aws_session_token, region_name,
                                              with_service_model_patch=True)
            else:
                # we have tried our best, time to panic
                rospy.logerr('Amazon Polly is not available. Please install the latest boto3.')
                raise 
Example #3
Source File: utils.py    From botoflow with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.session = session.get_session()
        self.region = self.test_args['region']
        self.client = self.session.create_client(
            'swf', self.region)

        self.domain = self.test_args['domain']
        self.task_list = self.test_args['tasklist']
        self.workflow_execution = None
        self.workflow_executions = []
        self.serializer = JSONDataConverter() 
Example #4
Source File: test_ebs.py    From flocker with Apache License 2.0 5 votes vote down vote up
def boto_volume_for_test(test, cluster_id):
    """
    Create an in-memory boto3 Volume, avoiding any AWS API calls.
    """
    # Create a session directly rather than allow lazy loading of a default
    # session.
    region_name = u"some-test-region-1"
    s = Boto3Session(
        botocore_session=botocore_get_session(),
        region_name=region_name,
    )
    ec2 = s.resource("ec2", region_name=region_name)
    stubber = Stubber(ec2.meta.client)
    # From this point, any attempt to interact with AWS API should fail with
    # botocore.exceptions.StubResponseError
    stubber.activate()
    volume_id = u"vol-{}".format(random_name(test))
    v = ec2.Volume(id=volume_id)
    tags = []
    if cluster_id is not None:
        tags.append(
            dict(
                Key=CLUSTER_ID_LABEL,
                Value=cluster_id,
            ),
        )
    # Pre-populate the metadata to prevent any attempt to load the metadata by
    # API calls.
    v.meta.data = dict(
        Tags=tags
    )
    return v 
Example #5
Source File: base.py    From PynamoDB with MIT License 5 votes vote down vote up
def session(self) -> botocore.session.Session:
        """
        Returns a valid botocore session
        """
        # botocore client creation is not thread safe as of v1.2.5+ (see issue #153)
        if getattr(self._local, 'session', None) is None:
            self._local.session = get_session()
        return self._local.session 
Example #6
Source File: state_function.py    From boto3-examples with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._session = session.get_session()
        region = self.kwargs.get('region_name', 'us-east-1')
        self.client = self._session.create_client(
            'stepfunctions', region_name=region) 
Example #7
Source File: common.py    From hokusai with MIT License 5 votes vote down vote up
def get_region_name():
  # boto3 autodiscovery
  _region = botosession.get_session().get_config_variable('region')
  if _region:
    return _region
  # boto2 compatibility
  if os.environ.get('AWS_REGION'):
    return os.environ.get('AWS_REGION')
  return AWS_DEFAULT_REGION 
Example #8
Source File: credentials.py    From cloud-custodian with Apache License 2.0 4 votes vote down vote up
def assumed_session(role_arn, session_name, session=None, region=None, external_id=None):
    """STS Role assume a boto3.Session

    With automatic credential renewal.

    Args:
      role_arn: iam role arn to assume
      session_name: client session identifier
      session: an optional extant session, note session is captured
      in a function closure for renewing the sts assumed role.

    :return: a boto3 session using the sts assumed role credentials

    Notes: We have to poke at botocore internals a few times
    """
    if session is None:
        session = Session()

    retry = get_retry(('Throttling',))

    def refresh():

        parameters = {"RoleArn": role_arn, "RoleSessionName": session_name}

        if external_id is not None:
            parameters['ExternalId'] = external_id

        credentials = retry(
            get_sts_client(
                session, region).assume_role, **parameters)['Credentials']
        return dict(
            access_key=credentials['AccessKeyId'],
            secret_key=credentials['SecretAccessKey'],
            token=credentials['SessionToken'],
            # Silly that we basically stringify so it can be parsed again
            expiry_time=credentials['Expiration'].isoformat())

    session_credentials = RefreshableCredentials.create_from_metadata(
        metadata=refresh(),
        refresh_using=refresh,
        method='sts-assume-role')

    # so dirty.. it hurts, no clean way to set this outside of the
    # internals poke. There's some work upstream on making this nicer
    # but its pretty baroque as well with upstream support.
    # https://github.com/boto/boto3/issues/443
    # https://github.com/boto/botocore/issues/761

    s = get_session()
    s._credentials = session_credentials
    if region is None:
        region = s.get_config_variable('region') or 'us-east-1'
    s.set_config_variable('region', region)
    return Session(botocore_session=s)