def test_list_invalid_field(mocker): mocker.patch("aws_gate.decorators.is_existing_region", return_value=True) mocker.patch("aws_gate.decorators.is_existing_profile", return_value=True) with pytest.raises(ValueError): list_instances(profile_name="default", region_name="eu-west-1", fields=["invalid-field"])
def test_list_instances(self): with patch('sys.stdout', new_callable=io.StringIO) as mock_stdout, \ patch('aws_gate.list.get_aws_resource', return_value=self.ec2), \ patch('aws_gate.list.get_aws_client', return_value=self.ssm), \ patch('aws_gate.decorators.is_existing_region', return_value=True), \ patch('aws_gate.decorators.is_existing_profile', return_value=True): list_instances(profile_name='default', region_name='eu-west-1') self.assertEqual(mock_stdout.getvalue(), "i-0c32153096cd68a6d - dummy-instance\n")
def main(): # We want to provide default values in cases they are not configured in ~/.aws/config or availabe as # environment variables default_region = get_default_region() if default_region is None: default_region = AWS_DEFAULT_REGION # We try to obtain default profile from the environment or use 'default' to save call to boto3. # boto3 will also return 'default': https://github.com/boto/boto3/blob/develop/boto3/session.py#L93 default_profile = os.environ.get('AWS_PROFILE') or 'default' args = parse_arguments() if not DEBUG: sys.excepthook = lambda exc_type, exc_value, traceback: logger.error( exc_value) log_level = logging.ERROR log_format = '%(message)s' # We want to silence dependencies logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) if args.verbose: log_level = logging.INFO if DEBUG: log_level = logging.DEBUG log_format = '%(asctime)s - %(name)-16s - %(levelname)-5s - %(message)s' logging.basicConfig(level=log_level, stream=sys.stderr, format=log_format) try: config = load_config_from_files() except (ValidationError, ScannerError) as e: raise ValueError('Invalid configuration provided: {}'.format( e.message)) profile = _get_profile(args=args, config=config, default=default_profile) region = _get_region(args=args, config=config, default=default_region) # breakpoint() if args.subcommand == 'session': session(config=config, instance_name=args.instance_name, region_name=region, profile_name=profile) if args.subcommand in ['ls', 'list']: list_instances(region_name=args.region, profile_name=args.profile)
def test_list(mocker, ec2, ssm, capsys): mocker.patch("aws_gate.list.get_aws_resource", return_value=ec2) mocker.patch("aws_gate.list.get_aws_client", return_value=ssm) mocker.patch("aws_gate.decorators.is_existing_region", return_value=True) mocker.patch("aws_gate.decorators.is_existing_profile", return_value=True) expected_data = [ "i-0c32153096cd68a6d", "dummy-instance", "eu-west-1a", "vpc-1981f29759da4a354", "10.69.104.49\n", ] expected = " ".join(expected_data) list_instances(profile_name="default", region_name="eu-west-1") out, _ = capsys.readouterr() assert out == expected
def test_list_instances_invalid_region(self): with patch('aws_gate.decorators.is_existing_profile', return_value=True): with self.assertRaises(ValueError): list_instances(profile_name='default', region_name='invalid-region')
def main(): args = parse_arguments() if not DEBUG: sys.excepthook = lambda exc_type, exc_value, traceback: logger.error( exc_value) log_level = logging.ERROR log_format = "%(message)s" # We want to silence dependencies logging.getLogger("botocore").setLevel(logging.CRITICAL) logging.getLogger("boto3").setLevel(logging.CRITICAL) logging.getLogger("urllib3").setLevel(logging.CRITICAL) if args.verbose: log_level = logging.INFO if DEBUG: log_level = logging.DEBUG log_format = "%(asctime)s - %(name)-28s - %(levelname)-5s - %(message)s" logging.basicConfig(level=log_level, stream=sys.stderr, format=log_format) try: config = load_config_from_files() except (ValidationError, ScannerError) as e: raise ValueError("Invalid configuration provided: {}".format(e)) # We want to provide default values in cases they are not configured # in ~/.aws/config or availabe a environment variables default_region = get_default_region() if default_region is None: default_region = AWS_DEFAULT_REGION # We try to obtain default profile from the environment or use 'default' to # save a call to boto3. In the environment, we check if we are being called # from aws-vault first or not. Then we return 'default' as boto3 will # https://github.com/boto/boto3/blob/develop/boto3/session.py#L93 if "AWS_VAULT" in os.environ: logger.debug( "aws-vault usage detected, defaulting to the AWS profile from $AWS_VAULT" ) default_profile = (os.environ.get("AWS_VAULT") or os.environ.get("AWS_PROFILE") or AWS_DEFAULT_PROFILE) profile = _get_profile(args=args, config=config, default=default_profile) region = _get_region(args=args, config=config, default=default_region) logger.debug('Using AWS profile "%s" in region "%s"', profile, region) if args.subcommand == "bootstrap": bootstrap(force=args.force) if args.subcommand == "session": session( config=config, instance_name=args.instance_name, region_name=region, profile_name=profile, ) if args.subcommand == "ssh": ssh( config=config, instance_name=args.instance_name, region_name=region, profile_name=profile, user=args.os_user, port=args.port, key_type=args.key_type, key_size=args.key_size, command=args.command, ) if args.subcommand == "ssh-config": ssh_config(region_name=region, profile_name=profile, user=args.os_user, port=args.port) if args.subcommand == "ssh-proxy": ssh_proxy( config=config, instance_name=args.instance_name, region_name=region, profile_name=profile, user=args.os_user, port=args.port, key_type=args.key_type, key_size=args.key_size, ) if args.subcommand in ["ls", "list"]: fields = args.output.split(",") list_instances( region_name=region, profile_name=profile, output_format=args.format, fields=fields, )
def test_list_invalid_region(mocker): mocker.patch("aws_gate.decorators.is_existing_profile", return_value=True) with pytest.raises(ValueError): list_instances(profile_name="default", region_name="invalid-region")
def test_list_invalid_profile(): with pytest.raises(ValueError): list_instances(profile_name="invalid-profile", region_name="eu-west-1")
def test_list_instances(self, mock_client, mock_resource, mock_stdout): mock_client.return_value = self.ssm mock_resource.return_value = self.ec2 list_instances() self.assertEqual(mock_stdout.getvalue(), "i-0c32153096cd68a6d - dummy-instance\n")
def main(): if 'AWS_PROFILE' in os.environ: default_profile = os.environ['AWS_PROFILE'] else: default_profile = 'default' if 'AWS_DEFAULT_REGION' in os.environ: default_region = os.environ['AWS_DEFAULT_REGION'] else: default_region = 'eu-west-1' parser = argparse.ArgumentParser(description=__description__) parser.add_argument('-v', '--verbose', help='increase output verbosity', action='store_true') parser.add_argument( '--version', action='version', version='%(prog)s {version}'.format(version=__version__)) subparsers = parser.add_subparsers(title='subcommands', dest='subcommand', metavar='{session, list}') # 'session' subcommand session_parser = subparsers.add_parser( 'session', help='Open new session on instance and connect to it') session_parser.add_argument('-p', '--profile', help='AWS profile to use', default=default_profile) session_parser.add_argument('-r', '--region', help='AWS region to use', default=default_region) session_parser.add_argument('instance_name', help='Instance we wish to open session to') ls_parser = subparsers.add_parser('list', aliases=['ls'], help='List available instances') ls_parser.add_argument('-p', '--profile', help='AWS profile to use', default=default_profile) ls_parser.add_argument('-r', '--region', help='AWS region to use', default=default_region) args = parser.parse_args() if not args.subcommand: parser.print_help() sys.exit(0) if not DEBUG: sys.excepthook = lambda exc_type, exc_value, traceback: logger.error( exc_value) log_level = logging.ERROR log_format = '%(message)s' # We want to silence dependencies logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) if args.verbose: log_level = logging.INFO if DEBUG: log_level = logging.DEBUG log_format = '%(asctime)s - %(name)-16s - %(levelname)-5s - %(message)s' logging.basicConfig(level=log_level, stream=sys.stderr, format=log_format) if not is_existing_profile(args.profile): raise ValueError('Invalid profile provided: {}'.format(args.profile)) if args.subcommand == 'session': session(instance_name=args.instance_name, region_name=args.region, profile_name=args.profile) if args.subcommand in ['ls', 'list']: list_instances(region_name=args.region, profile_name=args.profile)