修正AWS Systems Manager自动化文档:为停止的EC2实例打标签
修正后的AWS Systems Manager自动化文档(EC2实例标签管理+补丁后启停流程)
问题根源说明
原脚本报错(parameters) Parameter definition does not match any following types,通常是因为参数定义不符合SSM自动化文档的Schema规范,比如缺少必填的Type字段、参数格式错误,或者未遵循SSM允许的参数类型(String、StringList、Integer等)。
完整修正版自动化文档(无Lambda,纯AWS API动作)
以下文档实现完整流程:
- 筛选指定区域内所有已停止的EC2实例
- 为目标实例添加专属标签
- 启动带标签的实例
- (可选)等待Run Command补丁任务完成
- 关闭带标签的实例
- 移除目标标签
description: "Automate EC2 instance tagging, start, patch post-stop and tag removal" schemaVersion: '0.3' parameters: Region: type: String description: "Target AWS region for EC2 instances" default: "us-east-1" PatchTagKey: type: String description: "Key of the tag to mark patch target instances" default: "PatchTarget" PatchTagValue: type: String description: "Value of the tag to mark patch target instances" default: "PendingPatch" # 可选:如果需要等待Run Command任务,添加任务ID参数 # PatchCommandId: # type: String # description: "Run Command task ID for patching" assumeRole: "{{ AutomationAssumeRole }}" mainSteps: # 步骤1:获取指定区域内已停止的EC2实例ID - name: GetStoppedInstances action: 'aws:executeAwsApi' inputs: Service: ec2 Api: DescribeInstances Region: "{{ Region }}" Filters: - Name: instance-state-name Values: ["stopped"] outputs: - Name: InstanceIds Selector: "$.Reservations[].Instances[].InstanceId" Type: StringList # 步骤2:为已停止实例添加标签 - name: TagStoppedInstances action: 'aws:executeAwsApi' inputs: Service: ec2 Api: CreateTags Region: "{{ Region }}" Resources: "{{ GetStoppedInstances.InstanceIds }}" Tags: - Key: "{{ PatchTagKey }}" Value: "{{ PatchTagValue }}" isCritical: true nextStep: StartTaggedInstances # 步骤3:启动带标签的实例 - name: StartTaggedInstances action: 'aws:executeAwsApi' inputs: Service: ec2 Api: StartInstances Region: "{{ Region }}" InstanceIds: "{{ GetStoppedInstances.InstanceIds }}" nextStep: WaitForPatchCompletion # 如果不需要等待,直接跳转到StopTaggedInstances # 可选步骤:等待Run Command补丁任务完成(根据实际需求启用) - name: WaitForPatchCompletion action: 'aws:waitForAwsResourceProperty' inputs: Service: ssm Api: GetCommandInvocation Region: "{{ Region }}" CommandId: "{{ PatchCommandId }}" # 替换为你的Run Command任务ID,或从参数传入 InstanceId: "{{ GetStoppedInstances.InstanceIds }}" PropertySelector: "$.Status" DesiredValues: ["Success", "Failed"] nextStep: StopTaggedInstances # 步骤4:关闭带标签的实例 - name: StopTaggedInstances action: 'aws:executeAwsApi' inputs: Service: ec2 Api: StopInstances Region: "{{ Region }}" InstanceIds: "{{ GetStoppedInstances.InstanceIds }}" nextStep: RemovePatchTags # 步骤5:移除补丁标签 - name: RemovePatchTags action: 'aws:executeAwsApi' inputs: Service: ec2 Api: DeleteTags Region: "{{ Region }}" Resources: "{{ GetStoppedInstances.InstanceIds }}" Tags: - Key: "{{ PatchTagKey }}"
关键修正点说明
- 参数规范修正:所有参数明确指定
type字段,符合SSM自动化文档的参数定义要求,解决原脚本的参数类型不匹配错误。 - 纯API动作实现:全部使用
aws:executeAwsApi调用EC2原生API,无需依赖Lambda,降低复杂度。 - 流程完整性:串联标签添加、实例启停、标签移除全流程,可根据实际需求调整步骤(比如启用/禁用等待补丁任务的步骤)。
- 可扩展性:将标签的Key/Value、目标区域设为可配置参数,方便复用和修改。
内容的提问来源于stack exchange,提问作者Jaya Kandpal
相关产品推荐
相关产品推荐

