当前位置:   article > 正文

Heat模板

heat模板
Heat模板使用说明文档


1 简介
The Orchestration service provides a template-based orchestration for describing a cloud application by running OpenStack API calls to generate running cloud applications. The software integrates other core components of OpenStack into a one-file template system. The templates allow you to create most OpenStack resource types, such as instances, floating IPs, volumes, security groups and users. It also provides advanced functionality, such as instance high availability, instance auto-scaling, and nested stacks. This enables OpenStack core projects to receive a larger user base.
The service enables deployers to integrate with the Orchestration service directly or through custom plug-ins.
The Orchestration service consists of the following components:
heat command-line client
A CLI that communicates with the heat-api to run AWS CloudFormation APIs. End developers can directly use the Orchestration REST API.
heat-api component
An OpenStack-native REST API that processes API requests by sending them to the heat-engine over Remote Procedure Call (RPC).
heat-api-cfn component
An AWS Query API that is compatible with AWS CloudFormation. It processes API requests by sending them to the heat-engine over RPC.
heat-engine
Orchestrates the launching of templates and provides events back to the API consumer.


Heat 目前支持两种格式的模板,一种是基于 JSON 格式的 CFN 模板;另外一种是基于 YAML 格式的 HOT 模板。CFN 模板主要是为了保持对 AWS 的兼容性。HOT 模板的全称是 Heat Orchestration Template,是 Heat 发展的重心。HOT 模板是 Heat 自有的,资源类型更加丰富,更能体现出 Heat 特点的模板。


heat的template描述了所用的所有组件资源以及组件资源之间的关系。 这些资源包括:servers,floating ips, volumes, security groups, users and others. Heat管理这些组件的生命周期,当你需要对现在的部署做一些修改的时候,你只需要对template做一些修改即可。Heat还可以与其他软件管理工具集成比如Puppet以及chef。




Heat 模板必须是 OpenStack HOT 规范中定义的有效 Heat 协调模板 (HOT)。 Heat 模板中引用的所有资源都必须在 OpenStack 环境中定义:
1 映像必须存储在 OpenStack Glance 中。
2 虚拟硬件样板和网络必须在 OpenStack 中定义。
3 密钥必须在项目中注册。












2 模板结构
HOT模板样式由YAML定义,形式如下:
heat_template_version: 2015-10-15


description:
  # a description of the template


parameter_groups:
  # a declaration of input parameter groups and order


parameters:
  # declaration of input parameters


resources:
  # declaration of template resources


outputs:
  # declaration of output parameters


conditions:
  # declaration of conditions


1 heat_template_version
heat 模板版本号:heat 模板的版本号不仅代表模板的格式,也包含所支持的特性。


2 description 可选关键字
该部分是针对当前模板功能的详细描述


3 parameter_groups可选关键字
这是模板的可选部分,该部分定义应该如何组织输入参数


4 parameters可选关键字
这是模板的可选部分,该部分定义在初始化模板时必须提供的输入参数


5 resources
该部分包含模板资源的声明,在任何模板中该部分中都应至少包含一个资源类型,否则模板实际上将不会做任何事情。可以定义资源间的依赖关系,比如说生成 Port,然后再用 port 来生成 VM。


6 outputs可选关键字
这是模板的可选部分,该部分描述在模板初始化后,对用户可见的输出参数。可以用来给用户使用,也可以用来作为输入提供给其它的 Stack。


7 conditions 可选关键字
Note: Support for this section is added in the Newton version.
3 Heat template version
heat模板的版本号不仅代表模板的格式,也包含所支持的特性。每个版本支持的内置方法不同。
Beginning with the Newton release, the version can be either the date of the Heat release or the code name of the Heat release.


目前heat版本号如下
3.1 2013-05-23
 提示: 该版本包含icehouse及以前的heat特性


3.2 2014-10-16
 提示: 该版本包含juno及以前的heat特性,即包含新添加的,也存在删除一些旧特性


3.3 2015-04-30


参考:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#


3.4 2015-10-15
The key with value 2015-10-15 indicates that the YAML document is a HOT template and it may contain features added and/or removed up until the Liberty release.


支持的内置方法功能为:
get_attr
get_file
get_param
get_resource
list_join
repeat
digest
resource_facade
str_replace
str_split


3.5 2016-04-08


参考:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#


3.6 2016-10-14 | newton


参考:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#


3.7 2017-02-24 | ocata


参考:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#


3.8 2017-09-01 | pike


参考:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#


3.9 2018-03-02 | queens


参考:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#




4 Parameter groups section
用于指定参数的顺序,每个参数只能与指定的group关联一次。
parameter_groups:
- label: <human-readable label of parameter group>
  description: <description of the parameter group>
  parameters:
  - <param name>
  - <param name>
label:参数组标签
description:参数组描述
parameters:参数列表
param name:参数名字,与parameters模块中定义的参数关联








5 Parameters section
该部分定义在初始化模板时必须提供的输入参数,例如在每次部署模板时,自定义每次部署的参数值或者绑定到不同环境,例如特定的镜像




每个参数都由嵌套的模块定义,参数名称在第一行定义,而附加属性例如类型或者默认值作为嵌套元素
典型的参数定义如下格式:
parameters:
  <param name>:
    type: <string | number | json | comma_delimited_list | boolean>
    label: <human-readable name of the parameter>
    description: <description of the parameter>
    default: <default value for parameter>
    hidden: <true | false>
    constraints:
      <parameter constraints>
    immutable: <true | false>


格式中每个嵌套元素的含义如下:
param name: 参数的名称
type:参数的类型,支持的类型如string, number,json,comma_delimited_list,Boolean
Type Description Examples
string A literal string. “String param”
number An integer or float. “2”; “0.2”
comma_delimited_list An array of literal strings that are separated by commas. The total number of strings should be one more than the total number of commas. [“one”, “two”]; “one, two”; Note: “one, two” returns [“one”, ” two”]
json A JSON-formatted map or list. {“key”: “value”}
boolean Boolean type value, which can be equal “t”, “true”, “on”, “y”, “yes”, or “1” for true value and “f”, “false”, “off”, “n”, “no”, or “0” for false value. “on”; “n”


label: 可选属性,便于阅读的参数名称/标签
description:可选属性,便于阅读的参数描述
default:可选属性,参数的默认值,当用户没有在部署时定义特定值时将使用默认值来部署栈(stack,下同)
hidden:可选属性,规定当用户使用模板创建栈时,该参数是否应该隐藏,这个属性可以用来隐藏密码类型的参数
constraints:可选属性,对参数的约束,heat引擎部署栈时将使用该约束来检查用户的输入参数是否满足要求
约束类型 约束对象 约束内容
length string length: { min: <lower limit>, max: <upper limit> }
range number range: { min: <lower limit>, max: <upper limit> }
allowed_values string or number allowed_values: [ <value>, <value>, ... ]
allowed_pattern string allowed_pattern: <regular expression>
custom_constraint 检查特定资源是否存在 custom_constraint: <name>
Pseudo parameters stack OS::stack_name
OS::stack_id
OS::project_id




下面是参数定义的简单示例:


parameters:
  user_name:
    type: string
    label: User Name
    description: User name to be configured for the application
  port_number:
    type: number
    label: Port Number
    description: Port number to be configured for the web server


 Parameter constraints
 针对参数的约束有多种约束类型:


 length
 range
 allowed_values
 allowed_pattern
 custom_constraint
 
 参数约束按如下列表形式进行定义:


constraints:
  - <constraint type>: <constraint definition>
    description: <constraint description>
constraint type:约束类型
constraint definition:约束定义,实际定义约束的地方,每个约束类型的具体语法后面会介绍。
description:约束的描述,是可选属性,该文字将在用户提供了不满足于参数要求的值时显示给用户。




如下示例显示了带两个约束的参数定义:
parameters:
  user_name:
    type: string
    label: User Name
    description: User name to be configured for the application
    constraints:
      - length: { min: 6, max: 8 }
        description: User name must be between 6 and 8 characters
      - allowed_pattern: "[A-Z]+[a-zA-Z0-9]*"
        description: User name must start with an uppercase character
约束类型
length 长度
长度约束可应用于字符串(string)类型的参数,它定义了该字符串类型参数的最小和最大长度,语法如下:
length: { min: <下限>, max: <上限> }
可以只定义上限或者下限,但是二者至少要有一个,不可以都不提供


range 范围


范围约束可应用于数值(number)类型的参数,它定义了一个数值类型参数的最小和最大值,语法如下:
range: { min: <下限>, max: <上限> }
可以只定义上限或者下限,但是二者至少要有一个,不可以都不提供




allowed_values 有效值
有效值约束可应用于数值或字符串类型的参数,它指定了一个参数可能出现的参数值集合,在部署时,用户提供的值必须匹配有效值列表中的某个元素
语法如下:
allowed_values: [ <value>, <value>, ... ]


或者如下格式:
allowed_values:
  - <value>
  - <value>
  - ...


例如:
parameters:
  instance_type:
    type: string
    label: Instance Type
    description: Instance type for compute instances
    constraints:
      - allowed_values:
        - m1.small
        - m1.medium
        - m1.large


allowed_pattern 有效模式
有效模式约束可应用于字符串类型的参数,它指定了一个正则表达式用来检查用户提供的参数值,语法如下:


allowed_pattern: <正则表达式>
例如:


parameters:
  user_name:
    type: string
    label: User Name
    description: User name to be configured for the application
    constraints:
      - allowed_pattern: "[A-Z]+[a-zA-Z0-9]*"
        description: User name must start with an uppercase character


custom_constraint 自定义约束
自定义约束增加了校验时的额外检查项,通常同来检查后端的特定资源是否存在,一般自定义约束由插件实现,以提供一些高级的检验逻辑


custom_constraint: <name>


例如:
parameters:
  key_name
    type: string
    description: SSH key pair
    constraints:
      - custom_constraint: nova.keypair




The following section lists the custom constraints and the plug-ins that support them.
Name Plug-in
barbican.container heat.engine.clients.os.barbican:ContainerConstraint
barbican.secret heat.engine.clients.os.barbican:SecretConstraint
cinder.backup heat.engine.clients.os.cinder:VolumeBackupConstraint
cinder.qos_specs heat.engine.clients.os.cinder:QoSSpecsConstraint
cinder.snapshot heat.engine.clients.os.cinder:VolumeSnapshotConstraint
cinder.volume heat.engine.clients.os.cinder:VolumeConstraint
cinder.vtype heat.engine.clients.os.cinder:VolumeTypeConstraint
cron_expression heat.engine.constraint.common_constraints:CRONExpressionConstraint
designate.domain heat.engine.clients.os.designate:DesignateDomainConstraint
designate.zone heat.engine.clients.os.designate:DesignateZoneConstraint
dns_domain heat.engine.constraint.common_constraints:DNSDomainConstraint
dns_name heat.engine.constraint.common_constraints:DNSNameConstraint
expiration heat.engine.constraint.common_constraints:ExpirationConstraint
glance.image heat.engine.clients.os.glance:ImageConstraint
heat.resource_type heat.engine.constraint.heat_constraints:ResourceTypeConstraint
ip_addr heat.engine.constraint.common_constraints:IPConstraint
iso_8601 heat.engine.constraint.common_constraints:ISO8601Constraint
keystone.domain heat.engine.clients.os.keystone.keystone_constraints:KeystoneDomainConstraint
keystone.group heat.engine.clients.os.keystone.keystone_constraints:KeystoneGroupConstraint
keystone.project heat.engine.clients.os.keystone.keystone_constraints:KeystoneProjectConstraint
keystone.region heat.engine.clients.os.keystone.keystone_constraints:KeystoneRegionConstraint
keystone.role heat.engine.clients.os.keystone.keystone_constraints:KeystoneRoleConstraint
keystone.service heat.engine.clients.os.keystone.keystone_constraints:KeystoneServiceConstraint
keystone.user heat.engine.clients.os.keystone.keystone_constraints:KeystoneUserConstraint
mac_addr heat.engine.constraint.common_constraints:MACConstraint
magnum.baymodel heat.engine.clients.os.magnum:BaymodelConstraint
magnum.cluster_template heat.engine.clients.os.magnum:ClusterTemplateConstraint
manila.share_network heat.engine.clients.os.manila:ManilaShareNetworkConstraint
manila.share_snapshot heat.engine.clients.os.manila:ManilaShareSnapshotConstraint
manila.share_type heat.engine.clients.os.manila:ManilaShareTypeConstraint
mistral.workflow heat.engine.clients.os.mistral:WorkflowConstraint
monasca.notification heat.engine.clients.os.monasca:MonascaNotificationConstraint
net_cidr heat.engine.constraint.common_constraints:CIDRConstraint
neutron.address_scope heat.engine.clients.os.neutron.neutron_constraints:AddressScopeConstraint
neutron.flow_classifier heat.engine.clients.os.neutron.neutron_constraints:FlowClassifierConstraint
neutron.lb.provider heat.engine.clients.os.neutron.neutron_constraints:LBaasV1ProviderConstraint
neutron.lbaas.listener heat.engine.clients.os.neutron.lbaas_constraints:ListenerConstraint
neutron.lbaas.loadbalancer heat.engine.clients.os.neutron.lbaas_constraints:LoadbalancerConstraint
neutron.lbaas.pool heat.engine.clients.os.neutron.lbaas_constraints:PoolConstraint
neutron.lbaas.provider heat.engine.clients.os.neutron.lbaas_constraints:LBaasV2ProviderConstraint
neutron.network heat.engine.clients.os.neutron.neutron_constraints:NetworkConstraint
neutron.port heat.engine.clients.os.neutron.neutron_constraints:PortConstraint
neutron.port_pair heat.engine.clients.os.neutron.neutron_constraints:PortPairConstraint
neutron.port_pair_group heat.engine.clients.os.neutron.neutron_constraints:PortPairGroupConstraint
neutron.qos_policy heat.engine.clients.os.neutron.neutron_constraints:QoSPolicyConstraint
neutron.router heat.engine.clients.os.neutron.neutron_constraints:RouterConstraint
neutron.security_group heat.engine.clients.os.neutron.neutron_constraints:SecurityGroupConstraint
neutron.segment heat.engine.clients.os.openstacksdk:SegmentConstraint
neutron.subnet heat.engine.clients.os.neutron.neutron_constraints:SubnetConstraint
neutron.subnetpool heat.engine.clients.os.neutron.neutron_constraints:SubnetPoolConstraint
nova.flavor heat.engine.clients.os.nova:FlavorConstraint
nova.host heat.engine.clients.os.nova:HostConstraint
nova.keypair heat.engine.clients.os.nova:KeypairConstraint
nova.network heat.engine.constraint.common_constraints:TestConstraintDelay
nova.server heat.engine.clients.os.nova:ServerConstraint
rel_dns_name heat.engine.constraint.common_constraints:RelativeDNSNameConstraint
sahara.cluster heat.engine.clients.os.sahara:ClusterConstraint
sahara.cluster_template heat.engine.clients.os.sahara:ClusterTemplateConstraint
sahara.data_source heat.engine.clients.os.sahara:DataSourceConstraint
sahara.image heat.engine.clients.os.sahara:ImageConstraint
sahara.job_binary heat.engine.clients.os.sahara:JobBinaryConstraint
sahara.job_type heat.engine.clients.os.sahara:JobTypeConstraint
sahara.plugin heat.engine.clients.os.sahara:PluginConstraint
senlin.cluster heat.engine.clients.os.senlin:ClusterConstraint
senlin.policy heat.engine.clients.os.senlin:PolicyConstraint
senlin.policy_type heat.engine.clients.os.senlin:PolicyTypeConstraint
senlin.profile heat.engine.clients.os.senlin:ProfileConstraint
senlin.profile_type heat.engine.clients.os.senlin:ProfileTypeConstraint
test_constr heat.engine.constraint.common_constraints:TestConstraintDelay
timezone heat.engine.constraint.common_constraints:TimezoneConstraint
trove.flavor heat.engine.clients.os.trove:FlavorConstraint
zaqar.queue heat.engine.clients.os.zaqar:QueueConstraint




Pseudo Parameters 伪参数
除了模板作者定义的参数,heat模块也为每个栈创建了两个参数来引用栈的名称和id,这两个参数被定义为OS::stack_name 和OS::stack_id
它们的值可以通过get_param 内置方法来获得。


注意:OS::project_id is available since 2015.1 (Kilo).




6 Resources section
模板文件的这些部分中最为关键的是Resources段,Resource具有很多的attribute,例如type等,还有一些可选的attribute,例如depends_on, metadata,properties等。除了属性之外,属性中还会用到一些函数。通过resource,我们可以描述应用系统包含的虚拟机,虚拟机的属性,开机初始化信息,虚拟机软件栈的配置以及应用系统的网络等信息。
Heat中把功能定义成资源,在Heat中会用到Nova,Neutron,Ceilometer等组件,这些都可以看成是资源,通过模板文件来描述,模板文件可以是yaml格式,也可以是json格式,一般是yaml格式。 


模块格式:
resources:
  <resource ID>:
    type: <resource type>
    properties:
      <property name>: <property value>
    metadata:
      <resource specific metadata>
    depends_on: <resource ID or list of ID>
    update_policy: <update policy>
    deletion_policy: <deletion policy>
    external_id: <external resource ID>
    condition: <condition name or expression or boolean>


resource ID:在该template内唯一
type:资源类型,例如OS::Nova::Server or OS::Neutron::Port
参考:https://docs.openstack.org/heat/latest/template_guide/openstack.html
properties:可选关键字,资源特性列表,属性值可以直接提供,或通过一个函数(内部函数见后文)。properties中的user_data: 一般是脚本文件内容,根据环境来配置虚拟机的软件栈。通过在虚拟机内部安装cloudinit和heat-cfntools这两个工具,结合metadata完成应用的自动化部署的大量工作。
metadata:可选关键字,元数据。作为nova创建虚拟机时指定的meta选项, 主要完成虚拟机启动时的基本配置,例如安装软件包,启动服务等等。
depends_on:可选关键字,资源依赖关系
应用举例:一个资源依赖于一个或更多资源时,
resources:
  server1:
    type: OS::Nova::Server
    depends_on: [ server2, server3 ]
 
  server2:
    type: OS::Nova::Server
 
  server3:
    type: OS::Nova::Server
 
update_policy:可选关键字,资源更新策略,是否支持更新策略以及确切的语义取决于资源类型
deletion_policy:可选关键字,资源删除策略,支持的删除策略类型取决于资源类型。表示在删除stack时,资源的删除策略,默认是Delete。指定Retain,表示不删除该资源,对于有快照功能的资源,也可以指定Snapshot,表示在删除前先做快照。
The allowed deletion policies are Delete, Retain, and Snapshot. Beginning with heat_template_version 2016-10-14, the lowercase equivalents delete, retain, and snapshot are also allowed. This attribute is optional; the default policy is to delete the physical resource when deleting a resource from the stack.


heat ResourceGroup资源使用介绍
在heat中有一个ResourceGroup资源,类型是“OS::Heat::ResourceGroup”。
从名称就能够大概猜到该资源的作用:资源组,组内可以包括一个或多个相同的嵌套资源。


通过resource-type-show命令查看该资源的信息,可以看到该资源有以下几项输入属性:
属性 类型 描述
count number 定义资源组包含子资源个数,默认1
index_var string 定义索引替换字符串,默认%index%
removal_policies comma_delimited_list 定义要从资源组中删除的子资源,默认[]
resource_def json 子资源定义,跟在模板中直接定义资源属性相同
其中必须显示指定的属性是resource_def。


另外,该资源的输出属性如下:
属性 描述
attributes 输出子资源指定属性信息
refs 输出所有子资源ID列表
show 输出所有子资源详细信息




下面通过一个例子来演示ResourceGroup资源的使用。


编辑模板文件template.yaml如下:
[plain] view plain copy
heat_template_version: 2015-04-30  
description: create a group of cinder volume  
  
resources:  
  resgroup:  
    type: OS::Heat::ResourceGroup  
    properties:  
      count: 2  
      resource_def:  
        type: OS::Cinder::Volume  
        properties:  
          name: vol-%index%  
          size: 2  
  
outputs:  
    myattributes:  
        value: {"get_attr": [resgroup, "attributes", volume_type]}  
    myrefs:  
        value: {get_attr: ['resgroup', refs]}  
    myshow:  
        value: {get_attr: [resgroup, "show"]}  


然后使用该模板创建stack:
[plain] view plain copy
heat stack-create -f template.yaml mystack  




查看创建成功后的结果:
[plain] view plain copy
# heat stack-list -n  
+--------------------------------------+-------------------------------+-----------------+---------------------+--------------------------------------+  
| id                                   | stack_name                    | stack_status    | creation_time       | parent                               |  
+--------------------------------------+-------------------------------+-----------------+---------------------+--------------------------------------+  
| b309d171-b98e-4577-a596-ebce15556953 | mystack                       | CREATE_COMPLETE | 2015-08-31T05:56:30 | None                                 |  
| 9fe9df0b-d5db-4da4-8aa3-a65aed4a2775 | mystack-resgroup-pwgynlfi5p3g | CREATE_COMPLETE | 2015-08-31T05:56:34 | b309d171-b98e-4577-a596-ebce15556953 |  
+--------------------------------------+-------------------------------+-----------------+---------------------+--------------------------------------+  
# heat resource-list -n 1 mystack  
+---------------+--------------------------------------+-------------------------+-----------------+---------------------+-------------------------------+  
| resource_name | physical_resource_id                 | resource_type           | resource_status | updated_time        | stack_name                    |  
+---------------+--------------------------------------+-------------------------+-----------------+---------------------+-------------------------------+  
| resgroup      | 9fe9df0b-d5db-4da4-8aa3-a65aed4a2775 | OS::Heat::ResourceGroup | CREATE_COMPLETE | 2015-08-31T05:56:34 | mystack                       |  
| 0             | 0365818e-27ec-4773-a785-bb4875856a0b | OS::Cinder::Volume      | CREATE_COMPLETE | 2015-08-31T05:56:35 | mystack-resgroup-pwgynlfi5p3g |  
| 1             | db4935c4-6250-4778-893f-1e7683a667b8 | OS::Cinder::Volume      | CREATE_COMPLETE | 2015-08-31T05:56:35 | mystack-resgroup-pwgynlfi5p3g |  
+---------------+--------------------------------------+-------------------------+-----------------+---------------------+-------------------------------+  
可以看到,ResourceGroup资源实际上是生成了一个嵌套stack(如上mystack-resgroup-pwgynlfi5p3g),资源组中的那些子资源实际是属于嵌套stack。
按照模板的配置,生成了两个Volume类型的子资源。


再来查看outputs:
[plain] view plain copy
# heat output-show mystack myattributes  
{  
  "1": "lvmdriver-1",   
  "0": "lvmdriver-1"  
}  
# heat output-show mystack myrefs  
[  
  "0365818e-27ec-4773-a785-bb4875856a0b",   
  "db4935c4-6250-4778-893f-1e7683a667b8"  
]  
按照模板配置,myattributes是输出的Volume子资源的volume_type属性(如上lvmdriver-1)。
而myrefs是输出的资源组的refs属性,实际效果是子资源ID列表。
还有一个myshow,是子资源的详细信息,由于输出太长这里没有贴出来。


看了上面的例子,对资源组的使用也就大体有了一个了解。
这时候就面临着另一个问题,如果stack创建完成后需要调整子资源的数量,怎么实现?
调整模板中的count参数,然后用stack-update命令即可。
例如在上面模板的基础上,把count改为3,stack-update之后再查看子资源,就会发现多了一个名称为2的子资源。
而如果把count改为1,stack-update之后,就只剩下名称为0的子资源了。
注:子资源移除是删除名称数字较大的,保留名称数字较小的。例如上面更新子资源数量为1后,就把名称为1和2的子资源删除了,剩下名称为0的子资源。


那是否能够删除指定的子资源呢?答案是肯定的。前面提到的removal_policies属性就是这个作用。
直接上例子。
按照前面的例子创建一个stack,创建成功后有两个子资源0和1。
这时候如果想删除子资源0,可以这样配置模板中的ResourceGroup资源,增加removal_policies属性:
[plain] view plain copy
resgroup:  
    type: OS::Heat::ResourceGroup  
    properties:  
      count: 1  
      removal_policies: [{resource_list: [0]}]  
      resource_def:  
        type: OS::Cinder::Volume  
        properties:  
          name: vol-%index%  
          size: 2  
其中,resource_list键对应的是一个列表,列表包含的是要删除的子资源名称,也可以是子资源的ID。上面是指定的名称0。
更新stack之后,可以看到0子资源被删除了,1子资源保留下来了:
[plain] view plain copy
# heat resource-list -n 1 mystack  
+---------------+--------------------------------------+-------------------------+-----------------+---------------------+-------------------------------+  
| resource_name | physical_resource_id                 | resource_type           | resource_status | updated_time        | stack_name                    |  
+---------------+--------------------------------------+-------------------------+-----------------+---------------------+-------------------------------+  
| 1             | affd7faf-8735-4a3a-ba09-6e0f50f385c8 | OS::Cinder::Volume      | CREATE_COMPLETE | 2015-08-31T06:32:30 | mystack-resgroup-pwgynlfi5p3g |  
| resgroup      | 9fe9df0b-d5db-4da4-8aa3-a65aed4a2775 | OS::Heat::ResourceGroup | UPDATE_COMPLETE | 2015-08-31T07:04:21 | mystack                       |  
+---------------+--------------------------------------+-------------------------+-----------------+---------------------+-------------------------------+  


至此,ResourceGroup资源的使用介绍完毕。
总结一下:ResourceGroup主要用在需要创建多个相同资源的场景,好处一是能够简化模板的编写,二是可以方便地调整资源数量。




7 Outputs section


outputs:
  <parameter name>:
    description: <description>
    value: <parameter value>
    condition: <condition name or expression or boolean>


parameter name:输出参数名字,template内唯一
description:可选参数,输出参数描述
value:输出参数值,通常由函数得到(内部函数见后文)
condition: 可选参数,有条件的定义输出值。
Note: Support condition for output is added in the Newton version.


示例:
outputs:
  instance_ip:
    description: IP address of the deployed compute instance
    value: { get_attr: [my_instance, first_address] }




8 Conditions section
The conditions section is defined with the following syntax
conditions:
  <condition name1>: {expression1}
  <condition name2>: {expression2}
  ...
condition name
The condition name, which must be unique within the conditions section of a template.
expression
The expression which is expected to return True or False. Usually, the condition functions can be used as expression to define conditions:
equals
get_param
not
and
or
yaql
Note: In condition functions, you can reference a value from an input parameter, but you cannot reference resource or its attribute. We support referencing other conditions (by condition name) in condition functions. We support ‘yaql’ as condition function in the Pike version.
An example of conditions section definition
conditions:
  cd1: True
  cd2:
    get_param: param1
  cd3:
    equals:
    - get_param: param2
    - yes
  cd4:
    not:
      equals:
      - get_param: param3
      - yes
  cd5:
    and:
    - equals:
      - get_param: env_type
      - prod
    - not:
        equals:
        - get_param: zone
        - beijing
  cd6:
    or:
    - equals:
      - get_param: zone
      - shanghai
    - equals:
      - get_param: zone
      - beijing
  cd7:
    not: cd4
  cd8:
    and:
    - cd1
    - cd2
  cd9:
    yaql:
      expression: $.data.services.contains('heat')
      data:
        services:
          get_param: ServiceNames
  cd10:
    contains:
    - 'neutron'
    - get_param: ServiceNames
The example below shows how to associate condition with resources
parameters:
  env_type:
    default: test
    type: string
conditions:
  create_prod_res: {equals : [{get_param: env_type}, "prod"]}
resources:
  volume:
    type: OS::Cinder::Volume
    condition: create_prod_res
    properties:
      size: 1
The ‘create_prod_res’ condition evaluates to true if the ‘env_type’ parameter is equal to ‘prod’. In the above sample template, the ‘volume’ resource is associated with the ‘create_prod_res’ condition. Therefore, the ‘volume’ resource is created only if the ‘env_type’ is equal to ‘prod’.
The example below shows how to conditionally define an output
outputs:
  vol_size:
    value: {get_attr: [my_volume, size]}
    condition: create_prod_res
In the above sample template, the ‘vol_size’ output is associated with the ‘create_prod_res’ condition. Therefore, the ‘vol_size’ output is given corresponding value only if the ‘env_type’ is equal to ‘prod’, otherwise the value of the output is None.




9 Intrinsic functions内部函数
Heat模板内部函数称为Intrinsic functions。
Note:这些函数只能用于resource的properties模块,或output模块。
 
9.1   get_attr:引用资源属性
基于关键字或索引的方法需要heat_template_version 2014-10-16或更高
2015-10-15以后,<attribute_name>为可选关键字,缺省为all attributes
get_attr:
  - <resource_name>


作用:获取所创建资源的属性。
语法:


get_attr:
  - <resource name>
  - <attribute name>
  - <key/index 1> (optional)
  - <key/index 2> (optional)
  - ...


Resource name:必须是模板 resouce 段中指定的资源。
Attribute name:要获取的属性,如果属性对应的值是list 或map, 则可以指定key/index来获取具体的值。
示例:


resources:
  my_instance:
    type: OS::Nova::Server
    # ...


outputs:
  instance_ip:
    description: IP address of the deployed compute instance
    value: { get_attr: [my_instance, first_address] }
  instance_private_ip:
    description: Private IP address of the deployed compute instance
    value: { get_attr: [my_instance, networks, private, 0] }


在这个例子中,如果networks属性包含下面数据:
{"public": ["2001:0db8:0000:0000:0000:ff00:0042:8329", "1.2.3.4"],
 "private": ["10.0.0.1"]}
get_attr函数的值为10.0.0.1 (first item of the private entry in the networks map).


 
9.2   get_file:返回template中file的内容
实参必须是一个静态路径或URL,且不能依赖于内部函数。
It is generally used as a file inclusion mechanism for files containing scripts or configuration files.


语法:
get_file: <content key>
示例:
resources:
  my_instance:
    type: OS::Nova::Server
    properties:
      # general properties ...
      user_data:
        get_file: my_instance_user_data.sh
  my_other_instance:
    type: OS::Nova::Server
    properties:
      # general properties ...
      user_data:
        get_file: http://example.com/my_other_instance_user_data.sh
The files dictionary generated by the Orchestration client during instantiation of the stack would contain the following keys:
file:///path/to/my_instance_user_data.sh
http://example.com/my_other_instance_user_data.sh






9.3   get_param:引用模板的输入参数
作用:引用模板中指定的参数。
语法:
get_param:
 - <parameter name>
 - <key/index 1> (optional)
 - <key/index 2> (optional)
 - ...
parameter name
The parameter name to be resolved. If the parameters returns a complex data structure such as a list or a map, then subsequent keys or indexes can be specified. These additional parameters are used to navigate the data structure to return the desired value.
示例:
parameters:
  instance_type:
    type: string
    label: Instance Type
    description: Instance type to be used.
  server_data:
    type: json


resources:
  my_instance:
    type: OS::Nova::Server
    properties:
      flavor: { get_param: instance_type}
      metadata: { get_param: [ server_data, metadata ] }
      key_name: { get_param: [ server_data, keys, 0 ] }
输入参数是:
{"instance_type": "m1.tiny",
{"server_data": {"metadata": {"foo": "bar"},
                 "keys": ["a_key","other_key"]}}}
then the value of the property flavor would resolve to m1.tiny, metadata would resolve to {"foo": "bar"} and key_name would resolve to a_key.
 
9.4   get_resource:引用同一模板中的其他resource
语法:
get_resource: <resource ID>
The resource ID of the referenced resource is given as single parameter to the get_resource function.
示例:
resources:
  instance_port:
    type: OS::Neutron::Port
    properties: ...


  instance:
    type: OS::Nova::Server
    properties:
      ...
      networks:
        port: { get_resource: instance_port }
 
9.5   list_join:把给定分隔符加入strings列表
作用:使用指定的分隔符将一个list中的字符串合成一个字符串。
语法:
list_join:
- <delimiter>
- <list to join>
示例:
list_join: [', ', ['one', 'two', 'and three']]
示例输出: one, two, and three.
From HOT version 2015-10-15 you may optionally pass additional lists, which will be appended to the previous lists to join.
For example:
list_join: [', ', ['one', 'two'], ['three', 'four']]
This resolve to the string one, two, three, four.
From HOT version 2015-10-15 you may optionally also pass non-string list items (e.g json/map/list parameters or attributes) and they will be serialized as json before joining.
 
 
9.6   digest:对给定值进行digest操作
Kilo版本引进,2015-04-30之后版本可用
算法由hashlib提供(md5, sha1, sha224, sha256, sha384, and sha512),或OpenSSL


作用:在指定的值上使用algorithm。
语法:
digest:
  - <algorithm>
  - <value>
algorithm
The digest algorithm. Valid algorithms are the ones provided natively by hashlib (md5, sha1, sha224, sha256, sha384, and sha512) or any one provided by OpenSSL.
value
The value to digest. This function will resolve to the corresponding hash of the value.


示例:
# from a user supplied parameter
pwd_hash: { digest: ['sha512', { get_param: raw_password }] }
The value of the digest function would resolve to the corresponding hash of the value of raw_password.




9.7   repeat:动态改变模板资源列表中的内容,返回一个新的列表
list内容可以来自一个函数
The repeat function allows for dynamically transforming lists by iterating over the contents of one or more source lists and replacing the list elements into a template. The result of this function is a new list, where the elements are set to the template, rendered for each list item.
作用:迭代fore_each中的列表,按照template的格式生成一个list。
语法:
repeat:
  template:
    <template>
  for_each:
    <var>: <list>
template
The template argument defines the content generated for each iteration, with placeholders for the elements that need to be replaced at runtime. This argument can be of any supported type.
for_each
The for_each argument is a dictionary that defines how to generate the repetitions of the template and perform substitutions. In this dictionary the keys are the placeholder names that will be replaced in the template, and the values are the lists to iterate on. On each iteration, the function will render the template by performing substitution with elements of the given lists. If a single key/value pair is given in this argument, the template will be rendered once for each element in the list. When more than one key/value pairs are given, the iterations will be performed on all the permutations of values between the given lists. The values in this dictionary can be given as functions such as get_attr or get_param.


示例:
The following example shows how a security group resource can be defined to include a list of ports given as a parameter
parameters:
  ports:
    type: comma_delimited_list
    label: ports
    default: "80,443,8080"


resources:
  security_group:
    type: OS::Neutron::SecurityGroup
    properties:
      name: web_server_security_group
      rules:
        repeat:
          for_each:
            <%port%>: { get_param: ports }
          template:
            protocol: tcp
            port_range_min: <%port%>
            port_range_max: <%port%>
The following example demonstrates how the use of multiple lists enables the security group to also include parameterized protocols
parameters:
  ports:
    type: comma_delimited_list
    label: ports
    default: "80,443,8080"
  protocols:
    type: comma_delimited_list
    label: protocols
    default: "tcp,udp"


resources:
  security_group:
    type: OS::Neutron::SecurityGroup
    properties:
      name: web_server_security_group
      rules:
        repeat:
          for_each:
            <%port%>: { get_param: ports }
            <%protocol%>: { get_param: protocols }
          template:
            protocol: <%protocol%>
            port_range_min: <%port%>
Note how multiple entries in the for_each argument are equivalent to nested for-loops in most programming languages.
From HOT version 2016-10-14 you may also pass a map as value for the for_each key, in which case the list of map keys will be used as value.
From HOT version 2017-09-01 (or pike) you may specify a argument permutations to decide whether to iterate nested the over all the permutations of the elements in the given lists. If ‘permutations’ is not specified, we set the default value to true to compatible with before behavior. The args have to be lists instead of dicts if ‘permutations’ is False because keys in a dict are unordered, and the list args all have to be of the same length.
parameters:
  subnets:
    type: comma_delimited_list
    label: subnets
    default: "sub1, sub2"
  networks:
    type: comma_delimited_list
    label: networks
    default: "net1, net2"


resources:
  my_server:
    type: OS::Nova:Server
    properties:
      networks:
        repeat:
          for_each:
            <%sub%>: { get_param: subnets }
            <%net%>: { get_param: networks }
          template:
            subnet: <%sub%>
            network: <%net%>
          permutations: false
After resolved, we will get the networks of server like: [{subnet: sub1, network: net1}, {subnet: sub2, network: net2}]
 
9.8   resource_facade:在父模板中提取数据
作用:检索资源的数据。
语法:
resource_facade: <data type>
data type:metadata、deletion_policy、update_policy
 
9.9 str_replace:用给定值替换template中的相应内容
作用:使用params中的值替换template中的占位符,从而构造一个新的字符串。
语法:
str_replace:
  template: <template string>
  params: <parameter mappings>
示例:
 
resources:
  my_instance:
    type: OS::Nova::Server
    # general metadata and properties ...
 
outputs:
  Login_URL:
    description: The URL to log into the deployed application
    value:
      str_replace:
        template: http://host/MyApplication
        params:
          host: { get_attr: [ my_instance, first_address ] }
 
template 中 host 将会被替换。


9.10 str_split:list_join的相反操作
作用:将一个字符串按照分隔符分隔成一个list
语法:
str_split:
  - ','
  - string,to,split
示例:
str_split: [',', 'string,to,split']
结果是['string', 'to', 'split']




以下函数参考官网:https://docs.openstack.org/heat/latest/template_guide/hot_spec.html#
9.11 map_merge


9.12 map_replace


9.13 yaql




9.14 filter




9.15 make_url




9.16 list_concat 




9.17 list_concat_unique




9.18 contains




9.19 其它:equals, if, not, and, or




10 模板示例
开发模板时,建议您使用参数并避免硬编码值。
在下列示例中,示例 1 和示例 2 取自 OpenStack Template Guide,它们说明使用硬编码值与使用参数的差别。
示例 3 说明如何使用查找注释来生成参数的可能值列表,这可以帮助用户选择有效的参数值。
示例 4 说明如何使用 user_data 节针对虚拟机设置 admin 密码。


示例 1
以下示例是一个用于部署单个虚拟系统的简单 Heat 模板,该示例限制为此模板中硬编码的映像、密钥和虚拟硬件样板值的单一组合:
heat_template_version: 2013-05-23


description: Simple template to deploy a single compute instance with hardcoded values


resources:
  my_instance:
    type: OS::Nova::Server
    properties:
      key_name: my_key_pair_1
      image: cirros-0.3.1-x86_64
      flavor: m1.tiny


示例 2
以下示例是一个 Heat 模板,它使用参数来部署单个虚拟系统,因此可以复用于其他配置:
heat_template_version: 2013-05-23
description: Simple template to deploy a single compute instance with parameters


parameters:
  key_name:
    type: string
    label: Key Name
    description: Name of key-pair to be used for compute instance
  image_id:
    type: string
    label: Image ID
    description: Image to be used for compute instance
  instance_type:
    type: string
    label: Instance Type
    description: Type of instance (flavor) to be used
resources:
  my_instance:
    type: OS::Nova::Server
    properties:
      key_name: { get_param: key_name }
      image: { get_param: image_id }
      flavor: { get_param: instance_type }


示例 3
以下示例是一个简单的 Heat 模板,它通过使用参数的查找注释来部署具有两个虚拟机实例的堆栈:
heat_template_version: 2013-05-23


description: Simple template to deploy a stack with two virtual machine instances


parameters:
  image_name_1: 
    type: string 
    label: Image Name 
    description: SCOIMAGE Specify an image name for instance1 
    default: cirros-0.3.1-x86_64
  image_name_2: 
    type: string 
    label: Image Name 
    description: SCOIMAGE Specify an image name for instance2 
    default: cirros-0.3.1-x86_64 
  network_id:
    type: string
    label: Network ID
    description: SCONETWORK Network to be used for the compute instance


resources: 
  my_instance1: 
    type: OS::Nova::Server 
    properties: 
      image: { get_param: image_name_1 } 
      flavor: m1.small 
      networks:
        - network : { get_param : network_id }
  my_instance2: 
    type: OS::Nova::Server 
    properties: 
      image: { get_param: image_name_2 } 
      flavor: m1.tiny
      networks:
        - network : { get_param : network_id }


示例 4
以下示例是一个简单的 Heat 模板,此模板通过使用 user_data 节来针对虚拟机设置 admin 密码:
heat_template_version: 2013-05-23


description: Simple template to set the admin password for a virtual machine


parameters:
  key_name:
    type: string
    label: Key Name
    description: SCOKEY Name of the key pair to be used for the compute instance
  image_name:
    type: string
    label: Image Name
    description: SCOIMAGE Name of the image to be used for the compute instance
  password:
    type: string
    label: password
    description: admin password
    hidden: true


 
resources:
  my_instance:
    type: OS::Nova::Server
    properties:
      key_name: { get_param: key_name }
      admin_user: sampleuser
      image: { get_param: image_name }
      flavor: m1.small
      user_data:
        str_replace:
          template: |
            #!/bin/bash
            echo "Setting  password to  " $password           
            echo $password |passwd --stdin sampleuser


          params:
            $password: { get_param: password }




官方模板
https://github.com/openstack/heat-templates/tree/master/hot




11 创建一个启动实例的栈
创建一个模板¶
Orchestration服务使用模版来描述栈。想要学习模版语言,参考`Heat developer documentation <http://docs.openstack.org/developer/heat/index.html>`__中的`the Template Guide <http://docs.openstack.org/developer/heat/template_guide/index.html>`__ 。`
使用下面的内容创建``demo-template.yml``文件:
heat_template_version: 2015-10-15
description: Launch a basic instance using the ``m1.tiny`` flavor and one network.


parameters:
  ImageID:
    type: string
    description: Image to use for the instance.
  NetID:
    type: string
    description: Network ID to use for the instance.


resources:
  server:
    type: OS::Nova::Server
    properties:
      image: { get_param: ImageID }
      flavor: m1.tiny
      networks:
      - network: { get_param: NetID }


outputs:
  instance_name:
    description: Name of the instance.
    value: { get_attr: [ server, name ] }
  instance_ip:
    description: IP address of the instance.
    value: { get_attr: [ server, first_address ] }
创建一个栈¶
使用``demo-template.yml`` 模版创建一个栈。
1. 加载 ``demo``凭证,作为非管理员项目执行下面的步骤:
$ source demo-openrc.sh
2. 检测可用网络。
$ neutron net-list
+--------------------------------------+---------+-----------------------------------------------------+
| id                                   | name    | subnets                                             |
+--------------------------------------+---------+-----------------------------------------------------+
| 9c13da20-4c4f-486f-a4e9-692e9ea397f1 | public  | 85140549-1f54-4bc6-a2c5-f08428de3f7a 203.0.113.0/24 |
| 303a9aaf-40fd-4fc8-9213-39bff933467b | private | ddeba0b1-21eb-471a-8f31-10f0e290cc36 172.16.1.0/24  |
+--------------------------------------+---------+-----------------------------------------------------+
 
注解
这个输出可能跟你的环境有所不同。
3. 设置``NET_ID``环境变量表示网络ID。例如,使用``public`` 网络:
$ export NET_ID=$(neutron net-list | awk '/ public / { print $2 }')
4. 在公共网络上创建一个CirrOS实例的栈:
$ heat stack-create -f demo-template.yml -P "ImageID=cirros;NetID=$NET_ID" stack
+--------------------------------------+------------+--------------------+---------------------+--------------+
| id                                   | stack_name | stack_status       | creation_time       | updated_time |
+--------------------------------------+------------+--------------------+---------------------+--------------+
| dbf46d1b-0b97-4d45-a0b3-9662a1eb6cf3 | stack      | CREATE_IN_PROGRESS | 2015-10-13T15:27:20 | None         |
+--------------------------------------+------------+--------------------+---------------------+--------------+
5. 等一段时间,验证栈的创建是否成功:
$ heat stack-list
+--------------------------------------+------------+-----------------+---------------------+--------------+
| id                                   | stack_name | stack_status    | creation_time       | updated_time |
+--------------------------------------+------------+-----------------+---------------------+--------------+
| dbf46d1b-0b97-4d45-a0b3-9662a1eb6cf3 | stack      | CREATE_COMPLETE | 2015-10-13T15:27:20 | None         |
+--------------------------------------+------------+-----------------+---------------------+--------------+
6. 查看实例的名称和IB地址并和``nova`` 命令的输出比较:
$ heat output-show --all stack
[
  {
    "output_value": "stack-server-3nzfyfofu6d4",
    "description": "Name of the instance.",
    "output_key": "instance_name"
  },
  {
    "output_value": "10.4.31.106",
    "description": "IP address of the instance.",
    "output_key": "instance_ip"
  }
]


$ nova list
+--------------------------------------+---------------------------+--------+------------+-------------+---------------------------------+
| ID                                   | Name                      | Status | Task State | Power State | Networks                        |
+--------------------------------------+---------------------------+--------+------------+-------------+---------------------------------+
| 0fc2af0c-ae79-4d22-8f36-9e860c257da5 | stack-server-3nzfyfofu6d4 | ACTIVE | -          | Running     | public=10.4.31.106              |
+--------------------------------------+---------------------------+--------+------------+-------------+---------------------------------+
7. 删除栈。
$ heat stack-delete stack







声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/70568
推荐阅读
相关标签
  

闽ICP备14008679号