在 EC2 TOE中使用条件构造 - EC2Image Builder
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在 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

条件表达式可以在顶层包含以下类型的运算符之一。

  • 比较运算符-有关比较运算符的列表以及它们在 EC2 TOE 组件文档中的工作方式的信息,请参阅比较运算符

  • 逻辑运算符 - 逻辑运算符包括 andor、和 not,并对一个或多个比较运算符进行运算。有关逻辑运算符在 EC2 TOE 组件文档中的工作原理的更多信息,请参阅逻辑运算符

如果您的表达式必须满足多个条件,请使用逻辑运算符来指定您的条件。

then

定义条件表达式的计算结果为 true 时要采取的操作。

else

定义条件表达式的计算结果为 false 时要采取的操作。

步骤操作 条件

使用 thenelse 时,必须指定以下步骤操作之一:

  • Abort - EC2 TOE 将步骤标记为失败。

  • Execute - EC2 TOE 运行步骤。

  • Skip - EC2 TOE 跳过步骤。

示例 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'