Ejemplo n.º 1
0
def create_environment(environment):
    """
    Creates an Elastic Beanstalk environment
    """
    LOG.debug('Inside create_environment api wrapper')

    kwargs = environment.convert_to_kwargs()

    if environment.database:
        # need to know region for database string
        region = aws.get_region_name()

        # Database is a dictionary
        kwargs['TemplateSpecification'] = {
            'TemplateSnippets': [{
                'SnippetName':
                'RdsExtensionEB',
                'Order':
                10000,
                'SourceUrl':
                'https://s3.amazonaws.com/'
                'elasticbeanstalk-env-resources-' + region +
                '/eb_snippets/rds/rds.json'
            }]
        }

    result = _make_api_call('create_environment', **kwargs)

    # convert to object
    env = Environment.json_to_environment_object(result)
    request_id = result['ResponseMetadata']['RequestId']
    return env, request_id
    def test_status__verbose_mode__elbv2(
            self, get_target_group_healths_mock,
            get_target_groups_for_load_balancer_mock,
            get_environment_resources_mock, get_default_repository_mock,
            get_default_branch_mock, echo_mock, log_alert_mock,
            find_solution_stack_from_string_mock, get_environment_mock):
        environment_object = Environment.json_to_environment_object(
            mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments'][0])
        environment_object.platform = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
        )
        get_environment_mock.return_value = environment_object
        find_solution_stack_from_string_mock.return_value = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
        )
        get_default_branch_mock.return_value = 'branch'
        get_default_repository_mock.return_value = 'repository'
        get_environment_resources_mock.return_value = mock_responses.DESCRIBE_ENVIRONMENT_RESOURCES_RESPONSE__ELBV2_ENVIRONMENT
        get_target_groups_for_load_balancer_mock.return_value = mock_responses.DESCRIBE_TARGET_GROUPS_RESPONSE[
            'TargetGroups']
        get_target_group_healths_mock.return_value = {
            "arn:aws:elasticloadbalancing:us-west-2:123123123123:targetgroup/awseb-AWSEB-179V6JWWL9HI5/e57decc4139bfdd2":
            mock_responses.DESCRIBE_TARGET_HEALTH_RESPONSE
        }

        statusops.status('my-application', 'environment-1', True)

        log_alert_mock.assert_not_called()
        echo_mock.assert_has_calls([
            mock.call('Environment details for:', 'environment-1'),
            mock.call('  Application name:', 'my-application'),
            mock.call('  Region:', 'us-west-2'),
            mock.call('  Deployed Version:', 'Sample Application'),
            mock.call('  Environment ID:', 'e-sfsdfsfasdads'),
            mock.call(
                '  Platform:',
                PlatformVersion(
                    'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
                )),
            mock.call('  Tier:', Tier.from_raw_string('webserver')),
            mock.call('  CNAME:',
                      'environment-1.us-west-2.elasticbeanstalk.com'),
            mock.call(
                '  Updated:',
                datetime.datetime(2018,
                                  3,
                                  27,
                                  23,
                                  47,
                                  41,
                                  830000,
                                  tzinfo=tz.tzutc())),
            mock.call('  Status:', 'Ready'),
            mock.call('  Health:', 'Green'),
            mock.call('  Running instances:', 1),
            mock.call('          ', 'i-01641763db1c0cb47: healthy'),
            mock.call('Current CodeCommit settings:'),
            mock.call('  Repository: repository'),
            mock.call('  Branch: branch')
        ])
Ejemplo n.º 3
0
def _api_to_environment(api_dict, want_solution_stack = False):
    # Convert solution_stack and tier to objects
    try:
        if want_solution_stack:
            solution_stack_name = api_dict['SolutionStackName']
            platform = SolutionStack(solution_stack_name)
        else:
            platform_arn = api_dict['PlatformArn']
            platform = PlatformVersion(platform_arn)
    except KeyError:
        platform = SolutionStack(api_dict['SolutionStackName'])

    tier = api_dict['Tier']
    tier = Tier(tier['Name'], tier['Type'], tier['Version'])

    env = Environment(
        version_label=api_dict.get('VersionLabel'),
        status=api_dict.get('Status'),
        app_name=api_dict.get('ApplicationName'),
        health=api_dict.get('Health'),
        id=api_dict.get('EnvironmentId'),
        date_updated=api_dict.get('DateUpdated'),
        platform=platform,
        description=api_dict.get('Description'),
        name=api_dict.get('EnvironmentName'),
        date_created=api_dict.get('DateCreated'),
        tier=tier,
        cname=api_dict.get('CNAME', 'UNKNOWN'),
        option_settings=api_dict.get('OptionSettings'),
        is_abortable=api_dict.get('AbortableOperationInProgress', False),
        environment_links=api_dict.get('EnvironmentLinks'),
        environment_arn=api_dict.get('EnvironmentArn')
    )
    return env
    def test_ask_for_customer_confirmation_to_delete_all_application_resources(
            self,
            validate_action_mock,
            echo_mock,
            get_environment_names_mock,
            describe_application_mock
    ):
        describe_application_mock.return_value = mock_responses.DESCRIBE_APPLICATIONS_RESPONSE['Applications'][0]
        get_environment_names_mock.return_value = Environment.json_to_environment_objects_array(
            mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments']
        )

        terminateops.ask_for_customer_confirmation_to_delete_all_application_resources(
            'my-application'
        )

        echo_mock.assert_called_once_with(
            """The application "my-application" and all its resources will be deleted.
This application currently has the following:
Running environments: 4
Configuration templates: 0
Application versions: 1
"""
        )

        validate_action_mock.assert_called_once_with(
            'To confirm, type the application name',
            'my-application'
        )
Ejemplo n.º 5
0
def get_environment(app_name=None,
                    env_name=None,
                    env_id=None,
                    include_deleted=False,
                    deleted_back_to=None,
                    want_solution_stack=False):
    LOG.debug('Inside get_environment api wrapper')

    kwargs = {}
    if app_name is not None:
        kwargs['ApplicationName'] = app_name
    if env_name is not None:
        kwargs['EnvironmentNames'] = [env_name]
    if env_id is not None:
        kwargs['EnvironmentIds'] = [env_id]
    if include_deleted and deleted_back_to is not None:
        kwargs['IncludedDeletedBackTo'] = deleted_back_to

    result = _make_api_call('describe_environments',
                            IncludeDeleted=include_deleted,
                            **kwargs)

    envs = result['Environments']
    if len(envs) < 1:
        env_str = env_id if env_name is None else env_name
        raise NotFoundError('Environment "' + env_str + '" not Found.')
    else:
        return Environment.json_to_environment_object(envs[0],
                                                      want_solution_stack)
Ejemplo n.º 6
0
def create_environment(environment):
    """
    Creates an Elastic Beanstalk environment
    """
    LOG.debug('Inside create_environment api wrapper')

    kwargs = environment.convert_to_kwargs()

    if environment.database:
        # need to know region for database string
        region = aws.get_region_name()

        # Database is a dictionary
        kwargs['TemplateSpecification'] = {
            'TemplateSnippets': [
                {'SnippetName': 'RdsExtensionEB',
                 'Order': 10000,
                 'SourceUrl': 'https://s3.amazonaws.com/'
                              'elasticbeanstalk-env-resources-' + region +
                              '/eb_snippets/rds/rds.json'}
            ]
        }

    result = _make_api_call('create_environment', **kwargs)

    # convert to object
    env = Environment.json_to_environment_object(result)
    request_id = result['ResponseMetadata']['RequestId']
    return env, request_id
    def test_retrieve_application_version_url__app_version_url_not_found_in_app_source__raises_not_found_error(
            self, get_template_mock, wait_until_stack_exists_mock,
            get_environment_mock):
        io._log_warning = io.log_warning
        io.log_warning = mock.MagicMock()

        get_template_response = {
            "TemplateBody": {
                "Parameters": {
                    "AppSource": {
                        "NoEcho": "true",
                        "Type": "String",
                        "Description": "The url of the application source."
                    }
                },
                "Description":
                "AWS Elastic Beanstalk environment (Name: 'my_env_name'  Id: 'my_env_id')",
            }
        }

        get_environment_mock.return_value = Environment(name='my_env_name',
                                                        id='my_env_id')
        get_template_mock.return_value = get_template_response

        createops.retrieve_application_version_url('my_env_name')

        io.log_warning.assert_called_with(
            'Cannot find app source for environment. ')

        io.log_warning = io._log_warning
    def test_retrieve_application_version_url__successfully_returns_sample_app_url(
            self, get_template_mock, wait_until_stack_exists_mock,
            get_environment_mock):
        get_template_response = {
            "TemplateBody": {
                "Parameters": {
                    "AppSource": {
                        "NoEcho": "true",
                        "Type": "String",
                        "Description": "The url of the application source.",
                        "Default":
                        "http://sample-app-location/python-sample.zip"
                    },
                },
                "Description":
                "AWS Elastic Beanstalk environment (Name: 'my_env_name'  Id: 'my_env_id')",
            }
        }
        get_environment_mock.return_value = Environment(name='my_env_name',
                                                        id='my_env_id')
        get_template_mock.return_value = get_template_response

        self.assertEqual(
            "http://sample-app-location/python-sample.zip",
            createops.retrieve_application_version_url('my_env_name'))
    def test_clone_env__environment_name_is_unavailable(
            self,
            prompt_for_environment_name_mock,
            get_unique_name_mock,
            get_environment_names_mock,
            echo_mock,
            prompt_for_cname_mock,
            clone_environment_mock
    ):
        clone_request_mock = mock.MagicMock()
        clone_request_mock.app_name = 'my-application'
        clone_request_mock.env_name = 'unavailable-environment-name'
        prompt_for_cname_mock.return_value = 'my-environment-cname'
        get_environment_names_mock.return_value = ['environment-1', 'environment-2']
        get_unique_name_mock.return_value = 'environment-3'
        prompt_for_environment_name_mock.return_value = 'my-environment'

        environment_mock = Environment.json_to_environment_object(mock_responses.CREATE_ENVIRONMENT_RESPONSE)
        clone_environment_mock.side_effect = [
            cloneops.InvalidParameterValueError('Environment unavailable-environment-name already exists.'),
            (environment_mock, 'request-id')
        ]

        self.assertEqual(
            (environment_mock, 'request-id'),
            cloneops.clone_env(clone_request_mock)
        )

        echo_mock.assert_called_once_with('An environment with that name already exists.')
        get_environment_names_mock.assert_called_once_with('my-application')
        get_unique_name_mock.assert_called_once_with(
            'unavailable-environment-name',
            ['environment-1', 'environment-2']
        )
        self.assertEqual('my-environment', clone_request_mock.env_name)
Ejemplo n.º 10
0
def get_environment_settings(app_name, env_name):
    LOG.debug('Inside get_environment_settings api wrapper')
    result = _make_api_call('describe_configuration_settings',
                            ApplicationName=app_name,
                            EnvironmentName=env_name)

    return Environment.json_to_environment_object(result['ConfigurationSettings'][0])
Ejemplo n.º 11
0
def get_environment_settings(app_name, env_name):
    LOG.debug('Inside get_environment_settings api wrapper')
    result = _make_api_call('describe_configuration_settings',
                            ApplicationName=app_name,
                            EnvironmentName=env_name)

    return Environment.json_to_environment_object(
        result['ConfigurationSettings'][0])
Ejemplo n.º 12
0
def environment_from_mock_responses(environment_name):
    all_available_environments = Environment.json_to_environment_objects_array(
        mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments']
    )

    return [
        environment for environment in all_available_environments if environment.name == environment_name
    ][0]
Ejemplo n.º 13
0
    def test_clone__prompt_for_choice_between_current_and_latest_platform_arn_in_interactive_mode(
            self,
            prompt_for_item_in_list_mock,
            find_solution_stack_from_string_mock,
            is_cname_available_mock,
            get_app_name_mock,
            get_env_name_mock,
            make_cloned_env_mock,
            clone_environment_request_mock,
            prompt_for_environment_name_mock,
            get_environment_names_mock,
            get_environment_mock
    ):
        is_cname_available_mock.return_value = True
        find_solution_stack_from_string_mock.return_value = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.2 running on 64bit Amazon Linux/2.6.5'
        )
        get_app_name_mock.return_value = 'my-application'
        get_env_name_mock.return_value = 'environment-1'
        prompt_for_environment_name_mock.return_value = 'environment-1-clone'
        get_environment_names_mock.return_value = Environment.json_to_environment_objects_array(
            mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments']
        )
        get_environment_mock.return_value = environment_from_mock_responses('environment-1')
        prompt_for_item_in_list_mock.return_value = 'Latest  (arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.2 running on 64bit Amazon Linux/2.6.5)'
        clone_environment_request_mock.return_value = mock.MagicMock()
        clone_environment_request = clone_environment_request_mock.return_value

        app = EB(argv=['clone', '--cname', 'some-cname'])
        app.setup()
        app.run()

        prompt_for_environment_name_mock.assert_called_once_with(
            default_name='my-application-clone',
            prompt_text='Enter name for Environment Clone'
        )
        prompt_for_item_in_list_mock.assert_called_once_with(
            [
                'Latest  (arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.2 running on 64bit Amazon Linux/2.6.5)',
                'Same    (arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.5)'
            ]
        )
        clone_environment_request_mock.assert_called_once_with(
            app_name='environment-1',
            cname='some-cname',
            env_name='environment-1-clone',
            original_name='my-application',
            platform=PlatformVersion(
                'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.2 running on 64bit Amazon Linux/2.6.5'
            ),
            scale=None,
            tags=[]
        )
        make_cloned_env_mock.assert_called_once_with(
            clone_environment_request,
            nohang=False,
            timeout=None
        )
    def test_status__verbose_mode__elb(
            self, get_health_of_instances_mock, get_environment_resources_mock,
            get_default_repository_mock, get_default_branch_mock, echo_mock,
            log_alert_mock, find_solution_stack_from_string_mock,
            get_environment_mock):
        environment_object = Environment.json_to_environment_object(
            mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments'][0])
        environment_object.platform = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
        )
        get_environment_mock.return_value = environment_object
        find_solution_stack_from_string_mock.return_value = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
        )
        get_default_branch_mock.return_value = 'branch'
        get_default_repository_mock.return_value = 'repository'
        get_environment_resources_mock.return_value = mock_responses.DESCRIBE_ENVIRONMENT_RESOURCES_RESPONSE
        get_health_of_instances_mock.return_value = mock_responses.DESCRIBE_INSTANCE_HEALTH[
            'InstanceStates']

        statusops.status('my-application', 'environment-1', True)

        log_alert_mock.assert_not_called()
        echo_mock.assert_has_calls([
            mock.call('Environment details for:', 'environment-1'),
            mock.call('  Application name:', 'my-application'),
            mock.call('  Region:', 'us-west-2'),
            mock.call('  Deployed Version:', 'Sample Application'),
            mock.call('  Environment ID:', 'e-sfsdfsfasdads'),
            mock.call(
                '  Platform:',
                PlatformVersion(
                    'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
                )),
            mock.call('  Tier:', Tier.from_raw_string('webserver')),
            mock.call('  CNAME:',
                      'environment-1.us-west-2.elasticbeanstalk.com'),
            mock.call(
                '  Updated:',
                datetime.datetime(2018,
                                  3,
                                  27,
                                  23,
                                  47,
                                  41,
                                  830000,
                                  tzinfo=tz.tzutc())),
            mock.call('  Status:', 'Ready'),
            mock.call('  Health:', 'Green'),
            mock.call('  Running instances:', 2),
            mock.call('     ', 'i-23452345346456566:', 'InService'),
            mock.call('     ', 'i-21312312312312312:', 'OutOfService'),
            mock.call('Current CodeCommit settings:'),
            mock.call('  Repository: repository'),
            mock.call('  Branch: branch')
        ])
    def test_retrieve_application_version_url__empty_response__raises_not_found_error(
            self, get_template_mock, wait_until_stack_exists_mock,
            get_environment_mock):
        get_template_response = {}

        io._log_warning = io.log_warning
        io.log_warning = mock.MagicMock()

        get_environment_mock.return_value = Environment(name='my_env_name',
                                                        id='my_env_id')
        get_template_mock.return_value = get_template_response
Ejemplo n.º 16
0
def get_environments(env_names=None):
    LOG.debug('Inside get_environments api wrapper')
    result = _make_api_call('describe_environments',
                            EnvironmentNames=env_names or [],
                            IncludeDeleted=False)

    environments = result['Environments']
    if not environments and env_names:
        raise NotFoundError(
            'Could not find any environments from the list: {}'.format(
                ', '.join(env_names)))
    return Environment.json_to_environment_objects_array(environments)
    def test_status__non_verbose_mode__codecommit_not_setup__using_non_latest_platform(
            self, get_default_repository_mock, get_default_branch_mock,
            echo_mock, log_alert_mock, find_solution_stack_from_string_mock,
            get_environment_mock):
        environment_object = Environment.json_to_environment_object(
            mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments'][0])
        environment_object.platform = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.5'
        )
        get_environment_mock.return_value = environment_object
        get_environment_mock.platform = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.5'
        )
        find_solution_stack_from_string_mock.return_value = PlatformVersion(
            'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.6'
        )
        get_default_branch_mock.return_value = None
        get_default_repository_mock.return_value = None

        statusops.status('my-application', 'environment-1', False)

        log_alert_mock.assert_called_once_with(
            'There is a newer version of the platform used by your environment. '
            'You can upgrade your environment to the most recent platform version by typing "eb upgrade".'
        )
        echo_mock.assert_has_calls([
            mock.call('Environment details for:', 'environment-1'),
            mock.call('  Application name:', 'my-application'),
            mock.call('  Region:', 'us-west-2'),
            mock.call('  Deployed Version:', 'Sample Application'),
            mock.call('  Environment ID:', 'e-sfsdfsfasdads'),
            mock.call(
                '  Platform:',
                PlatformVersion(
                    'arn:aws:elasticbeanstalk:us-west-2::platform/PHP 7.1 running on 64bit Amazon Linux/2.6.5'
                )),
            mock.call('  Tier:', Tier.from_raw_string('webserver')),
            mock.call('  CNAME:',
                      'environment-1.us-west-2.elasticbeanstalk.com'),
            mock.call(
                '  Updated:',
                datetime.datetime(2018,
                                  3,
                                  27,
                                  23,
                                  47,
                                  41,
                                  830000,
                                  tzinfo=tz.tzutc())),
            mock.call('  Status:', 'Ready'),
            mock.call('  Health:', 'Green')
        ])
Ejemplo n.º 18
0
def get_app_environments(app_name, include_deleted=False, deleted_back_to=None):
    LOG.debug('Inside get_app_environments api wrapper')

    kwargs = {}
    if include_deleted and deleted_back_to is not None:
        kwargs['IncludedDeletedBackTo'] = deleted_back_to

    result = _make_api_call('describe_environments',
                            ApplicationName=app_name,
                            IncludeDeleted=include_deleted,
                            **kwargs)

    return Environment.json_to_environment_objects_array(result['Environments'])
Ejemplo n.º 19
0
    def test_check_env_lifecycle_state(
        self,
        alert_environment_status_mock,
        get_environment_mock,
    ):
        environment_name = 'environment-1'
        environment = Environment(name=environment_name)
        get_environment_mock.return_value = environment

        deploy._check_env_lifecycle_state(env_name=environment_name)

        get_environment_mock.assert_called_once_with(env_name=environment_name)
        alert_environment_status_mock.assert_called_once_with(environment)
Ejemplo n.º 20
0
def clone_environment(clone):
    LOG.debug('Inside clone_environment api wrapper')

    kwargs = clone.convert_to_kwargs()

    kwargs['TemplateSpecification'] = \
        {'TemplateSource': {'EnvironmentName': clone.original_name}}

    result = _make_api_call('create_environment', **kwargs)

    environment = Environment.json_to_environment_object(result)
    request_id = result['ResponseMetadata']['RequestId']
    return environment, request_id
    def test_clone_env(
            self,
            clone_environment_mock
    ):
        clone_request_mock = mock.MagicMock()

        environment_mock = Environment.json_to_environment_object(mock_responses.CREATE_ENVIRONMENT_RESPONSE)
        clone_environment_mock.return_value = (environment_mock, 'request-id')

        self.assertEqual(
            (environment_mock, 'request-id'),
            cloneops.clone_env(clone_request_mock)
        )
Ejemplo n.º 22
0
def clone_environment(clone):
    LOG.debug('Inside clone_environment api wrapper')

    kwargs = clone.convert_to_kwargs()

    kwargs['TemplateSpecification'] = \
        {'TemplateSource': {'EnvironmentName': clone.original_name}}

    result = _make_api_call('create_environment', **kwargs)

    # convert to object
    environment = Environment.json_to_environment_object(result)
    request_id = result['ResponseMetadata']['RequestId']
    return environment, request_id
Ejemplo n.º 23
0
def get_environments(env_names=None):
    LOG.debug('Inside get_environments api wrapper')
    result = _make_api_call('describe_environments',
                            EnvironmentNames=env_names or [],
                            IncludeDeleted=False)

    environments = result['Environments']
    if not environments and env_names:
        raise NotFoundError(
            'Could not find any environments from the list: {}'.format(
                ', '.join(env_names)
            )
        )
    return Environment.json_to_environment_objects_array(environments)
Ejemplo n.º 24
0
    def test_clone__neither_clone_name_nor_cname_provided__customer_is_prompted_for_both(
            self,
            find_solution_stack_from_string_mock,
            is_cname_available_mock,
            get_app_name_mock,
            get_env_name_mock,
            make_cloned_env_mock,
            clone_environment_request_mock,
            get_cname_from_customer,
            prompt_for_environment_name_mock,
            get_environment_names_mock,
            get_environment_mock
    ):
        is_cname_available_mock.return_value = True
        find_solution_stack_from_string_mock.return_value = self.platform
        get_app_name_mock.return_value = 'my-application'
        get_env_name_mock.return_value = 'environment-1'
        get_cname_from_customer.return_value = 'my-cname'
        prompt_for_environment_name_mock.return_value = 'environment-1-clone'
        get_environment_names_mock.return_value = Environment.json_to_environment_objects_array(
            mock_responses.DESCRIBE_ENVIRONMENTS_RESPONSE['Environments']
        )
        get_environment_mock.return_value = environment_from_mock_responses('environment-1')
        clone_environment_request_mock.return_value = mock.MagicMock()
        clone_environment_request = clone_environment_request_mock.return_value

        app = EB(argv=['clone'])
        app.setup()
        app.run()

        prompt_for_environment_name_mock.assert_called_once_with(
            default_name='my-application-clone',
            prompt_text='Enter name for Environment Clone'
        )
        clone_environment_request_mock.assert_called_once_with(
            app_name='environment-1',
            cname='my-cname',
            env_name='environment-1-clone',
            original_name='my-application',
            platform=self.platform,
            scale=None,
            tags=[]
        )
        make_cloned_env_mock.assert_called_once_with(
            clone_environment_request,
            nohang=False,
            timeout=None
        )
Ejemplo n.º 25
0
def get_app_environments(app_name,
                         include_deleted=False,
                         deleted_back_to=None):
    LOG.debug('Inside get_app_environments api wrapper')

    kwargs = {}
    if include_deleted and deleted_back_to is not None:
        kwargs['IncludedDeletedBackTo'] = deleted_back_to

    result = _make_api_call('describe_environments',
                            ApplicationName=app_name,
                            IncludeDeleted=include_deleted,
                            **kwargs)

    return Environment.json_to_environment_objects_array(
        result['Environments'])
Ejemplo n.º 26
0
    def setUp(self):
        self.patcher_elasticbeanstalk = mock.patch(
            'ebcli.operations.appversionops.elasticbeanstalk')
        self.patcher_io = mock.patch('ebcli.operations.appversionops.io')
        self.mock_elasticbeanstalk = self.patcher_elasticbeanstalk.start()
        self.mock_io = self.patcher_io.start()

        self.mock_elasticbeanstalk.get_application_versions.return_value = {
            u'ApplicationVersions': [{
                u'ApplicationName': self.app_name,
                u'VersionLabel': self.version_to_delete
            }, {
                u'ApplicationName': self.app_name,
                u'VersionLabel': self.version_deployed
            }]
        }
        self.mock_elasticbeanstalk.get_app_environments.return_value = \
            [Environment(version_label=self.version_deployed, app_name=self.app_name, name='wow')]
Ejemplo n.º 27
0
    def do_command(self):
        self.environment_passed = not not self.app.pargs.environment_name
        self.environment_name = self.app.pargs.environment_name
        self.resource = self.app.pargs.resource

        self.list_argument = self.app.pargs.list

        self.add_arguments = self.app.pargs.add
        self.delete_arguments = self.app.pargs.delete
        self.update_arguments = self.app.pargs.update

        self.verbose = self.app.pargs.verbose

        self.__assert_list_argument_xor_modifier_arguments_specified()
        self.__assert_resource_argument_conflict()

        if self.environment_passed:
            self.resource = elasticbeanstalk.get_environment_arn(
                self.environment_name)
            resource_type = Environment
        elif self.resource and Environment.is_valid_arn(self.resource):
            resource_type = Environment
        elif self.resource:
            resource_type = None
        else:
            self.resource = elasticbeanstalk.get_environment_arn(
                self.get_env_name())
            resource_type = Environment

        tagops = TagOps(self.resource, self.verbose)

        if self.list_argument:
            tagops.list_tags()

            return

        tagops.handle_addition_string(
            self.add_arguments) if self.add_arguments else None
        tagops.handle_deletion_string(
            self.delete_arguments) if self.delete_arguments else None
        tagops.handle_update_string(
            self.update_arguments) if self.update_arguments else None

        tagops.update_tags(resource_type)
    def test_clone_env__cname_is_unavailable(
            self,
            echo_mock,
            prompt_for_cname_mock,
            clone_environment_mock
    ):
        clone_request_mock = mock.MagicMock()
        prompt_for_cname_mock.return_value = 'my-environment-cname'

        environment_mock = Environment.json_to_environment_object(mock_responses.CREATE_ENVIRONMENT_RESPONSE)
        clone_environment_mock.side_effect = [
            cloneops.InvalidParameterValueError('DNS name (in-use-cname.com) is not available.'),
            (environment_mock, 'request-id')
        ]

        self.assertEqual(
            (environment_mock, 'request-id'),
            cloneops.clone_env(clone_request_mock)
        )

        echo_mock.assert_called_once_with('The CNAME you provided is already in use.\n')
Ejemplo n.º 29
0
def get_environment(app_name=None, env_name=None, env_id=None, include_deleted=False, deleted_back_to=None, want_solution_stack=False):
    LOG.debug('Inside get_environment api wrapper')

    kwargs = {}
    if app_name is not None:
        kwargs['ApplicationName'] = app_name
    if env_name is not None:
        kwargs['EnvironmentNames'] = [env_name]
    if env_id is not None:
        kwargs['EnvironmentIds'] = [env_id]
    if include_deleted and deleted_back_to is not None:
        kwargs['IncludedDeletedBackTo'] = deleted_back_to

    result = _make_api_call('describe_environments',
                            IncludeDeleted=include_deleted,
                            **kwargs)

    envs = result['Environments']
    if len(envs) < 1:
        env_str = env_id if env_name is None else env_name
        raise NotFoundError('Environment "' + env_str + '" not Found.')
    else:
        return Environment.json_to_environment_object(envs[0], want_solution_stack)
Ejemplo n.º 30
0
class TestRestoreEnvironment(unittest.TestCase):
    current_time = datetime.now()
    request_id = 'foo-request-id'
    env_id = 'e-1234567890'
    app = Application(name="some-app")
    env1 = {'EnvironmnetId': env_id, 'EnvironmentName': "env1", 'VersionLabel': "v1",
            'ApplicationName': "app1", 'Status' : 'Ready',
            'DateUpdated': (date.today() - timedelta(days=10))}
    env2 = {'EnvironmnetId': 'e-0987654321', 'EnvironmentName': "env2", 'VersionLabel': "v2",
            'ApplicationName': "some-app", 'Status': 'Terminated',
            'DateUpdated': (date.today())}
    env_object = Environment(id=env_id, name="env1", version_label="v1", app_name="app1",
                       date_updated=(date.today() - timedelta(days=10)), status='Terminated')

    def setUp(self):
        self.patcher_beanstalk = mock.patch('ebcli.operations.restoreops.elasticbeanstalk')
        self.mock_beanstalk = self.patcher_beanstalk.start()
        self.env_object.status = 'Terminated'

    def tearDown(self):
        self.patcher_beanstalk.stop()

    def test_validate_restore_bad_env(self):
        self.env_object.status = 'Ready'
        self.mock_beanstalk.get_environment.return_value = self.env_object
        self.assertRaises(InvalidParameterValueError, restoreops.validate_restore, self.env_id)

    @mock.patch('ebcli.operations.restoreops.get_date_cutoff')
    def test_validate_restore_good_env(self, mock_date):
        mock_date.return_value = self.current_time
        self.mock_beanstalk.get_environment.return_value = self.env_object
        restoreops.validate_restore(self.env_id)
        self.mock_beanstalk.get_environment.assert_called_with(env_id=self.env_id, include_deleted=True,
                                               deleted_back_to=self.current_time)

    @mock.patch('ebcli.operations.restoreops.commonops')
    def test_restore_with_good_env(self, mock_common_ops):
        self.mock_beanstalk.get_environment.return_value = self.env_object
        self.mock_beanstalk.rebuild_environment.return_value = self.request_id

        restoreops.restore(self.env_id)

        mock_common_ops.wait_for_success_events.assert_called_with(self.request_id, timeout_in_minutes=None,
                                                                   can_abort=True)

    def test_restore_with_bad_param_exception(self):
        self.env_object.status = 'Ready'
        self.mock_beanstalk.get_environment.return_value = self.env_object

        self.mock_beanstalk.rebuild_environment.side_effect = [
            InvalidParameterValueError('Could not rebuild environment some-name because the cname is taken')]

        self.assertRaises(InvalidParameterValueError, restoreops.restore, self.env_id)


    def test_fetch_restorable_envs(self):
        self.mock_beanstalk.get_raw_app_environments.return_value = [self.env1, self.env2]

        environments = restoreops.get_restorable_envs(self.app)

        self.assertNotIn(self.env1, environments,
                         "Non-terminated environment returned in restorable environments when it should not be")
        self.assertIn(self.env2, environments, "Terminated environment not in restorable environments when it should be")
Ejemplo n.º 31
0
def get_all_environments():
    LOG.debug('Inside get_all_environments api wrapper')
    result = _make_api_call('describe_environments', IncludeDeleted=False)

    return Environment.json_to_environment_objects_array(
        result['Environments'])
Ejemplo n.º 32
0
def get_all_environments():
    LOG.debug('Inside get_all_environments api wrapper')
    result = _make_api_call('describe_environments',
                            IncludeDeleted=False)

    return Environment.json_to_environment_objects_array(result['Environments'])