def open_console(app_name, env_name): if utils.is_ssh(): raise NotSupportedError('The console command is not supported' ' in an ssh type session') env = None if env_name is not None: env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) region = aws.get_region_name() if env is not None: page = 'environment/dashboard' else: page = 'application/overview' app_name = utils.url_encode(app_name) console_url = 'console.aws.amazon.com/elasticbeanstalk/home?' console_url += 'region=' + region console_url += '#/' + page + '?applicationName=' + app_name if env is not None: console_url += '&environmentId=' + env.id commonops.open_webpage_in_browser(console_url, ssl=True)
def get_environment_platform(app_name, env_name, want_solution_stack=False): env = elasticbeanstalk.get_environment( app_name=app_name, env_name=env_name, want_solution_stack=want_solution_stack ) return env.platform
def validate_restore(env_id): """ Do client side validation because rebuild will rebuild a running environments as well """ env = elasticbeanstalk.get_environment(env_id=env_id, include_deleted=True, deleted_back_to=get_date_cutoff()) if env.status != 'Terminated': raise InvalidParameterValueError('Environment {0} ({1}) is currently {2}, must be "Terminated" to restore' .format(env.name, env.id, env.status))
def status(app_name, env_name, verbose): env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) env.print_env_details(io.echo, elasticbeanstalk.get_environments, elasticbeanstalk.get_environment_resources, health=True) _print_information_about_elb_and_instances(env_name) if verbose else None alert_environment_status(env) _print_codecommit_repositories()
def _get_health_data(self): timestamp = datetime.now(tz.tzutc()) env = elasticbeanstalk.get_environment(app_name=self.app_name, env_name=self.env_name) env_dict = elasticbeanstalk.get_environment_resources(self.env_name) env_dict = env_dict['EnvironmentResources'] load_balancers = env_dict.get('LoadBalancers', None) if load_balancers and len(load_balancers) > 0: load_balancer_name = env_dict.get('LoadBalancers')[0].get('Name') instance_states = elb.get_health_of_instances(load_balancer_name) else: instance_states = [] instance_ids = [i['Id'] for i in env_dict.get('Instances', [])] total_instances = len(instance_ids) total_in_service = len( [i for i in instance_states if i['State'] == 'InService']) env_data = { 'EnvironmentName': env.name, 'Color': env.health, 'Status': env.status, 'Total': total_instances, 'InService': total_in_service, 'Other': total_instances - total_in_service } data = {'environment': env_data, 'instances': []} # Get Instance Health for i in instance_states: instance = { 'id': i['InstanceId'], 'state': i['State'], 'description': i['Description'] } ec2_health = ec2.describe_instance(instance['id']) instance['health'] = ec2_health['State']['Name'] data['instances'].append(instance) # Get Health for instances not in Load Balancer yet for i in instance_ids: instance = {'id': i} if i not in [x['InstanceId'] for x in instance_states]: instance['description'] = 'N/A (Not registered ' \ 'with Load Balancer)' instance['state'] = 'n/a' ec2_health = ec2.describe_instance(i) instance['health'] = ec2_health['State']['Name'] data['instances'].append(instance) data['environment']['RefreshedAt'] = timestamp return data
def deployment_logs_log_group_name(env_name): """ Determines the default deployment logGroup for the environment, `env_name` :param env_name: An Elastic Beanstalk environment name :return: 'var/log/eb-activity.log' if the environment is using a non-Windows platform, 'EBDeploy-Log' otherwise """ environment = elasticbeanstalk.get_environment(env_name=env_name) if 'windows' in environment.platform.name.lower(): log_group_suffix = 'EBDeploy-Log' else: log_group_suffix = 'var/log/eb-activity.log' return cloudwatch_log_group_prefix_for_environment(env_name) + '/' + log_group_suffix
def open_app(app_name, env_name): env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) settings = elasticbeanstalk.describe_configuration_settings( app_name, env_name) option_settings = settings.get('OptionSettings', []) http_port = elasticbeanstalk.get_option_setting( option_settings, namespaces.LOAD_BALANCER, option_names.LOAD_BALANCER_HTTP_PORT) if http_port == 'OFF': ssl = True else: ssl = False commonops.open_webpage_in_browser(env.cname, ssl=ssl)
def make_cloned_env(clone_request, nohang=False, timeout=None): io.log_info('Cloning environment') env = elasticbeanstalk.get_environment( app_name=clone_request.app_name, env_name=clone_request.original_name) clone_request.version_label = env.version_label result, request_id = clone_env(clone_request) result.print_env_details(io.echo, elasticbeanstalk.get_environments, elasticbeanstalk.get_environment_resources, health=False) if nohang: return io.echo('Printing Status:') commonops.wait_for_success_events(request_id, timeout_in_minutes=timeout)
def __init__(self, app_name, env_name, all_app_versions): super(VersionDataPoller, self).__init__(app_name, env_name) self.next_token = None self.history = [] self.curr_page = 0 self.all_app_versions = all_app_versions self.app_versions = [] self.list_len_left = len(all_app_versions) self.env = None self.curr_deploy_num = None self.env_data = {} if self.env_name is not None: # If we have a default environment, save current env status into env_data self.env = elasticbeanstalk.get_environment(app_name=self.app_name, env_name=self.env_name) self.curr_deploy_num = self.get_curr_deploy_num() self.env_data = self.get_env_data()
def download_source_bundle(app_name, env_name): env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) if env.version_label and env.version_label != 'Sample Application': app_version = elasticbeanstalk.get_application_versions( app_name, version_labels=[env.version_label])['ApplicationVersions'][0] source_bundle = app_version['SourceBundle'] bucket_name = source_bundle['S3Bucket'] key_name = source_bundle['S3Key'] io.echo('Downloading application version...') data = s3.get_object(bucket_name, key_name) filename = get_filename(key_name) else: # sample app template = cloudformation.get_template('awseb-' + env.id + '-stack') try: url = template['TemplateBody']['Parameters']['AppSource'][ 'Default'] except KeyError: raise NotFoundError('Can not find app source for environment') utils.get_data_from_url(url) io.echo('Downloading application version...') data = utils.get_data_from_url(url, timeout=30) filename = 'sample.zip' fileoperations.make_eb_dir('downloads/') location = fileoperations.get_eb_file_full_location('downloads/' + filename) fileoperations.write_to_data_file(location, data) io.echo('Application version downloaded to:', location) cwd = os.getcwd() try: fileoperations._traverse_to_project_root() if heuristics.directory_is_empty(): # If we dont have any project code, unzip as current project io.echo('Unzipping application version as project files.') fileoperations.unzip_folder(location, os.getcwd()) io.echo('Done.') finally: os.chdir(cwd)
def get_quick_link(app_name, env_name): env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) settings = elasticbeanstalk.describe_configuration_settings( app_name, env_name) option_settings = settings['OptionSettings'] environment_type = elasticbeanstalk.get_option_setting( option_settings, 'aws:elasticbeanstalk:environment', 'EnvironmentType') instance_type = elasticbeanstalk.get_option_setting( option_settings, 'aws:autoscaling:launchconfiguration', 'InstanceType') link = 'https://console.aws.amazon.com/elasticbeanstalk/home?' # add region region = aws.get_region_name() link += 'region=' + urllib.parse.quote(region) # add quicklaunch flag link += '#/newApplication' # add application name link += '?applicationName=' + urllib.parse.quote(app_name) # add solution stack link += '&solutionStackName=' + urllib.parse.quote( env.platform.platform_shorthand) # add link += '&tierName=' + env.tier.name if environment_type: link += '&environmentType=' + environment_type if env.version_label: app_version = elasticbeanstalk.get_application_versions( app_name, version_labels=[env.version_label])['ApplicationVersions'][0] source_bundle = app_version['SourceBundle'] source_url = 'https://s3.amazonaws.com/' + source_bundle['S3Bucket'] + \ '/' + source_bundle['S3Key'] link += '&sourceBundleUrl=' + source_url if instance_type: link += '&instanceType=' + instance_type link = _add_database_options(link, option_settings) link = _add_vpc_options(link, option_settings) io.echo(link)
def assemble_environment_data(self, ids_of_all_instances, instances_registered_with_elb): total_instances = len(ids_of_all_instances) total_in_service = 0 for instance_state in instances_registered_with_elb: if instance_state[ 'State'] == statics.ec2_instance_statuses.IN_SERVICE: total_in_service += 1 env = elasticbeanstalk.get_environment(app_name=self.app_name, env_name=self.env_name) return { 'EnvironmentName': env.name, 'Color': env.health, 'Status': env.status, 'Total': total_instances, 'InService': total_in_service, 'Other': total_instances - total_in_service, 'RefreshedAt': _datetime_utcnow_wrapper() }
def assemble_environment_data( self, ids_of_all_instances, instances_registered_with_elb ): total_instances = len(ids_of_all_instances) total_in_service = 0 for instance_state in instances_registered_with_elb: if instance_state['State'] == statics.ec2_instance_statuses.IN_SERVICE: total_in_service += 1 env = elasticbeanstalk.get_environment(app_name=self.app_name, env_name=self.env_name) return { 'EnvironmentName': env.name, 'Color': env.health, 'Status': env.status, 'Total': total_instances, 'InService': total_in_service, 'Other': total_instances - total_in_service, 'RefreshedAt': _datetime_utcnow_wrapper() }
def retrieve_application_version_url(env_name): """ Method retrieves the URL of the application version of the environment, 'env_name', for the CLI to download from. The method waits for the CloudFormation stack associated with `env_name` to come into existence, after which, it retrieves the 'url' of the application version. :param env_name: Name of the environment that launched with the sample application :return: The URL of the application version. """ env = elasticbeanstalk.get_environment(env_name=env_name) cloudformation_stack_name = 'awseb-' + env.id + '-stack' cloudformation.wait_until_stack_exists(cloudformation_stack_name) template = cloudformation.get_template(cloudformation_stack_name) url = None try: url = template['TemplateBody']['Parameters']['AppSource']['Default'] except KeyError: io.log_warning('{}. '.format(strings['cloudformation.cannot_find_app_source_for_environment'])) return url
def get_environment_platform(app_name, env_name, want_solution_stack=False): env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name, want_solution_stack=want_solution_stack) return env.platform
def do_command(self): app_name = self.get_app_name() env_name = self.get_env_name() clone_name = self.app.pargs.clone_name cname = self.app.pargs.cname scale = self.app.pargs.scale nohang = self.app.pargs.nohang tags = self.app.pargs.tags envvars = self.app.pargs.envvars exact = self.app.pargs.exact timeout = self.app.pargs.timeout provided_clone_name = clone_name is not None platform = None env = elasticbeanstalk.get_environment(app_name=app_name, env_name=env_name) tier = env.tier if 'worker' in tier.name.lower() and cname: raise InvalidOptionsError(strings['worker.cname']) if cname: if not elasticbeanstalk.is_cname_available(cname): raise AlreadyExistsError(strings['cname.unavailable'].replace( '{cname}', cname)) tags = tagops.get_and_validate_tags(tags) envvars = get_and_validate_envars(envvars) if not clone_name: if len(env_name) < 16: unique_name = env_name + '-clone' else: unique_name = 'my-cloned-env' env_list = elasticbeanstalk.get_environment_names(app_name) unique_name = utils.get_unique_name(unique_name, env_list) clone_name = io.prompt_for_environment_name( default_name=unique_name, prompt_text='Enter name for Environment Clone') if tier.name.lower() == 'webserver': if not cname and not provided_clone_name: cname = get_cname_from_customer(clone_name) elif not cname: cname = None if not exact: if not provided_clone_name: latest = solution_stack_ops.find_solution_stack_from_string( env.platform.name, find_newer=True) if latest != env.platform: io.echo() io.echo(prompts['clone.latest']) lst = [ 'Latest (' + str(latest) + ')', 'Same (' + str(env.platform) + ')' ] result = utils.prompt_for_item_in_list(lst) if result == lst[0]: platform = latest else: platform = latest else: platform = solution_stack_ops.find_solution_stack_from_string( env.platform.name, find_newer=True) if platform != env.platform: io.log_warning(prompts['clone.latestwarn']) clone_request = CloneEnvironmentRequest( app_name=app_name, env_name=clone_name, original_name=env_name, cname=cname, platform=platform, scale=scale, tags=tags, ) clone_request.option_settings += envvars cloneops.make_cloned_env(clone_request, nohang=nohang, timeout=timeout)
def __verify_environment_exists(env_name): elasticbeanstalk.get_environment(env_name=env_name)
def _check_env_lifecycle_state(env_name): env = elasticbeanstalk.get_environment(env_name=env_name) statusops.alert_environment_status(env)