You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS多账号架构下Lambda无法给SSM托管实例添加标签排查

解决SSM托管实例标签同步的ValidationException错误

你遇到的ValidationException错误,本质是Lambda角色试图修改AWS系统维护的标签,而这类标签是不允许用户手动变更的。

错误原因解析

报错信息里明确提到“not allowed to mutate system tags”——AWS的系统标签都是以aws:开头的(比如aws:cloudformation:stack-id、aws:ssm:managedinstanceids等),这些标签由AWS自动创建和维护,任何用户角色都无权修改或添加它们。你的Lambda代码是直接把子账号EC2实例的所有标签同步到SSM托管实例,这里面大概率包含了子账号实例的系统标签,所以触发了权限校验错误。

解决方案

1. 过滤系统标签(核心修复)

修改Lambda代码,在同步标签前过滤掉所有以aws:开头的标签,只保留用户自定义的标签。调整后的代码如下:

import boto3
import json
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel( logging.WARN )

client = boto3.client( 'ssm' )

def lambda_handler( event, context ):
    """Copies tags from the list of instances in the event context to the specified managed instances. """
    for instance in event[ "instances" ]:
        addTags( instance[ "instanceId" ], instance[ "tags" ] )

def addTags( resourceid, tags ):
    # 过滤掉AWS系统标签(以aws:开头)
    filtered_tags = [tag for tag in tags if not tag['Key'].startswith('aws:')]
    
    if not filtered_tags:
        logger.info(f"No custom tags to sync for managed instance {resourceid}")
        return
    
    logger.info( f"Configuring managed instance {resourceid} with tags: {str(filtered_tags)}" )
    try:
        response = client.add_tags_to_resource(
            ResourceType='ManagedInstance',
            ResourceId=resourceid,
            Tags=filtered_tags
        )
        logger.info( response )
        return response
    except Exception as e:
        errorMessage = str(e) + " instanceId: " + resourceid
        logger.error( errorMessage )
        return errorMessage

2. 优化IAM权限(可选但推荐)

你的现有IAM策略给了过于宽泛的tag:*权限,建议细化权限范围,只允许操作SSM托管实例的标签,提升安全性:

Policies:
  - PolicyName: "CopyInstanceTagsToSSMPolicy"
    PolicyDocument:
      Version: "2012-10-17"
      Statement:
        - Effect: "Allow"
          Action:
            - ssm:AddTagsToResource
            - logs:CreateLogGroup
            - logs:CreateLogStream
            - logs:PutLogEvents
          Resource:
            - "arn:aws:ssm:*:*:managed-instance/*"
            - "arn:aws:logs:*:*:*"

验证步骤

  1. 更新Lambda代码并重新部署
  2. 触发标签同步流程
  3. 查看CloudWatch日志,确认不再出现ValidationException错误,同时SSM托管实例已成功添加自定义标签

内容的提问来源于stack exchange,提问作者Idris.AH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:33:59