在中使用条件构造 AWSTOE - EC2Image Builder

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

在中使用条件构造 AWSTOE

根据指定的条件表达式的计算结果是否为或,条件构造在组件文档中执行不同的操作。true false您可以使用if构造来控制组件文档中的执行流程。

如果构造

您可以使用该if构造来评估步骤是否应该运行。默认情况下,当if条件表达式的计算结果为true,则 AWSTOE 运行该步骤,当条件计算为时false, AWSTOE 跳过该步骤。如果跳过某个步骤,则在 AWSTOE 评估该阶段和文档是否成功运行时,该步骤将被视为成功步骤。

注意

即使该步骤触if发了重启,也只能对一条语句进行一次求值。如果某个步骤重新启动,它就会识别出该if语句已经过评估,并从中断的地方继续执行。

语法

if: - <conditional expression>: [then: <step action>] [else: <step action>]
键名称 必需 描述
条件表达式

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

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

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

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

then

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

else

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

步进动作 条件

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

  • 中止 — 将步骤 AWSTOE 标记为失败。

  • 执行- AWSTOE 运行该步骤。

  • 跳过 — AWSTOE 跳过该步骤。

示例 1:安装软件包

AWSTOE 组件文档中的以下示例步骤使用逻辑运算符来测试参数值,并在软件包解压缩后运行相应的软件包管理器命令来安装应用程序。

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