Python botocore.session() Examples

The following are 30 code examples of botocore.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 , or try the search function .
Example #1
Source File: aws.py    From aws-elastic-beanstalk-cli with Apache License 2.0 6 votes vote down vote up
def _get_botocore_session():
    if _get_botocore_session.botocore_session is None:
        LOG.debug('Creating new Botocore Session')
        LOG.debug('Botocore version: {0}'.format(botocore.__version__))
        session = botocore.session.get_session({
            'profile': (None, _profile_env_var, _profile, None),
        })
        session.set_config_variable('region', _region_name)
        session.set_config_variable('profile', _profile)
        session.register_component('data_loader', _get_data_loader())
        _set_user_agent_for_session(session)
        _get_botocore_session.botocore_session = session
        if _debug:
            session.set_debug_logger()

    return _get_botocore_session.botocore_session 
Example #2
Source File: test_botocore.py    From pytest-localstack with MIT License 6 votes vote down vote up
def test_session(region_name, service_name, make_test_session):
    """Test Session creation."""
    localstack = make_test_session(region_name=region_name)

    ls_session = localstack.botocore.session()
    assert isinstance(ls_session, localstack_botocore.Session)

    if hasattr(localstack, "_container"):
        with pytest.raises(exceptions.ContainerNotStartedError):
            # Can't create clients until the container is started,
            # because the client needs to know what port its
            # target service is running on.
            bc_client = ls_session.create_client(service_name, localstack.region_name)

    with localstack:  # Start container.
        bc_client = ls_session.create_client(service_name, localstack.region_name)
        assert isinstance(bc_client, botocore.client.BaseClient)
        assert "127.0.0.1" in bc_client._endpoint.host 
Example #3
Source File: __main__.py    From PMapper with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle_argquery(parsed_args) -> int:
    """Processes the arguments for the argquery subcommand and executes related tasks"""
    session = _grab_session(parsed_args)
    graph = principalmapper.graphing.graph_actions.get_existing_graph(session, parsed_args.account, parsed_args.debug)

    # process condition args to generate input dict
    conditions = {}
    if parsed_args.condition is not None:
        for arg in parsed_args.condition:
            # split on equals-sign (=), assume first instance separates the key and value
            components = arg.split('=')
            if len(components) < 2:
                print('Format for condition args not matched: <key>=<value>')
                return 64
            key = components[0]
            value = '='.join(components[1:])
            conditions.update({key: value})

    query_actions.argquery(graph, parsed_args.principal, parsed_args.action, parsed_args.resource, conditions,
                           parsed_args.preset, parsed_args.skip_admin, sys.stdout, parsed_args.debug)

    return 0 
Example #4
Source File: policy.py    From chalice with Apache License 2.0 6 votes vote down vote up
def __init__(self, session=None, api_policy_actions=None,
                 custom_policy_actions=None):
        # type: (Any, APIPolicyT, CustomPolicyT) -> None
        if session is None:
            session = botocore.session.get_session()
        # The difference between api_policy_actions and custom_policy_actions
        # is that api_policy_actions correspond to the 1-1 method to API calls
        # exposed in boto3/botocore clients whereas custom_policy_actions
        # correspond to method names that represent high level abstractions
        # that are typically hand written (e.g s3.download_file()).  These
        # are kept as separate files because we manage these files
        # separately.
        if api_policy_actions is None:
            api_policy_actions = load_api_policy_actions()
        if custom_policy_actions is None:
            custom_policy_actions = load_custom_policy_actions()
        self._session = session
        self._api_policy_actions = api_policy_actions
        self._custom_policy_actions = custom_policy_actions 
Example #5
Source File: saml.py    From awsprocesscreds with Apache License 2.0 6 votes vote down vote up
def __init__(self, password_prompter, requests_session=None):
        """Retrieve SAML assertion using form based auth.

        This class can retrieve a SAML assertion by using form
        based auth.  The supported workflow is:

            * Make a GET request to ``saml_endpoint``
            * Parse the HTML to look for an HTML form
            * Fill in the form data with the username, password
            * Make a POST request to the URL indicated by the form
              action with the filled in form data.
            * Parse the HTML returned from the service and
              extract out the SAMLAssertion.

        :param password_prompter: A function that takes a prompt string and
            returns a password string.

        :param requests_session: A requests session object used to make
            requests to the saml provider.
        """
        if requests_session is None:
            requests_session = requests.Session()
        self._requests_session = requests_session
        self._password_prompter = password_prompter 
Example #6
Source File: aws.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def _get_botocore_session():
    if _get_botocore_session.botocore_session is None:
        LOG.debug('Creating new Botocore Session')
        LOG.debug('Botocore version: {0}'.format(botocore.__version__))
        session = botocore.session.get_session({
            'profile': (None, _profile_env_var, _profile, None),
        })
        session.set_config_variable('region', _region_name)
        session.set_config_variable('profile', _profile)
        session.register_component('data_loader', _get_data_loader())
        _set_user_agent_for_session(session)
        _get_botocore_session.botocore_session = session
        if _debug:
            session.set_debug_logger()

    return _get_botocore_session.botocore_session 
Example #7
Source File: __main__.py    From awsmfa with Apache License 2.0 6 votes vote down vote up
def make_session(identity_profile):
    session = botocore.session.Session(profile=identity_profile)
    try:
        session3 = boto3.session.Session(botocore_session=session)
    except botocore.exceptions.ProfileNotFound as err:
        print(str(err), file=sys.stderr)
        if session.available_profiles:
            print("Available profiles: %s" %
                  ", ".join(sorted(session.available_profiles)),
                  file=sys.stderr)
            print("You can specify a profile by passing it with the -i "
                  "command line flag.", file=sys.stderr)
        else:
            print("You have no AWS profiles configured. Please run 'aws "
                  "configure --profile identity' to get started.",
                  file=sys.stderr)
        return None, None, USER_RECOVERABLE_ERROR
    return session, session3, None 
Example #8
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                 aws_session_token=None, region_name=None,
                 botocore_session=None, profile_name=None):
        if botocore_session is not None:
            self._session = botocore_session
        else:
            # Create a new default session
            self._session = botocore.session.get_session()

        # Setup custom user-agent string if it isn't already customized
        if self._session.user_agent_name == 'Botocore':
            botocore_info = 'Botocore/{0}'.format(
                self._session.user_agent_version)
            if self._session.user_agent_extra:
                self._session.user_agent_extra += ' ' + botocore_info
            else:
                self._session.user_agent_extra = botocore_info
            self._session.user_agent_name = 'Boto3'
            self._session.user_agent_version = boto3.__version__

        if profile_name is not None:
            self._session.set_config_variable('profile', profile_name)

        if aws_access_key_id or aws_secret_access_key or aws_session_token:
            self._session.set_credentials(
                aws_access_key_id, aws_secret_access_key, aws_session_token)

        if region_name is not None:
            self._session.set_config_variable('region', region_name)

        self.resource_factory = ResourceFactory(
            self._session.get_component('event_emitter'))
        self._setup_loader()
        self._register_default_handlers() 
Example #9
Source File: __main__.py    From awsmfa with Apache License 2.0 5 votes vote down vote up
def rotate(args, credentials):
    """rotate the identity profile's AWS access key pair."""
    current_access_key_id = credentials.get(
        args.identity_profile, 'aws_access_key_id')

    # create new sessions using the MFA credentials
    session, session3, err = make_session(args.target_profile)
    if err:
        return err
    iam = session3.resource('iam')

    # find the AccessKey corresponding to the identity profile and delete it.
    current_access_key = next((key for key
                               in iam.CurrentUser().access_keys.all()
                               if key.access_key_id == current_access_key_id))

    iam_service = session3.client('iam')

    # delete existing access key and create new one
    iam_service.delete_access_key(AccessKeyId=current_access_key.access_key_id)
    new_access_key_pair = iam_service.create_access_key()["AccessKey"]

    print("Rotating from %s to %s." % (current_access_key.access_key_id,
                                       new_access_key_pair['AccessKeyId']),
          file=sys.stderr)
    update_credentials_file(args.aws_credentials,
                            args.identity_profile,
                            args.identity_profile,
                            credentials,
                            new_access_key_pair)
    print("%s profile updated." % args.identity_profile, file=sys.stderr)

    return OK 
Example #10
Source File: aws.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def set_profile(profile):
    global _profile, _api_clients
    _profile = profile

    # Invalidate session and old clients
    _get_botocore_session.botocore_session = None
    _api_clients = {} 
Example #11
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                 aws_session_token=None, region_name=None,
                 botocore_session=None, profile_name=None):
        if botocore_session is not None:
            self._session = botocore_session
        else:
            # Create a new default session
            self._session = botocore.session.get_session()

        # Setup custom user-agent string if it isn't already customized
        if self._session.user_agent_name == 'Botocore':
            botocore_info = 'Botocore/{0}'.format(
                self._session.user_agent_version)
            if self._session.user_agent_extra:
                self._session.user_agent_extra += ' ' + botocore_info
            else:
                self._session.user_agent_extra = botocore_info
            self._session.user_agent_name = 'Boto3'
            self._session.user_agent_version = boto3.__version__

        if profile_name is not None:
            self._session.set_config_variable('profile', profile_name)

        if aws_access_key_id or aws_secret_access_key or aws_session_token:
            self._session.set_credentials(
                aws_access_key_id, aws_secret_access_key, aws_session_token)

        if region_name is not None:
            self._session.set_config_variable('region', region_name)

        self.resource_factory = ResourceFactory(
            self._session.get_component('event_emitter'))
        self._setup_loader()
        self._register_default_handlers() 
Example #12
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def available_profiles(self):
        """
        The profiles available to the session credentials
        """
        return self._session.available_profiles 
Example #13
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def events(self):
        """
        The event emitter for a session
        """
        return self._session.get_component('event_emitter') 
Example #14
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def available_profiles(self):
        """
        The profiles available to the session credentials
        """
        return self._session.available_profiles 
Example #15
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def get_credentials(self):
        """
        Return the :class:`botocore.credential.Credential` object
        associated with this session.  If the credentials have not
        yet been loaded, this will attempt to load them.  If they
        have already been loaded, this will return the cached
        credentials.
        """
        return self._session.get_credentials() 
Example #16
Source File: session.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def get_credentials(self):
        """
        Return the :class:`botocore.credential.Credential` object
        associated with this session.  If the credentials have not
        yet been loaded, this will attempt to load them.  If they
        have already been loaded, this will return the cached
        credentials.
        """
        return self._session.get_credentials() 
Example #17
Source File: test_aws_secretsmanager_caching.py    From aws-secretsmanager-caching-python with Apache License 2.0 5 votes vote down vote up
def client(self):
        yield botocore.session.get_session().create_client('secretsmanager') 
Example #18
Source File: s3.py    From karbor with Apache License 2.0 5 votes vote down vote up
def create(context, conf, **kwargs):
    register_opts(conf)

    client_config = conf.s3_client
    LOG.info('Creating s3 client with url %s.',
             client_config.s3_endpoint)
    return botocore.session.get_session().create_client(
        's3',
        aws_access_key_id=client_config.s3_access_key,
        aws_secret_access_key=client_config.s3_secret_key,
        endpoint_url=client_config.s3_endpoint
    ) 
Example #19
Source File: aws.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def _get_client(service_name):
    aws_access_key_id = _id
    aws_secret_key = _key
    if service_name in _api_clients:
        return _api_clients[service_name]

    session = _get_botocore_session()
    if service_name == 'elasticbeanstalk':
        endpoint_url = _endpoint_url
    else:
        endpoint_url = None
    try:
        LOG.debug('Creating new Botocore Client for ' + str(service_name))
        client = session.create_client(service_name,
                                       endpoint_url=endpoint_url,
                                       aws_access_key_id=aws_access_key_id,
                                       aws_secret_access_key=aws_secret_key,
                                       verify=_verify_ssl,
                                       config=Config(signature_version='s3v4'))

    except botocore.exceptions.ProfileNotFound as e:
        raise InvalidProfileError(e)
    LOG.debug('Successfully created session for ' + service_name)

    _api_clients[service_name] = client
    return client 
Example #20
Source File: __main__.py    From awsmfa with Apache License 2.0 5 votes vote down vote up
def acquire_code(args, session, session3):
    """returns the user's token serial number, MFA token code, and an
    error code."""
    serial_number = find_mfa_for_user(args.serial_number, session, session3)
    if not serial_number:
        print("There are no MFA devices associated with this user.",
              file=sys.stderr)
        return None, None, USER_RECOVERABLE_ERROR

    token_code = args.token_code
    if token_code is None:
        while token_code is None or len(token_code) != 6:
            token_code = input("MFA Token Code: ")
    return serial_number, token_code, OK 
Example #21
Source File: __main__.py    From awsmfa with Apache License 2.0 5 votes vote down vote up
def one_mfa(args, credentials):
    session, session3, err = make_session(args.identity_profile)
    if err:
        return err

    if "AWSMFA_TESTING_MODE" in os.environ:
        use_testing_credentials(args, credentials)
        return OK

    mfa_args = {}
    if args.token_code != 'skip':
        serial_number, token_code, err = acquire_code(args, session, session3)
        if err is not OK:
            return err
        mfa_args['SerialNumber'] = serial_number
        mfa_args['TokenCode'] = token_code

    sts = session3.client('sts')
    try:
        if args.role_to_assume:
            mfa_args.update(
                DurationSeconds=min(args.duration, TWELVE_HOURS_IN_SECONDS),
                RoleArn=args.role_to_assume,
                RoleSessionName=args.role_session_name)
            response = sts.assume_role(**mfa_args)
        else:
            mfa_args.update(DurationSeconds=args.duration)
            response = sts.get_session_token(**mfa_args)
    except botocore.exceptions.ClientError as err:
        if err.response["Error"]["Code"] == "AccessDenied":
            print(str(err), file=sys.stderr)
            return USER_RECOVERABLE_ERROR
        else:
            raise
    print_expiration_time(response['Credentials']['Expiration'])
    update_credentials_file(args.aws_credentials,
                            args.target_profile,
                            args.identity_profile,
                            credentials,
                            response['Credentials'])
    return OK 
Example #22
Source File: invokers.py    From pywren with Apache License 2.0 5 votes vote down vote up
def __init__(self, region_name, lambda_function_name):

        self.session = botocore.session.get_session()

        self.region_name = region_name
        self.lambda_function_name = lambda_function_name
        self.lambclient = self.session.create_client('lambda',
                                                     region_name=region_name)
        self.TIME_LIMIT = True 
Example #23
Source File: session.py    From aws-extender with MIT License 5 votes vote down vote up
def get_credentials(self):
        """
        Return the :class:`botocore.credential.Credential` object
        associated with this session.  If the credentials have not
        yet been loaded, this will attempt to load them.  If they
        have already been loaded, this will return the cached
        credentials.
        """
        return self._session.get_credentials() 
Example #24
Source File: session.py    From aws-extender with MIT License 5 votes vote down vote up
def available_profiles(self):
        """
        The profiles available to the session credentials
        """
        return self._session.available_profiles 
Example #25
Source File: session.py    From aws-extender with MIT License 5 votes vote down vote up
def events(self):
        """
        The event emitter for a session
        """
        return self._session.get_component('event_emitter') 
Example #26
Source File: session.py    From aws-extender with MIT License 5 votes vote down vote up
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                 aws_session_token=None, region_name=None,
                 botocore_session=None, profile_name=None):
        if botocore_session is not None:
            self._session = botocore_session
        else:
            # Create a new default session
            self._session = botocore.session.get_session()

        # Setup custom user-agent string if it isn't already customized
        if self._session.user_agent_name == 'Botocore':
            botocore_info = 'Botocore/{0}'.format(
                self._session.user_agent_version)
            if self._session.user_agent_extra:
                self._session.user_agent_extra += ' ' + botocore_info
            else:
                self._session.user_agent_extra = botocore_info
            self._session.user_agent_name = 'Boto3'
            self._session.user_agent_version = boto3.__version__

        if profile_name is not None:
            self._session.set_config_variable('profile', profile_name)

        if aws_access_key_id or aws_secret_access_key or aws_session_token:
            self._session.set_credentials(
                aws_access_key_id, aws_secret_access_key, aws_session_token)

        if region_name is not None:
            self._session.set_config_variable('region', region_name)

        self.resource_factory = ResourceFactory(
            self._session.get_component('event_emitter'))
        self._setup_loader()
        self._register_default_handlers() 
Example #27
Source File: botocore.py    From pytest-localstack with MIT License 5 votes vote down vote up
def default_session(self):
        """Return a default botocore Localstack Session.

        Most applications only need one Session.
        """
        if self._default_session is None:
            self._default_session = self.session()
        return self._default_session 
Example #28
Source File: botocore.py    From pytest-localstack with MIT License 5 votes vote down vote up
def client(self, service_name, *args, **kwargs):
        """Create a botocore client that will use Localstack.

        Arguments are the same as
        :meth:`botocore.session.Session.create_client`.
        """
        return self.default_session.create_client(service_name, *args, **kwargs) 
Example #29
Source File: botocore.py    From pytest-localstack with MIT License 5 votes vote down vote up
def session(self, *args, **kwargs):
        """Create a botocore Session that will use Localstack.

        Arguments are the same as :class:`botocore.session.Session`.
        """
        return Session(self.localstack_session, *args, **kwargs) 
Example #30
Source File: botocore.py    From pytest-localstack with MIT License 5 votes vote down vote up
def contribute_to_session(session):
    """Add :class:`BotocoreTestResourceFactory` to :class:`.LocalstackSession`."""
    logger.debug("patching session %r", session)
    session.botocore = BotocoreTestResourceFactory(session)