本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在 EC2 TOE中使用条件构造
根据指定的条件表达式的计算结果是 true
还是 false
,条件构造会在组件文档中执行不同的操作。您可以使用 if
构造来控制组件文档中的执行流程。
if 构造
您可以使用 if
构造来评估是否应该运行某步骤。默认情况下,当 if
条件表达式的计算结果为 true
时, EC2 TOE 运行该步骤,当条件表达式计算结果为 false
时, EC2 TOE 跳过该步骤。如果跳过某个步骤,则在 EC2 TOE 评估阶段和文档是否成功运行时,该步骤将被视为成功步骤。
注意
即使该步骤触发了重启,也只对一个 if
语句进行一次计算。如果某个步骤重启,它就会识别出 if
语句已经进行计算,并从中断的地方继续进行。
语法
if: - <conditional expression>: [then: <step action>] [else: <step action>]
键名称 | Required | 描述 |
---|---|---|
条件表达式 | Yes |
条件表达式可以在顶层包含以下类型的运算符之一。 如果您的表达式必须满足多个条件,请使用逻辑运算符来指定您的条件。 |
then | 否 |
定义条件表达式的计算结果为 |
else | 否 |
定义条件表达式的计算结果为 |
步骤操作 | 条件 |
使用
|
示例 1:安装软件包
EC2 TOE 组件文档中的以下示例步骤使用逻辑运算符来测试参数值,并在软件包解压缩后运行相应的软件包管理器命令来安装应用程序。
- name: InstallUnzipAptGet action: ExecuteBash if: and: - binaryExists: 'apt-get' - not: binaryExists: 'unzip' inputs: commands: - sudo apt-get update - sudo apt-get install -y unzip - name: InstallUnzipYum action: ExecuteBash if: and: - binaryExists: 'yum' - not: binaryExists: 'unzip' inputs: commands: - sudo yum install -y unzip - name: InstallUnzipZypper action: ExecuteBash if: and: - binaryExists: 'zypper' - not: binaryExists: 'unzip' inputs: commands: - sudo zypper refresh - sudo zypper install -y unzip
示例 2:跳过步骤
以下示例显示了跳过步骤的两种方法。一种是使用逻辑运算符,另一种是结合使用比较运算符与 Skip
步骤操作。
# Creates a file if it does not exist using not - name: CreateMyConfigFile-1 action: ExecuteBash if: not: fileExists: '/etc/my_config' inputs: commands: - echo "Hello world" > '/etc/my_config' # Creates a file if it does not exist using then and else - name: CreateMyConfigFile-2 action: ExecuteBash if: fileExists: '/etc/my_config' then: Skip else: Execute inputs: commands: - echo "Hello world" > '/etc/my_config'