idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
238,900
def retrieve_template ( self ) : links = self . retrieve_instance_links ( ) self . log . debug ( 'Links is \n%s' , pformat ( links ) ) self . pipeline_config [ 'instance_links' ] . update ( links ) jsondata = get_template ( template_file = 'infrastructure/app_data.json.j2' , appinfo = self . appinfo , pipeline_config =...
Sets the instance links with pipeline_configs and then renders template files
238,901
def retrieve_instance_links ( self ) : instance_links = { } self . log . debug ( "LINKS IS %s" , LINKS ) for key , value in LINKS . items ( ) : if value not in self . pipeline_config [ 'instance_links' ] . values ( ) : instance_links [ key ] = value return instance_links
Appends on existing instance links
238,902
def get_cloudwatch_event_rule ( app_name , account , region ) : session = boto3 . Session ( profile_name = account , region_name = region ) cloudwatch_client = session . client ( 'events' ) lambda_alias_arn = get_lambda_alias_arn ( app = app_name , account = account , region = region ) rule_names = cloudwatch_client . ...
Get CloudWatch Event rule names .
238,903
def setup_pathing ( self ) : self . s3_version_uri = self . _path_formatter ( self . version ) self . s3_latest_uri = self . _path_formatter ( "LATEST" ) self . s3_canary_uri = self . _path_formatter ( "CANARY" ) self . s3_alpha_uri = self . _path_formatter ( "ALPHA" ) self . s3_mirror_uri = self . _path_formatter ( "M...
Format pathing for S3 deployments .
238,904
def _path_formatter ( self , suffix ) : if suffix . lower ( ) == "mirror" : path_items = [ self . bucket , self . s3path ] else : path_items = [ self . bucket , self . s3path , suffix ] path = '/' . join ( path_items ) s3_format = "s3://{}" formatted_path = path . replace ( '//' , '/' ) full_path = s3_format . format (...
Format the s3 path properly .
238,905
def upload_artifacts ( self ) : deploy_strategy = self . properties [ "deploy_strategy" ] mirror = False if deploy_strategy == "mirror" : mirror = True self . _upload_artifacts_to_path ( mirror = mirror ) if deploy_strategy == "highlander" : self . _sync_to_uri ( self . s3_latest_uri ) elif deploy_strategy == "canary" ...
Upload artifacts to S3 and copy to correct path depending on strategy .
238,906
def promote_artifacts ( self , promote_stage = 'latest' ) : if promote_stage . lower ( ) == 'alpha' : self . _sync_to_uri ( self . s3_canary_uri ) elif promote_stage . lower ( ) == 'canary' : self . _sync_to_uri ( self . s3_latest_uri ) else : self . _sync_to_uri ( self . s3_latest_uri )
Promote artifact version to dest .
238,907
def _get_upload_cmd ( self , mirror = False ) : if mirror : dest_uri = self . s3_mirror_uri else : dest_uri = self . s3_version_uri cmd = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}' . format ( self . artifact_path , dest_uri , self . env ) return cmd
Generate the S3 CLI upload command
238,908
def _upload_artifacts_to_path ( self , mirror = False ) : if not os . listdir ( self . artifact_path ) or not self . artifact_path : raise S3ArtifactNotFound uploaded = False if self . s3props . get ( "content_metadata" ) : LOG . info ( "Uploading in multiple parts to set metadata" ) uploaded = self . content_metadata_...
Recursively upload directory contents to S3 .
238,909
def content_metadata_uploads ( self , mirror = False ) : excludes_str = '' includes_cmds = [ ] cmd_base = self . _get_upload_cmd ( mirror = mirror ) for content in self . s3props . get ( 'content_metadata' ) : full_path = os . path . join ( self . artifact_path , content [ 'path' ] ) if not os . listdir ( full_path ) :...
Finds all specified encoded directories and uploads in multiple parts setting metadata for objects .
238,910
def _sync_to_uri ( self , uri ) : cmd_cp = 'aws s3 cp {} {} --recursive --profile {}' . format ( self . s3_version_uri , uri , self . env ) cmd_sync = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}' . format ( self . s3_version_uri , uri , self . env ) cp_result = subprocess . run ( cmd_cp , check = True ,...
Copy and sync versioned directory to uri in S3 .
238,911
def get_vpc_id ( account , region ) : url = '{0}/networks/aws' . format ( API_URL ) response = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) if not response . ok : raise SpinnakerVPCNotFound ( response . text ) vpcs = response . json ( ) for vpc in vpcs : LOG . debug ( 'VPC: %(name)s, %(acc...
Get VPC ID configured for account in region .
238,912
def get_subnets ( target = 'ec2' , purpose = 'internal' , env = '' , region = '' , ) : account_az_dict = defaultdict ( defaultdict ) subnet_id_dict = defaultdict ( defaultdict ) subnet_url = '{0}/subnets/aws' . format ( API_URL ) subnet_response = requests . get ( subnet_url , verify = GATE_CA_BUNDLE , cert = GATE_CLIE...
Get all availability zones for a given target .
238,913
def create_lambda_events ( self ) : remove_all_lambda_permissions ( app_name = self . app_name , env = self . env , region = self . region ) triggers = self . properties [ 'lambda_triggers' ] for trigger in triggers : if trigger [ 'type' ] == 'sns' : create_sns_event ( app_name = self . app_name , env = self . env , re...
Create all defined lambda events for an lambda application .
238,914
def get_all_pipelines ( app = '' ) : url = '{host}/applications/{app}/pipelineConfigs' . format ( host = API_URL , app = app ) response = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) assert response . ok , 'Could not retrieve Pipelines for {0}.' . format ( app ) pipelines = response . json...
Get a list of all the Pipelines in _app_ .
238,915
def get_pipeline_id ( app = '' , name = '' ) : return_id = None pipelines = get_all_pipelines ( app = app ) for pipeline in pipelines : LOG . debug ( 'ID of %(name)s: %(id)s' , pipeline ) if pipeline [ 'name' ] == name : return_id = pipeline [ 'id' ] LOG . info ( 'Pipeline %s found, ID: %s' , name , return_id ) break r...
Get the ID for Pipeline _name_ .
238,916
def normalize_pipeline_name ( name = '' ) : normalized_name = name for bad in '\\/?%#' : normalized_name = normalized_name . replace ( bad , '_' ) return normalized_name
Translate unsafe characters to underscores .
238,917
def get_all_apps ( ) : LOG . info ( 'Retreiving list of all Spinnaker applications' ) url = '{}/applications' . format ( API_URL ) response = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) assert response . ok , 'Could not retrieve application list' pipelines = response . json ( ) LOG . debu...
Get a list of all applications in Spinnaker .
238,918
def get_details ( app = 'groupproject' , env = 'dev' , region = 'us-east-1' ) : url = '{host}/applications/{app}' . format ( host = API_URL , app = app ) request = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) if not request . ok : raise SpinnakerAppNotFound ( '"{0}" not found.' . format ( ...
Extract details for Application .
238,919
def create_pipeline ( self ) : clean_pipelines ( app = self . app_name , settings = self . settings ) pipeline_envs = self . environments self . log . debug ( 'Envs from pipeline.json: %s' , pipeline_envs ) regions_envs = collections . defaultdict ( list ) for env in pipeline_envs : for region in self . settings [ env ...
Main wrapper for pipeline creation . 1 . Runs clean_pipelines to clean up existing ones 2 . determines which environments the pipeline needs 3 . Renders all of the pipeline blocks as defined in configs 4 . Runs post_pipeline to create pipeline
238,920
def _check_lambda ( self ) : exists = False try : self . lambda_client . get_function ( FunctionName = self . app_name ) exists = True except boto3 . exceptions . botocore . exceptions . ClientError : pass return exists
Check if lambda function exists .
238,921
def _check_lambda_alias ( self ) : aliases = self . lambda_client . list_aliases ( FunctionName = self . app_name ) matched_alias = False for alias in aliases [ 'Aliases' ] : if alias [ 'Name' ] == self . env : LOG . info ( 'Found alias %s for function %s' , self . env , self . app_name ) matched_alias = True break els...
Check if lambda alias exists .
238,922
def _vpc_config ( self ) : if self . vpc_enabled : subnets = get_subnets ( env = self . env , region = self . region , purpose = 'internal' ) [ 'subnet_ids' ] [ self . region ] security_groups = self . _get_sg_ids ( ) vpc_config = { 'SubnetIds' : subnets , 'SecurityGroupIds' : security_groups } else : vpc_config = { 'S...
Get VPC config .
238,923
def _get_sg_ids ( self ) : try : lambda_extras = self . settings [ 'security_groups' ] [ 'lambda_extras' ] except KeyError : lambda_extras = [ ] security_groups = [ self . app_name ] + lambda_extras sg_ids = [ ] for security_group in security_groups : sg_id = get_security_group_id ( name = security_group , env = self ....
Get IDs for all defined security groups .
238,924
def update_function_configuration ( self , vpc_config ) : LOG . info ( 'Updating configuration for lambda function: %s' , self . app_name ) try : self . lambda_client . update_function_configuration ( Environment = self . lambda_environment , FunctionName = self . app_name , Runtime = self . runtime , Role = self . rol...
Update existing Lambda function configuration .
238,925
def create_function ( self , vpc_config ) : zip_file = 'lambda-holder.zip' with zipfile . ZipFile ( zip_file , mode = 'w' ) as zipped : zipped . writestr ( 'index.py' , 'print "Hello world"' ) contents = '' with open ( 'lambda-holder.zip' , 'rb' ) as openfile : contents = openfile . read ( ) LOG . info ( 'Creating lamb...
Create lambda function configures lambda parameters .
238,926
def create_lambda_function ( self ) : vpc_config = self . _vpc_config ( ) if self . _check_lambda ( ) : self . update_function_configuration ( vpc_config ) else : self . create_function ( vpc_config ) if self . _check_lambda_alias ( ) : self . update_alias ( ) else : self . create_alias ( )
Create or update Lambda function .
238,927
def destroy_sg ( app = '' , env = '' , region = '' , ** _ ) : vpc = get_vpc_id ( account = env , region = region ) url = '{api}/securityGroups/{env}/{region}/{app}' . format ( api = API_URL , env = env , region = region , app = app ) payload = { 'vpcId' : vpc } security_group = requests . get ( url , params = payload ,...
Destroy Security Group .
238,928
def destroy_s3 ( app = '' , env = 'dev' , ** _ ) : session = boto3 . Session ( profile_name = env ) client = session . resource ( 's3' ) generated = get_details ( app = app , env = env ) archaius = generated . archaius ( ) bucket = client . Bucket ( archaius [ 'bucket' ] ) for item in bucket . objects . filter ( Prefix...
Destroy S3 Resources for _app_ in _env_ .
238,929
def main ( ) : parser = argparse . ArgumentParser ( ) add_debug ( parser ) add_app ( parser ) parser . add_argument ( '--email' , help = 'Email address to associate with application' , default = 'PS-DevOpsTooling@example.com' ) parser . add_argument ( '--project' , help = 'Git project to associate with application' , d...
Entry point for creating a Spinnaker application .
238,930
def destroy_s3_event ( app , env , region ) : generated = get_details ( app = app , env = env ) bucket = generated . s3_app_bucket ( ) session = boto3 . Session ( profile_name = env , region_name = region ) s3_client = session . client ( 's3' ) config = { } s3_client . put_bucket_notification_configuration ( Bucket = b...
Destroy S3 event .
238,931
def destroy_iam ( app = '' , env = 'dev' , ** _ ) : session = boto3 . Session ( profile_name = env ) client = session . client ( 'iam' ) generated = get_details ( env = env , app = app ) generated_iam = generated . iam ( ) app_details = collections . namedtuple ( 'AppDetails' , generated_iam . keys ( ) ) details = app_...
Destroy IAM Resources .
238,932
def get_role_arn ( role_name , env , region ) : session = boto3 . Session ( profile_name = env , region_name = region ) iam_client = session . client ( 'iam' ) LOG . debug ( 'Searching for %s.' , role_name ) role = iam_client . get_role ( RoleName = role_name ) role_arn = role [ 'Role' ] [ 'Arn' ] LOG . debug ( "Found ...
Get role ARN given role name .
238,933
def render_policy_template ( account_number = '' , app = 'coreforrest' , env = 'dev' , group = 'forrest' , items = None , pipeline_settings = None , region = 'us-east-1' , service = '' ) : statements = [ ] rendered_service_policy = get_template ( 'infrastructure/iam/{0}.json.j2' . format ( service ) , account_number = ...
Render IAM Policy template .
238,934
def construct_policy ( app = 'coreforrest' , env = 'dev' , group = 'forrest' , region = 'us-east-1' , pipeline_settings = None ) : LOG . info ( 'Create custom IAM Policy for %s.' , app ) services = pipeline_settings . get ( 'services' , { } ) LOG . debug ( 'Found requested services: %s' , services ) services = auto_ser...
Assemble IAM Policy for _app_ .
238,935
def validate_gate ( ) : try : credentials = get_env_credential ( ) LOG . debug ( 'Found credentials: %s' , credentials ) LOG . info ( 'Gate working.' ) except TypeError : LOG . fatal ( 'Gate connection not valid: API_URL = %s' , API_URL )
Check Gate connection .
238,936
def create_s3_event ( app_name , env , region , bucket , triggers ) : session = boto3 . Session ( profile_name = env , region_name = region ) s3_client = session . client ( 's3' ) lambda_alias_arn = get_lambda_alias_arn ( app_name , env , region ) LOG . debug ( "Lambda ARN for lambda function %s is %s." , app_name , la...
Create S3 lambda events from triggers
238,937
def generate_packer_filename ( provider , region , builder ) : filename = '{0}_{1}_{2}.json' . format ( provider , region , builder ) return filename
Generate a filename to be used by packer .
238,938
def get_template ( template_file = '' , ** kwargs ) : template = get_template_object ( template_file ) LOG . info ( 'Rendering template %s' , template . filename ) for key , value in kwargs . items ( ) : LOG . debug ( '%s => %s' , key , value ) rendered_json = template . render ( ** kwargs ) LOG . debug ( 'Rendered JSO...
Get the Jinja2 template and renders with dict _kwargs_ .
238,939
def renumerate_stages ( pipeline ) : stages = pipeline [ 'stages' ] main_index = 0 branch_index = 0 previous_refid = '' for stage in stages : current_refid = stage [ 'refId' ] . lower ( ) if current_refid == 'master' : if main_index == 0 : stage [ 'requisiteStageRefIds' ] = [ ] else : stage [ 'requisiteStageRefIds' ] =...
Renumber Pipeline Stage reference IDs to account for dependencies .
238,940
def post_task ( task_data , task_uri = '/tasks' ) : url = '{}/{}' . format ( API_URL , task_uri . lstrip ( '/' ) ) if isinstance ( task_data , str ) : task_json = task_data else : task_json = json . dumps ( task_data ) resp = requests . post ( url , data = task_json , headers = HEADERS , verify = GATE_CA_BUNDLE , cert ...
Create Spinnaker Task .
238,941
def _check_task ( taskid ) : try : taskurl = taskid . get ( 'ref' , '0000' ) except AttributeError : taskurl = taskid taskid = taskurl . split ( '/tasks/' ) [ - 1 ] LOG . info ( 'Checking taskid %s' , taskid ) url = '{}/tasks/{}' . format ( API_URL , taskid ) task_response = requests . get ( url , headers = HEADERS , v...
Check Spinnaker Task status .
238,942
def check_task ( taskid , timeout = DEFAULT_TASK_TIMEOUT , wait = 2 ) : max_attempts = int ( timeout / wait ) try : return retry_call ( partial ( _check_task , taskid ) , max_attempts = max_attempts , wait = wait , exceptions = ( AssertionError , ValueError ) , ) except ValueError : raise SpinnakerTaskInconclusiveError...
Wrap check_task .
238,943
def wait_for_task ( task_data , task_uri = '/tasks' ) : taskid = post_task ( task_data , task_uri ) if isinstance ( task_data , str ) : json_data = json . loads ( task_data ) else : json_data = task_data job = json_data [ 'job' ] [ 0 ] env = job . get ( 'credentials' ) task_type = job . get ( 'type' ) timeout = TASK_TI...
Run task and check the result .
238,944
def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) parser = argparse . ArgumentParser ( description = main . __doc__ ) add_debug ( parser ) add_app ( parser ) add_env ( parser ) add_properties ( parser ) add_region ( parser ) add_artifact_path ( parser ) add_artifact_version ( parser ) args = parser . par...
Create application . properties for a given application .
238,945
def init_properties ( env = 'dev' , app = 'unnecessary' , ** _ ) : aws_env = boto3 . session . Session ( profile_name = env ) s3client = aws_env . resource ( 's3' ) generated = get_details ( app = app , env = env ) archaius = generated . archaius ( ) archaius_file = ( '{path}/application.properties' ) . format ( path =...
Make sure _application . properties_ file exists in S3 .
238,946
def create_cloudwatch_event ( app_name , env , region , rules ) : session = boto3 . Session ( profile_name = env , region_name = region ) cloudwatch_client = session . client ( 'events' ) rule_name = rules . get ( 'rule_name' ) schedule = rules . get ( 'schedule' ) rule_description = rules . get ( 'rule_description' ) ...
Create cloudwatch event for lambda from rules .
238,947
def find_api_id ( self ) : allapis = self . client . get_rest_apis ( ) api_name = self . trigger_settings [ 'api_name' ] api_id = None for api in allapis [ 'items' ] : if api [ 'name' ] == api_name : api_id = api [ 'id' ] self . log . info ( "Found API for: %s" , api_name ) break else : api_id = self . create_api ( ) r...
Given API name find API ID .
238,948
def find_resource_ids ( self ) : all_resources = self . client . get_resources ( restApiId = self . api_id ) parent_id = None resource_id = None for resource in all_resources [ 'items' ] : if resource [ 'path' ] == "/" : parent_id = resource [ 'id' ] if resource [ 'path' ] == self . trigger_settings [ 'resource' ] : re...
Given a resource path and API Id find resource Id .
238,949
def add_lambda_integration ( self ) : lambda_uri = self . generate_uris ( ) [ 'lambda_uri' ] self . client . put_integration ( restApiId = self . api_id , resourceId = self . resource_id , httpMethod = self . trigger_settings [ 'method' ] , integrationHttpMethod = 'POST' , uri = lambda_uri , type = 'AWS' ) self . add_i...
Attach lambda found to API .
238,950
def add_integration_response ( self ) : self . client . put_integration_response ( restApiId = self . api_id , resourceId = self . resource_id , httpMethod = self . trigger_settings [ 'method' ] , statusCode = '200' , responseTemplates = { 'application/json' : '' } )
Add an intergation response to the API for the lambda integration .
238,951
def add_permission ( self ) : statement_id = '{}_api_{}' . format ( self . app_name , self . trigger_settings [ 'api_name' ] ) principal = 'apigateway.amazonaws.com' lambda_alias_arn = get_lambda_alias_arn ( self . app_name , self . env , self . region ) lambda_unqualified_arn = get_lambda_arn ( self . app_name , self ...
Add permission to Lambda for the API Trigger .
238,952
def create_api_deployment ( self ) : try : self . client . create_deployment ( restApiId = self . api_id , stageName = self . env ) self . log . info ( 'Created a deployment resource.' ) except botocore . exceptions . ClientError as error : error_code = error . response [ 'Error' ] [ 'Code' ] if error_code == 'TooManyR...
Create API deployment of ENV name .
238,953
def create_api_key ( self ) : apikeys = self . client . get_api_keys ( ) for key in apikeys [ 'items' ] : if key [ 'name' ] == self . app_name : self . log . info ( "Key %s already exists" , self . app_name ) break else : self . client . create_api_key ( name = self . app_name , enabled = True , stageKeys = [ { 'restAp...
Create API Key for API access .
238,954
def _format_base_path ( self , api_name ) : name = self . app_name if self . app_name != api_name : name = '{0}-{1}' . format ( self . app_name , api_name ) return name
Format the base path name .
238,955
def update_api_mappings ( self ) : response_provider = None response_action = None domain = self . generated . apigateway ( ) [ 'domain' ] try : response_provider = self . client . create_base_path_mapping ( domainName = domain , basePath = self . _format_base_path ( self . trigger_settings [ 'api_name' ] ) , restApiId...
Create a cname for the API deployment .
238,956
def generate_uris ( self ) : lambda_arn = "arn:aws:execute-api:{0}:{1}:{2}/*/{3}/{4}" . format ( self . region , self . account_id , self . api_id , self . trigger_settings [ 'method' ] , self . trigger_settings [ 'resource' ] ) lambda_uri = ( "arn:aws:apigateway:{0}:lambda:path/{1}/functions/" "arn:aws:lambda:{0}:{2}:...
Generate several lambda uris .
238,957
def create_api ( self ) : created_api = self . client . create_rest_api ( name = self . trigger_settings . get ( 'api_name' , self . app_name ) ) api_id = created_api [ 'id' ] self . log . info ( "Successfully created API" ) return api_id
Create the REST API .
238,958
def create_resource ( self , parent_id = "" ) : resource_name = self . trigger_settings . get ( 'resource' , '' ) resource_name = resource_name . replace ( '/' , '' ) if not self . resource_id : created_resource = self . client . create_resource ( restApiId = self . api_id , parentId = parent_id , pathPart = resource_n...
Create the specified resource .
238,959
def attach_method ( self , resource_id ) : try : _response = self . client . put_method ( restApiId = self . api_id , resourceId = resource_id , httpMethod = self . trigger_settings [ 'method' ] , authorizationType = "NONE" , apiKeyRequired = False , ) self . log . debug ( 'Response for resource (%s) push authorization...
Attach the defined method .
238,960
def setup_lambda_api ( self ) : self . create_resource ( self . parent_id ) self . attach_method ( self . resource_id ) self . add_lambda_integration ( ) self . add_permission ( ) self . create_api_deployment ( ) self . create_api_key ( ) self . update_api_mappings ( )
A wrapper for all the steps needed to setup the integration .
238,961
def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) log = logging . getLogger ( __name__ ) parser = argparse . ArgumentParser ( ) add_debug ( parser ) add_app ( parser ) add_env ( parser ) add_region ( parser ) add_properties ( parser ) parser . add_argument ( "--elb-subnet" , help = "Subnetnet type, e.g. ...
Run newer stuffs .
238,962
def _validate_cidr ( self , rule ) : try : network = ipaddress . IPv4Network ( rule [ 'app' ] ) except ( ipaddress . NetmaskValueError , ValueError ) as error : raise SpinnakerSecurityGroupCreationFailed ( error ) self . log . debug ( 'Validating CIDR: %s' , network . exploded ) return True
Validate the cidr block in a rule .
238,963
def _process_rules ( self , rules ) : cidr = [ ] non_cidr = [ ] for rule in rules : if '.' in rule [ 'app' ] : self . log . debug ( 'Custom CIDR rule: %s' , rule ) self . _validate_cidr ( rule ) cidr . append ( rule ) else : self . log . debug ( 'SG reference rule: %s' , rule ) non_cidr . append ( rule ) self . log . d...
Process rules into cidr and non - cidr lists .
238,964
def add_tags ( self ) : session = boto3 . session . Session ( profile_name = self . env , region_name = self . region ) resource = session . resource ( 'ec2' ) group_id = get_security_group_id ( self . app_name , self . env , self . region ) security_group = resource . SecurityGroup ( group_id ) try : tag = security_gr...
Add tags to security group .
238,965
def add_cidr_rules ( self , rules ) : session = boto3 . session . Session ( profile_name = self . env , region_name = self . region ) client = session . client ( 'ec2' ) group_id = get_security_group_id ( self . app_name , self . env , self . region ) for rule in rules : data = { 'DryRun' : False , 'GroupId' : group_id...
Add cidr rules to security group via boto .
238,966
def update_default_rules ( self ) : app_ingress = self . properties [ 'security_group' ] [ 'ingress' ] ingress = conservative_merger . merge ( DEFAULT_SECURITYGROUP_RULES , app_ingress ) resolved_ingress = self . resolve_self_references ( ingress ) self . log . info ( 'Updated default rules:\n%s' , ingress ) return res...
Concatinate application and global security group rules .
238,967
def _create_security_group ( self , ingress ) : template_kwargs = { 'app' : self . app_name , 'env' : self . env , 'region' : self . region , 'vpc' : get_vpc_id ( self . env , self . region ) , 'description' : self . properties [ 'security_group' ] [ 'description' ] , 'ingress' : ingress , } secgroup_json = get_templat...
Send a POST to spinnaker to create a new security group .
238,968
def create_security_group ( self ) : ingress_rules = [ ] try : security_id = get_security_group_id ( name = self . app_name , env = self . env , region = self . region ) except ( SpinnakerSecurityGroupError , AssertionError ) : self . _create_security_group ( ingress_rules ) else : self . log . debug ( 'Security Group ...
Send a POST to spinnaker to create or update a security group .
238,969
def create_ingress_rule ( self , app , rule ) : if isinstance ( rule , dict ) : start_port = rule . get ( 'start_port' ) end_port = rule . get ( 'end_port' ) protocol = rule . get ( 'protocol' , 'tcp' ) requested_cross_account = rule . get ( 'env' , self . env ) if self . env == requested_cross_account : cross_account_...
Create a normalized ingress rule .
238,970
def get_lambda_arn ( app , account , region ) : session = boto3 . Session ( profile_name = account , region_name = region ) lambda_client = session . client ( 'lambda' ) lambda_arn = None paginator = lambda_client . get_paginator ( 'list_functions' ) for lambda_functions in paginator . paginate ( ) : for lambda_functio...
Get lambda ARN .
238,971
def get_lambda_alias_arn ( app , account , region ) : session = boto3 . Session ( profile_name = account , region_name = region ) lambda_client = session . client ( 'lambda' ) lambda_aliases = lambda_client . list_aliases ( FunctionName = app ) matched_alias = None for alias in lambda_aliases [ 'Aliases' ] : if alias [...
Get lambda alias ARN . Assumes that account name is equal to alias name .
238,972
def add_lambda_permissions ( function = '' , statement_id = '' , action = 'lambda:InvokeFunction' , principal = '' , source_arn = '' , env = '' , region = 'us-east-1' ) : session = boto3 . Session ( profile_name = env , region_name = region ) lambda_client = session . client ( 'lambda' ) response_action = None prefixed...
Add permission to Lambda for the event trigger .
238,973
def resource_action ( client , action = '' , log_format = 'item: %(key)s' , ** kwargs ) : result = None try : result = getattr ( client , action ) ( ** kwargs ) LOG . info ( log_format , kwargs ) except botocore . exceptions . ClientError as error : error_code = error . response [ 'Error' ] [ 'Code' ] if error_code == ...
Call _action_ using boto3 _client_ with _kwargs_ .
238,974
def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) parser = argparse . ArgumentParser ( description = 'Example with non-optional arguments' ) add_debug ( parser ) add_app ( parser ) add_env ( parser ) add_region ( parser ) add_properties ( parser ) args = parser . parse_args ( ) logging . getLogger ( __pa...
Entry point for ELB creation
238,975
def make_elb_json ( self ) : env = self . env region = self . region elb_settings = self . properties [ 'elb' ] LOG . debug ( 'Block ELB Settings:\n%s' , pformat ( elb_settings ) ) health_settings = elb_settings [ 'health' ] elb_subnet_purpose = elb_settings . get ( 'subnet_purpose' , 'internal' ) region_subnets = get_...
Render the JSON template with arguments .
238,976
def create_elb ( self ) : json_data = self . make_elb_json ( ) LOG . debug ( 'Block ELB JSON Data:\n%s' , pformat ( json_data ) ) wait_for_task ( json_data ) self . add_listener_policy ( json_data ) self . add_backend_policy ( json_data ) self . configure_attributes ( json_data )
Create or Update the ELB after rendering JSON data from configs . Asserts that the ELB task was successful .
238,977
def add_listener_policy ( self , json_data ) : env = boto3 . session . Session ( profile_name = self . env , region_name = self . region ) elbclient = env . client ( 'elb' ) stickiness = { } elb_settings = self . properties [ 'elb' ] if elb_settings . get ( 'ports' ) : ports = elb_settings [ 'ports' ] for listener in p...
Attaches listerner policies to an ELB
238,978
def add_backend_policy ( self , json_data ) : env = boto3 . session . Session ( profile_name = self . env , region_name = self . region ) elbclient = env . client ( 'elb' ) for job in json . loads ( json_data ) [ 'job' ] : for listener in job [ 'listeners' ] : instance_port = listener [ 'internalPort' ] backend_policy_...
Attaches backend server policies to an ELB
238,979
def add_stickiness ( self ) : stickiness_dict = { } env = boto3 . session . Session ( profile_name = self . env , region_name = self . region ) elbclient = env . client ( 'elb' ) elb_settings = self . properties [ 'elb' ] for listener in elb_settings . get ( 'ports' ) : if listener . get ( "stickiness" ) : sticky_type ...
Adds stickiness policy to created ELB
238,980
def configure_attributes ( self , json_data ) : env = boto3 . session . Session ( profile_name = self . env , region_name = self . region ) elbclient = env . client ( 'elb' ) elb_settings = self . properties [ 'elb' ] LOG . debug ( 'Block ELB Settings Pre Configure Load Balancer Attributes:\n%s' , pformat ( elb_setting...
Configure load balancer attributes such as idle timeout connection draining etc
238,981
def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) parser = argparse . ArgumentParser ( description = main . __doc__ ) add_debug ( parser ) parser . add_argument ( '-o' , '--output' , required = True , help = 'Name of environment file to append to' ) parser . add_argument ( '-g' , '--git-short' , metavar ...
Append Application Configurations to a given file in multiple formats .
238,982
def add_infra ( subparsers ) : infra_parser = subparsers . add_parser ( 'infra' , help = runner . prepare_infrastructure . __doc__ ) infra_parser . set_defaults ( func = runner . prepare_infrastructure )
Infrastructure subcommands .
238,983
def add_pipeline ( subparsers ) : pipeline_parser = subparsers . add_parser ( 'pipeline' , help = add_pipeline . __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) pipeline_parser . set_defaults ( func = pipeline_parser . print_help ) pipeline_subparsers = pipeline_parser . add_subparsers ( title = ...
Pipeline subcommands .
238,984
def add_rebuild ( subparsers ) : rebuild_parser = subparsers . add_parser ( 'rebuild' , help = runner . rebuild_pipelines . __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) rebuild_parser . set_defaults ( func = runner . rebuild_pipelines ) rebuild_parser . add_argument ( '-a' , '--all' , action =...
Rebuild Pipeline subcommands .
238,985
def add_autoscaling ( subparsers ) : autoscaling_parser = subparsers . add_parser ( 'autoscaling' , help = runner . create_scaling_policy . __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) autoscaling_parser . set_defaults ( func = runner . create_scaling_policy )
Auto Scaling Group Policy subcommands .
238,986
def add_validate ( subparsers ) : validate_parser = subparsers . add_parser ( 'validate' , help = add_validate . __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) validate_parser . set_defaults ( func = validate_parser . print_help ) validate_subparsers = validate_parser . add_subparsers ( title = ...
Validate Spinnaker setup .
238,987
def get_existing_pipelines ( self ) : url = "{0}/applications/{1}/pipelineConfigs" . format ( API_URL , self . app_name ) resp = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) assert resp . ok , 'Failed to lookup pipelines for {0}: {1}' . format ( self . app_name , resp . text ) return resp ...
Get existing pipeline configs for specific application .
238,988
def compare_with_existing ( self , region = 'us-east-1' , onetime = False ) : pipelines = self . get_existing_pipelines ( ) pipeline_id = None found = False for pipeline in pipelines : correct_app_and_region = ( pipeline [ 'application' ] == self . app_name ) and ( region in pipeline [ 'name' ] ) if onetime : onetime_s...
Compare desired pipeline with existing pipelines .
238,989
def create_pipeline ( self ) : clean_pipelines ( app = self . app_name , settings = self . settings ) pipeline_envs = self . environments self . log . debug ( 'Envs from pipeline.json: %s' , pipeline_envs ) regions_envs = collections . defaultdict ( list ) for env in pipeline_envs : for region in self . settings [ env ...
Main wrapper for pipeline creation . 1 . Runs clean_pipelines to clean up existing ones 2 . determines which environments the pipeline needs 3 . gets all subnets for template rendering 4 . Renders all of the pipeline blocks as defined in configs 5 . Runs post_pipeline to create pipeline
238,990
def ami_lookup ( region = 'us-east-1' , name = 'tomcat8' ) : if AMI_JSON_URL : ami_dict = _get_ami_dict ( AMI_JSON_URL ) ami_id = ami_dict [ region ] [ name ] elif GITLAB_TOKEN : warn_user ( 'Use AMI_JSON_URL feature instead.' ) ami_contents = _get_ami_file ( region = region ) ami_dict = json . loads ( ami_contents ) a...
Look up AMI ID .
238,991
def _get_ami_file ( region = 'us-east-1' ) : LOG . info ( "Getting AMI from Gitlab" ) lookup = FileLookup ( git_short = 'devops/ansible' ) filename = 'scripts/{0}.json' . format ( region ) ami_contents = lookup . remote_file ( filename = filename , branch = 'master' ) LOG . debug ( 'AMI file contents in %s: %s' , filen...
Get file from Gitlab .
238,992
def _get_ami_dict ( json_url ) : LOG . info ( "Getting AMI from %s" , json_url ) response = requests . get ( json_url ) assert response . ok , "Error getting ami info from {}" . format ( json_url ) ami_dict = response . json ( ) LOG . debug ( 'AMI json contents: %s' , ami_dict ) return ami_dict
Get ami from a web url .
238,993
def get_gitlab_project ( self ) : self . server = gitlab . Gitlab ( GIT_URL , private_token = GITLAB_TOKEN , api_version = 4 ) project = self . server . projects . get ( self . git_short ) if not project : raise GitLabApiError ( 'Could not get Project "{0}" from GitLab API.' . format ( self . git_short ) ) self . proje...
Get numerical GitLab Project ID .
238,994
def local_file ( self , filename ) : LOG . info ( 'Retrieving "%s" from "%s".' , filename , self . runway_dir ) file_contents = '' file_path = os . path . join ( self . runway_dir , filename ) try : with open ( file_path , 'rt' ) as lookup_file : file_contents = lookup_file . read ( ) except FileNotFoundError : LOG . w...
Read the local file in _self . runway_dir_ .
238,995
def remote_file ( self , branch = 'master' , filename = '' ) : LOG . info ( 'Retrieving "%s" from "%s".' , filename , self . git_short ) file_contents = '' try : file_blob = self . project . files . get ( file_path = filename , ref = branch ) except gitlab . exceptions . GitlabGetError : file_blob = None LOG . debug ( ...
Read the remote file on Git Server .
238,996
def banner ( text , border = '=' , width = 80 ) : text_padding = '{0:^%d}' % ( width ) LOG . info ( border * width ) LOG . info ( text_padding . format ( text ) ) LOG . info ( border * width )
Center _text_ in a banner _width_ wide with _border_ characters .
238,997
def get_sns_topic_arn ( topic_name , account , region ) : if topic_name . count ( ':' ) == 5 and topic_name . startswith ( 'arn:aws:sns:' ) : return topic_name session = boto3 . Session ( profile_name = account , region_name = region ) sns_client = session . client ( 'sns' ) topics = sns_client . list_topics ( ) [ 'Top...
Get SNS topic ARN .
238,998
def notify_slack_channel ( self ) : message = get_template ( template_file = 'slack/pipeline-prepare-ran.j2' , info = self . info ) if self . settings [ 'pipeline' ] [ 'notifications' ] [ 'slack' ] : post_slack_message ( message = message , channel = self . settings [ 'pipeline' ] [ 'notifications' ] [ 'slack' ] , user...
Post message to a defined Slack channel .
238,999
def get_properties ( properties_file = 'raw.properties.json' , env = None , region = None ) : with open ( properties_file , 'rt' ) as file_handle : properties = json . load ( file_handle ) env_properties = properties . get ( env , properties ) contents = env_properties . get ( region , env_properties ) LOG . debug ( 'F...
Get contents of _properties_file_ for the _env_ .