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







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章