How to use the taskcat.utils.CFNYAMLHandler.ordered_safe_load function in taskcat

To help you get started, we’ve selected a few taskcat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github awslabs / aws-servicebroker / build-tools / apb_packaging / sb_cfn_package / sb_cfn_package.py View on Github external
def __init__(self, template_path=None, service_spec_path=None):
        """
        Initialise the class, optionally providing paths for the template and a seperate service spec, if
        service_spec_path is not specified then we'll look for it in the template Metadata.

        :param template_path:
        :param service_spec_path:
        """
        self.template = {}
        self.service_spec = {}
        if template_path:
            self.template_path = os.path.dirname(template_path)
            with open(template_path, 'r') as stream:
                self.template = CFNYAMLHandler.ordered_safe_load(stream)
            if not service_spec_path:
                self.service_spec = self.template['Metadata']['AWS::ServiceBroker::Specification']
        if service_spec_path:
            with open(service_spec_path, 'r') as stream:
                self.service_spec = yaml.load(stream)
        if not self.service_spec:
            raise Exception("cannot continue without either a ['Metadata']['AWS::ServiceBroker::Specification'] section in the template, or a path to a seperate spec using service_spec_path")
github awslabs / aws-servicebroker / build-tools / apb_packaging / sb_cfn_package / aws_servicebroker_spec.py View on Github external
with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/%s/lambda_function.py" % util[1], 'r') as stream:
                            function_code = stream.read()
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code']['ZipFile'] = function_code
                    else:
                        self._inject_copy_zips()
                        bucket, key = self._publish_lambda_zip(os.path.dirname(os.path.abspath(__file__)) + "/functions/%s/" % util[1], util[1])
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code']['S3Bucket'] = '!Ref AWSSBInjectedLambdaZipsBucket'
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code']['S3Key'] = key
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Handler'] = 'lambda_function.handler'
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code'].pop('ZipFile')
                        self.template['Resources']['AWSSBInjectedCopyZips']['Properties']['Objects'].append(util[1] + '/lambda_function.zip')
                    temp_template = CFNYAMLHandler.ordered_safe_dump(self.template, default_flow_style=False).replace(
                        "!Ref %s" % util[3],
                        "!If [ %s, !GetAtt AWSSBInjected%s.%s, !Ref %s ]" % (util[4], util[2], util[3], util[3])
                    )
                    self.template = CFNYAMLHandler.ordered_safe_load(temp_template)
                    self.template['Resources'] = OrderedDict({**self.template['Resources'], **snippet['Resources']})
                    self.template['Conditions'] = OrderedDict({**self.template['Conditions'], **snippet['Conditions']})
github awslabs / aws-servicebroker / build-tools / apb_packaging / sb_cfn_package / aws_servicebroker_spec.py View on Github external
def _inject_copy_zips(self):
        self._make_asset_bucket()
        if 'AWSSBInjectedCopyZips' not in self.template['Resources'].keys():
            with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/copy_zips/template.snippet", 'r') as stream:
                snippet = CFNYAMLHandler.ordered_safe_load(stream)
            with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/copy_zips/lambda_function.py", 'r') as stream:
                    function_code = stream.read()
            snippet['Resources']['AWSSBInjectedCopyZipsLambda']['Properties']['Code']['ZipFile'] = function_code
            p = snippet['Resources']['AWSSBInjectedCopyZipsRole']['Properties']['Policies']
            p[0]['PolicyDocument']['Statement'][0]['Resource'][0] = p[0]['PolicyDocument']['Statement'][0]['Resource'][0].replace(
                '${SourceBucketName}', self.bucket_name
            ).replace('${KeyPrefix}', self.key_prefix)
            p[0]['PolicyDocument']['Statement'][1]['Resource'][0] = p[0]['PolicyDocument']['Statement'][1]['Resource'][
                0].replace(
                '${KeyPrefix}', self.key_prefix
            )
            snippet['Resources']['AWSSBInjectedCopyZips']['Properties']['SourceBucket'] = self.bucket_name
            snippet['Resources']['AWSSBInjectedCopyZips']['Properties']['Prefix'] = self.key_prefix + 'functions/'
            self.template['Resources'] = OrderedDict({**self.template['Resources'], **snippet['Resources']})
github awslabs / aws-servicebroker / build-tools / apb_packaging / sb_cfn_package / aws_servicebroker_spec.py View on Github external
def _inject_iam(self, policies=None):
        with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/create_keypair/template.snippet", 'r') as stream:
            snippet = CFNYAMLHandler.ordered_safe_load(stream)
        with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/create_keypair/lambda_function.py", 'r') as stream:
            function_code = stream.read()
        snippet['Resources']['AWSSBInjectedIAMUserLambda']['Properties']['Code']['ZipFile'] = function_code
        policy_template = snippet['Resources'].pop('AWSSBInjectedIAMUserPolicy')
        policy_arns = []
        if policies:
            pnum = 0
            for policy in policies:
                if type(policy) in [dict, OrderedDict]:
                    pnum += 1
                    pname = 'AWSSBInjectedIAMUserPolicy%s' % str(pnum)
                    p = copy.deepcopy(policy_template)
                    p['Properties']['PolicyName'] = pname
                    p['Properties']['PolicyDocument'] = policy['PolicyDocument']
                    snippet['Resources'][pname] = p
                elif policy.startswith('arn:aws:iam'):
github awslabs / aws-servicebroker / build-tools / apb_packaging / sb_cfn_package / aws_servicebroker_spec.py View on Github external
def _inject_utils(self):
        self._make_asset_bucket()
        for util in [
            ['CidrBlocks', 'get_cidrs', 'GetCidrs', 'CidrBlocks', 'AutoCidrs'],
            ['NumberOfAvailabilityZones', 'get_azs', 'GetAzs', 'AvailabilityZones', 'AutoAzs'],
            ['MasterUserPassword', 'generate_password', 'GeneratePassword', 'MasterUserPassword', 'AutoPassword'],
            ['DBName', 'generate_dbname', 'GenerateDBName', 'DBName', 'AutoDBName'],
            ['EMRClusterName', 'generate_emrname', 'GenerateEMRClusterName', 'EMRClusterName', 'AutoEMRClusterName'],
            ['EMRCidr', 'get_emrcidrs', 'GetEMRCidr', 'EMRCidr', 'AutoEMRCidr']
        ]:
            if util[0] in self.template['Parameters']:
                if self.template['Parameters'][util[3]]['Default'] == 'Auto':
                    with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/%s/template.snippet" % util[1], 'r') as stream:
                        snippet = CFNYAMLHandler.ordered_safe_load(stream)
                    if not os.path.isfile(os.path.dirname(os.path.abspath(__file__)) + "/functions/%s/requirements.txt" % util[1]):
                        with open(os.path.dirname(os.path.abspath(__file__)) + "/functions/%s/lambda_function.py" % util[1], 'r') as stream:
                            function_code = stream.read()
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code']['ZipFile'] = function_code
                    else:
                        self._inject_copy_zips()
                        bucket, key = self._publish_lambda_zip(os.path.dirname(os.path.abspath(__file__)) + "/functions/%s/" % util[1], util[1])
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code']['S3Bucket'] = '!Ref AWSSBInjectedLambdaZipsBucket'
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code']['S3Key'] = key
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Handler'] = 'lambda_function.handler'
                        snippet['Resources']['AWSSBInjected%sLambda' % util[2]]['Properties']['Code'].pop('ZipFile')
                        self.template['Resources']['AWSSBInjectedCopyZips']['Properties']['Objects'].append(util[1] + '/lambda_function.zip')
                    temp_template = CFNYAMLHandler.ordered_safe_dump(self.template, default_flow_style=False).replace(
                        "!Ref %s" % util[3],
                        "!If [ %s, !GetAtt AWSSBInjected%s.%s, !Ref %s ]" % (util[4], util[2], util[3], util[3])
                    )
github aws-quickstart / taskcat / beautycorn.py View on Github external
logger.info("Opening file [{}]".format(current_file))

        with open(current_file, 'r', newline=None) as template:
            template_raw_data = template.read()
            template.close()

        template_raw_data = template_raw_data.strip()

        if template_raw_data[0] in ['{', '['] and template_raw_data[-1] in ['}', ']']:
            logger.info('Detected JSON. Loading file.')
            FILE_FORMAT = 'JSON'
            template_data = json.load(open(current_file, 'r', newline=None), object_pairs_hook=OrderedDict)
        else:
            logger.info('Detected YAML. Loading file.')
            FILE_FORMAT = 'YAML'
            template_data = utils.CFNYAMLHandler.ordered_safe_load(open(current_file, 'r', newline=None), object_pairs_hook=OrderedDict)

        with open(current_file, 'w') as updated_template:
            logger.info("Writing file [{}]".format(current_file))
            if FILE_FORMAT == 'JSON':
                updated_template.write(json.dumps(template_data, indent=4, separators=(',', ': ')))
            elif FILE_FORMAT == 'YAML':
                updated_template.write(utils.CFNYAMLHandler.ordered_safe_dump(template_data, indent=2, allow_unicode=True, default_flow_style=False, explicit_start=True, explicit_end=True))
        updated_template.close()
    else:
        logger.warning("File type not supported. Please use .template file.")
        continue