首页 > 解决方案 > 当名称有效时,为什么 AWS boto3 调用 associate_iam_instance_profile 会导致 InvalidParameterValue 无效名称?

问题描述

我有调用 AWS boto3 API 的代码。这段代码使用 iam 客户端和 ec2 客户端做了几件事:

iam_client = boto3.client('iam')
ec2_client = boto3.client('ec2')

对于所有这些调用,角色名称和配置文件名称都是相同的:MyExampleName

  1. 调用iam_client.create_instance_profile以创建新的实例配置文件
  2. 调用iam_client.create_role以创建新角色
  3. 调用iam_client.attach_role_policy以将 AWS 托管策略附加到新角色
  4. 调用iam_client.add_role_to_instance_profile以将新角色添加到实例配置文件
  5. 调用ec2_client.associate_iam_instance_profile以将配置文件关联到实例

但是最后一次调用失败并显示如下消息:

信息“失败:调用 AssociateIamInstanceProfile 操作时发生错误 (InvalidParameterValue):参数 iamInstanceProfile.name 的值 (MyExampleName) 无效。IAM 实例配置文件名称无效,账户 ID:XXXXXXXXXXXXX,资源:EC2 实例:i-78sd976sd6912”

我刚刚创建了配置文件,那么对 associate_iam_instance_profile 的调用怎么会说它无效?

标签: amazon-web-servicesaws-lambdaboto3

解决方案


使用 IAM 客户端和 EC2 客户端都存在一些时间问题。通过 . 创建的配置文件iam_client可能无法立即ec2_client. 通过一些重试逻辑,该名称似乎最终会起作用——它并不是真的无效,只是还没有找到:

import time

logger.info('Attaching profile: MyExampleName'))
counter = 0
while counter < 60:
    try:
        ec2_client.associate_iam_instance_profile(IamInstanceProfile={'Name': 'MyExampleName'},
                                                  InstanceId='i-78sd976sd6912')
        break
    except ClientError as err:
        if err.response['Error']['Code'] == 'InvalidParameterValue':
            counter = counter + 1
            logger.info('The ec2 client did not find the profile yet; wait 1 second and then try again')
            time.sleep(1)
logger.info('Finally worked!')

以下日志显示了一个真实的日志条目示例,显示 EC2 客户端最终与 IAM 客户端一致:

INFO "Attaching profile: MyExampleName"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "Finally worked!"

推荐阅读