当前位置: 首页>>代码示例>>Python>>正文


Python Template.to_template_json方法代码示例

本文整理汇总了Python中template.Template.to_template_json方法的典型用法代码示例。如果您正苦于以下问题:Python Template.to_template_json方法的具体用法?Python Template.to_template_json怎么用?Python Template.to_template_json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在template.Template的用法示例。


在下文中一共展示了Template.to_template_json方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: EnvironmentBase

# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import to_template_json [as 别名]
class EnvironmentBase(object):
    """
    EnvironmentBase encapsulates functionality required to build and deploy a network and common resources for object storage within a specified region
    """

    config_filename = None
    config = {}
    globals = {}
    template_args = {}
    template = None
    manual_parameter_bindings = {}
    subnets = {}
    ignore_outputs = ['templateValidationHash', 'dateGenerated']
    stack_outputs = {}

    def __init__(self, view=None, create_missing_files=True, config_filename=res.DEFAULT_CONFIG_FILENAME):
        """
        Init method for environment base creates all common objects for a given environment within the CloudFormation
        template including a network, s3 bucket and requisite policies to allow ELB Access log aggregation and
        CloudTrail log storage.
        :param view: View object to use.
        :param create_missing_files: Specifies policy to use when local files are missing.  When disabled missing files will cause an IOException
        :param config_filename: The name of the config file to load by default.  Note: User can still override this value from the CLI with '--config-file'.
        """

        # Load the user interface
        if view is None:
            view = cli.CLI()

        # Config filename check has to happen now because the rest of the settings rely on having a loaded config file
        if hasattr(view, 'config_filename') and view.config_filename is not None:
            self.config_filename = view.config_filename
        else:
            self.config_filename = config_filename

        # Config location override
        self.create_missing_files = create_missing_files
        self.handle_local_config()

        # Process any global flags here before letting the view execute any requested user actions
        view.update_config(self.config)

        # Shortcut references to config sections
        self.globals = self.config.get('global', {})
        self.template_args = self.config.get('template', {})

        # Finally allow the view to execute the user's requested action
        view.process_request(self)

    def write_template_to_file(self):
        """
        Serializes self.template to string and writes it to the file named in config['global']['output']
        """
        indent = 0 if not self.config['global']['print_debug'] else 4

        with open(self.config['global']['output'], 'w') as output_file:
            # Here to_json() loads child templates into S3
            raw_json = self.template.to_template_json()

            reloaded_template = json.loads(raw_json)
            json.dump(reloaded_template, output_file, indent=indent, separators=(',', ':'))

    def create_action(self):
        """
        Default create_action invoked by the CLI
        Initializes a new template instance, and write it to file.
        """
        self.initialize_template()

        # Do custom troposphere resource creation in your overridden copy of this method

        self.write_template_to_file()

    def deploy_action(self):
        """
        Default deploy_action invoked by the CLI
        Attempt to query the status of the stack. If it already exists and is in a ready state, it will issue an
        update-stack command. If the stack does not yet exist, it will issue a create-stack command
        """

        # If the boto section of config is used, create the session with it
        # Otherwise, assume boto has been set up another way
        if self.config['boto']['region_name']:
            session = boto3.session.Session(region_name=self.config['boto']['region_name'])
        else:
            session = boto3.session.Session()

        if self.config['boto']['aws_access_key_id'] and self.config['boto']['aws_secret_access_key']:
            cfn_conn = session.client(
                'cloudformation',
                aws_access_key_id=self.config['boto']['aws_access_key_id'],
                aws_secret_access_key=self.config['boto']['aws_secret_access_key']
            )
        else:
            cfn_conn = session.client('cloudformation')

        # Validate existence of and read in the template file
        cfn_template_filename = self.config['global']['output']
        if os.path.isfile(cfn_template_filename):
            with open(self.config['global']['output'], 'r') as cfn_template_file:
#.........这里部分代码省略.........
开发者ID:23andMe,项目名称:cloudformation-environmentbase,代码行数:103,代码来源:environmentbase.py

示例2: EnvironmentBase

# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import to_template_json [as 别名]

#.........这里部分代码省略.........
        return True

    def init_action(self):
        """
        Default init_action invoked by the CLI
        Generates config and ami_cache files
        Override in your subclass for custom initialization steps
        """
        self.generate_config()
        self.generate_ami_cache()

    def s3_prefix(self):
        """
        Allows subclasses to modify the default s3 prefix
        """
        return self.config.get('template').get('s3_prefix')

    def stack_outputs_directory(self):
        """
        Allows subclasses to modify the default stack outputs directory
        """
        return self.config.get('global').get('stack_outputs_directory') or 'stack_outputs'

    def _ensure_template_dir_exists(self):
        template_dir = self.s3_prefix()
        if not os.path.exists(template_dir):
            os.makedirs(template_dir)
        return template_dir

    @staticmethod
    def serialize_templates_helper(template, s3_client, s3_upload=True):

        # Create stack resources for template and all child templates
        raw_json = template.to_template_json()

        # Recursively iterate through each child template to serialize it and process its children
        for child, _, _, _, _ in template._child_templates:
            EnvironmentBase.serialize_templates_helper(
                template=child,
                s3_client=s3_client,
                s3_upload=s3_upload)

        if s3_upload:
            # Upload the template to the s3 bucket under the template_prefix
            s3_client.Bucket(Template.template_bucket_default).put_object(
                Key=template.resource_path,
                Body=raw_json,
                ACL=Template.upload_acl
            )

        # Save the template locally with the same file hierarchy as on s3
        with open(template.resource_path, 'w') as output_file:
            reloaded_template = json.loads(raw_json)
            output_file.write(json.dumps(reloaded_template, indent=4, separators=(',', ':')))

        print "Generated {} template".format(template.name)

        if s3_upload:
            print "S3:\t{}".format(utility.get_template_s3_url(Template.template_bucket_default, template.resource_path))

        print "Local:\t{}\n".format(template.resource_path)


    def serialize_templates(self):
        s3_client = utility.get_boto_resource(self.config, 's3')
        local_file_path = self._ensure_template_dir_exists()
开发者ID:devonartis,项目名称:cloudformation-environmentbase,代码行数:70,代码来源:environmentbase.py

示例3: EnvironmentBase

# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import to_template_json [as 别名]
class EnvironmentBase(object):
    """
    EnvironmentBase encapsulates functionality required to build and deploy a network and common resources for object storage within a specified region
    """

    def __init__(self,
                 view=None,
                 env_config=EnvConfig(),
                 config_filename=res.DEFAULT_CONFIG_FILENAME,
                 config_file_override=None):
        """
        Init method for environment base creates all common objects for a given environment within the CloudFormation
        template including a network, s3 bucket and requisite policies to allow ELB Access log aggregation and
        CloudTrail log storage.
        :param view: View object to use.
        :param create_missing_files: Specifies policy to use when local files are missing.  When disabled missing files will cause an IOException
        :param config_filename: The name of the config file to load by default.  Note: User can still override this value from the CLI with '--config-file'.
        :param config: Override loading config values from file by providing config setting directly to the constructor
        """

        self.config_filename = config_filename
        self.env_config = env_config
        self.config_file_override = config_file_override
        self.config = {}
        self.globals = {}
        self.template_args = {}
        self.template = None
        self.manual_parameter_bindings = {}
        self.deploy_parameter_bindings = []
        self.ignore_outputs = ['templateValidationHash', 'dateGenerated']
        self.stack_outputs = {}
        self._config_handlers = []
        self._deploy_handlers = []

        self.boto_session = None

        # self.env_config = env_config
        for config_handler in env_config.config_handlers:
            self._add_config_handler(config_handler)

        # Load the user interface
        self.view = view if view else cli.CLI()

        # The view may override the config file location (i.e. command line arguments)
        if hasattr(self.view, 'config_filename') and self.view.config_filename is not None:
            self.config_filename = self.view.config_filename

        # Allow the view to execute the user's requested action
        self.view.process_request(self)

    def _ensure_template_dir_exists(self, filename=None):
        parent_dir = TEMPLATES_PATH
        if not os.path.exists(parent_dir):
            os.makedirs(parent_dir)

        if not filename:
            filename = self.globals['output']
        return os.path.join(TEMPLATES_PATH, filename)

    def write_template_to_file(self):
        """
        Serializes self.template to string and writes it to the file named in config['global']['output']
        """
        local_path = self._ensure_template_dir_exists()

        print 'Writing template to %s\n' % self.globals['output']

        with open(local_path, 'w') as output_file:
            # Here to_json() loads child templates into S3
            raw_json = self.template.to_template_json()

            reloaded_template = pure_json.loads(raw_json)
            pure_json.dump(reloaded_template, output_file, indent=4, separators=(',', ':'))

        stack_url = self.upload_template(self.template)
        url_file_path = self._ensure_template_dir_exists('main_template_url')
        with open(url_file_path, 'w') as url_file:
            url_file.write(stack_url)
            
    def _load_template_stack_url(self):
        url_file_path = self._ensure_template_dir_exists('main_template_url')
        return open(url_file_path).readline().rstrip('\n')

    def estimate_cost(self, template_name=None, stack_params=None):
        template_body = self._load_template(template_name)
        # Get url to cost estimate calculator
        cfn_conn = utility.get_boto_client(self.config, 'cloudformation')
        estimate_cost_url = cfn_conn.estimate_template_cost(
            TemplateBody=template_body,
            Parameters=stack_params).get('Url')
        print estimate_cost_url


    def init_action(self):
        """
        Default init_action invoked by the CLI
        Generates config and ami_cache files
        Override in your subclass for custom initialization steps
        """
        self.generate_config()
#.........这里部分代码省略.........
开发者ID:vladlosev,项目名称:cloudformation-environmentbase,代码行数:103,代码来源:environmentbase.py


注:本文中的template.Template.to_template_json方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。