예제 #1
0
파일: config.py 프로젝트: zeus911/awsudo
    def getEnvironment(self, profile=None):
        """Return environment variables that should be set for the profile."""
        eventHooks = HierarchicalEmitter()
        session = Session(event_hooks=eventHooks)

        if profile:
            session.set_config_variable('profile', profile)

        awscli_initialize(eventHooks)
        session.emit('session-initialized', session=session)
        creds = session.get_credentials()

        env = {}

        def set(key, value):
            if value:
                env[key] = value

        set('AWS_ACCESS_KEY_ID', creds.access_key)
        set('AWS_SECRET_ACCESS_KEY', creds.secret_key)

        # AWS_SESSION_TOKEN is the ostensibly the standard:
        # http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
        # http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-environment
        set('AWS_SESSION_TOKEN', creds.token)

        # ...but boto expects AWS_SECURITY_TOKEN. Set both for compatibility.
        # https://github.com/boto/boto/blob/b016c07d834df5bce75141c4b9d2f3d30352e1b8/boto/connection.py#L438
        set('AWS_SECURITY_TOKEN', creds.token)

        set('AWS_DEFAULT_REGION', session.get_config_variable('region'))

        return env
예제 #2
0
    class Context(object):
        def __init__(self, profile=''):
            self.session = Session()
            self.session.profile = profile

        def getS3Connection(self):
            return S3Connection(self.session.get_config_variable('access_key'),
                                self.session.get_config_variable('secret_key'))
예제 #3
0
    def __init__(self) -> None:
        current_session = Session()
        region = current_session.get_config_variable('region')
        creds = current_session.get_credentials()
        self.signer = SigV4Auth(creds, 'execute-api', region)

        analysis_api_fqdn = os.environ.get('ANALYSIS_API_FQDN')
        analysis_api_path = os.environ.get('ANALYSIS_API_PATH')
        self.url = 'https://' + analysis_api_fqdn + '/' + analysis_api_path
예제 #4
0
def run():
    "Entry proint"

    obj = BotocoreClientHandler(service='ecr')
    parser = obj._parse_args()
    print(parser.profile)
    session = Session(profile=parser.profile)
    print(dir(session))
    print(session.get_config_variable('region'))
    print(session.get_credentials(), session.profile)
예제 #5
0
    def __init__(
        self,
        *,
        max_concurrent_requests: int = _DEFAULT_MAX_CONCURRENT_REQUESTS,
        max_attempts: int = _DEFAULT_MAX_ATTEMPTS,
        timeout: aiohttp.ClientTimeout = _DEFAULT_TIMEOUT,
        session: aiohttp.ClientSession = None,
    ):
        self._max_concurrent_requests = max_concurrent_requests
        self._max_attempts = max_attempts

        # Fetch the credentials and default region from botocore's session.
        # This will automatically find configuration in the user's .aws folder,
        # or in instance metadata.
        boto_session = Session()
        self._credentials = boto_session.get_credentials()
        self._region = boto_session.get_config_variable("region")

        if session is None:
            self._session = aiohttp.ClientSession(raise_for_status=True, timeout=timeout)
        else:
            self._session = session
예제 #6
0
    def getEnvironment(self, profile=None):
        """Return environment variables that should be set for the profile."""
        eventHooks = HierarchicalEmitter()
        session = Session(event_hooks=eventHooks)

        if profile:
            session.set_config_variable('profile', profile)

        eventHooks.register('session-initialized',
                            inject_assume_role_provider_cache,
                            unique_id='inject_assume_role_cred_provider_cache')

        session.emit('session-initialized', session=session)
        creds = session.get_credentials()

        env = {}

        def set(key, value):
            if value:
                env[key] = value

        set('AWS_ACCESS_KEY_ID', creds.access_key)
        set('AWS_SECRET_ACCESS_KEY', creds.secret_key)

        # AWS_SESSION_TOKEN is the ostensibly the standard:
        # http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
        # http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-environment
        set('AWS_SESSION_TOKEN', creds.token)

        # ...but boto expects AWS_SECURITY_TOKEN. Set both for compatibility.
        # https://github.com/boto/boto/blob/b016c07d834df5bce75141c4b9d2f3d30352e1b8/boto/connection.py#L438
        set('AWS_SECURITY_TOKEN', creds.token)

        set('AWS_DEFAULT_REGION', session.get_config_variable('region'))

        return env
def main():
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    parser.add_argument('--profile', help='The AWS config profile to use')

    group = parser.add_mutually_exclusive_group()
    group.add_argument('--json', action='store_const', const='json', dest='format', help="Print credential_process-compatible JSON to stdout (default)")
    group.add_argument('--env', action='store_const', const='env', dest='format', help="Print as env vars")
    group.add_argument('--env-export', action='store_const', const='env-export', dest='format', help="Print as env vars prefixed by 'export ' for shell sourcing")
    group.add_argument('--exec', nargs=argparse.REMAINDER, help="Exec remaining input w/ creds injected as env vars")
    group.add_argument('--credentials-file-profile', '-c', metavar='PROFILE_NAME', help="Write to a profile in AWS credentials file")
    group.add_argument('--container', nargs=2, metavar=('HOST_PORT', 'TOKEN'), help="Start a server on [HOST:]PORT for use with containers, requires TOKEN for auth")

    parser.add_argument('--pretty', action='store_true', help='For --json, pretty-print')

    parser.add_argument('--version', action='store_true')
    parser.add_argument('--debug', action='store_true')

    cache_group = parser.add_argument_group('Caching')
    cache_group.add_argument('--cache-file')
    buffer_type = lambda v: timedelta(minutes=int(v))
    buffer_default = timedelta(minutes=10)
    cache_group.add_argument('--cache-expiration-buffer', type=buffer_type, default=buffer_default, metavar='MINUTES', help='Expiration buffer in minutes, defaults to 10 minutes')
    cache_group.add_argument('--refresh', action='store_true', help='Refresh the cache')

    args = parser.parse_args()

    if args.version:
        print(__version__)
        parser.exit()

    if not any([args.format, args.exec, args.credentials_file_profile, args.container]):
        args.format = 'json'
        args.pretty = True

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)

    if args.container:
        try:
            args.container = parse_container_arg(args.container)
        except Exception:
            parser.error("invalid value for --container")
        if args.cache_file:
            parser.error("cannot use --cache-file with --container")

    for key in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN']:
        os.environ.pop(key, None)

    # if args.profile:
    #     for key in ['AWS_PROFILE', 'AWS_DEFAULT_PROFILE']:
    #         os.environ.pop(key, None)

    credentials = None

    if args.cache_file and not args.refresh:
        credentials = load_cache(args.cache_file, args.cache_expiration_buffer)

    if credentials and args.credentials_file_profile:
        session = Session(profile=args.profile)
    elif not credentials:
        try:
            session = Session(profile=args.profile)

            credentials = get_credentials(session)

            if not credentials:
                print('Unable to locate credentials.', file=sys.stderr)
                sys.exit(2)

            if args.cache_file:
                save_cache(args.cache_file, credentials)
        except Exception as e:
            if args.debug:
                traceback.print_exc()
            print(str(e), file=sys.stderr)
            sys.exit(3)

    if args.exec:
        for key in ['AWS_PROFILE', 'AWS_DEFAULT_PROFILE']:
            os.environ.pop(key, None)

        os.environ.update({
            'AWS_ACCESS_KEY_ID': credentials.AccessKeyId,
            'AWS_SECRET_ACCESS_KEY': credentials.SecretAccessKey,
        })
        if credentials.SessionToken:
            os.environ['AWS_SESSION_TOKEN'] = credentials.SessionToken
        if credentials.Expiration:
            os.environ['AWS_CREDENTIALS_EXPIRATION'] = credentials.Expiration.strftime(TIME_FORMAT)

        region_name = session.get_config_variable('region')
        if region_name:
            os.environ['AWS_DEFAULT_REGION'] = region_name

        command = ' '.join(shlex.quote(arg) for arg in args.exec)
        os.system(command)
    elif args.format == 'json':
        data = {
            'Version': 1,
            'AccessKeyId': credentials.AccessKeyId,
            'SecretAccessKey': credentials.SecretAccessKey,
        }
        if credentials.SessionToken:
            data['SessionToken'] = credentials.SessionToken
        if credentials.Expiration:
            data['Expiration'] = credentials.Expiration.strftime(TIME_FORMAT)

        if args.pretty:
            json_kwargs={'indent': 2}
        else:
            json_kwargs={'separators': (',', ':')}

        print(json.dumps(data, **json_kwargs))
    elif args.format in ['env', 'env-export']:
        if args.format == 'env-export':
            prefix = 'export '
        else:
            prefix = ''
        lines = [
            '{}AWS_ACCESS_KEY_ID={}'.format(prefix, credentials.AccessKeyId),
            '{}AWS_SECRET_ACCESS_KEY={}'.format(prefix, credentials.SecretAccessKey),
        ]
        if credentials.SessionToken:
            lines.append('{}AWS_SESSION_TOKEN={}'.format(prefix, credentials.SessionToken))
        if credentials.Expiration:
            lines.append('{}AWS_CREDENTIALS_EXPIRATION={}'.format(prefix, credentials.Expiration.strftime(TIME_FORMAT)))
        print('\n'.join(lines))
    elif args.credentials_file_profile:
        values = {
            'aws_access_key_id': credentials.AccessKeyId,
            'aws_secret_access_key': credentials.SecretAccessKey,
        }
        if credentials.SessionToken:
            values['aws_session_token'] = credentials.SessionToken
        if credentials.Expiration:
            values['aws_credentials_expiration'] = credentials.Expiration.strftime(TIME_FORMAT)

        write_values(session, args.credentials_file_profile, values)
    elif args.container:
        server_address, token = args.container
        handler_class = functools.partial(ContainerRequestHandler,
            token=token,
            session=session,
        )
        server = HTTPServer(server_address, handler_class)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass
    else:
        print("ERROR: no option set (this should never happen)", file=sys.stderr)
        sys.exit(1)
예제 #8
0
 def credentials_file_path(session: Session, expand_user: bool = False):
     cred_path = session.get_config_variable("credentials_file")
     return path.expanduser(cred_path) if expand_user else cred_path
 def __init__(self) -> None:
     botocore_session = Session()
     self.credentials = botocore_session.get_credentials()
     self.region_name = botocore_session.get_config_variable('region')