使用lambda访问ec2而不使用访问密钥和秘密python

时间:2016-12-07 11:06:31

标签: python amazon-web-services amazon-ec2 lambda

我可以使用boto3 python从lambda函数访问s3和dynamoDB,而无需使用访问密钥和秘密。但是,当我为ec2实例做同样的事情时,它不允许我。抛出以下错误:

"stackTrace": [
[
  "/var/task/lambda_function.py",
  17,
  "lambda_handler",
  "'Arn': ec2Arn"
],
[
  "/var/runtime/boto3/resources/factory.py",
  520,
  "do_action",
  "response = action(self, *args, **kwargs)"
],
[
  "/var/runtime/boto3/resources/action.py",
  83,
  "__call__",
  "response = getattr(parent.meta.client, operation_name)(**params)"
],
[
  "/var/runtime/botocore/client.py",
  159,
  "_api_call",
  "return self._make_api_call(operation_name, kwargs)"
],
[
  "/var/runtime/botocore/client.py",
  494,
  "_make_api_call",
  "raise ClientError(parsed_response, operation_name)"
]
],
"errorType": "ClientError",
"errorMessage": "An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. Encoded authorization failure message: SOME RANDOM STRINGS"}

我在lambda函数中使用的代码是:

def lambda_handler(event, context):
    # TODO implement
    import boto3
    ec2Arn="EC2_ARN_WITH_INSTANCE_PROFILE"
    bdm=[{"DeviceName": "/dev/sda1","Ebs" : { "DeleteOnTermination": True}}]
    sts_client = boto3.client('sts')
    ec2 = boto3.resource("ec2")
    instances = ec2.create_instances(ImageId="AMI_ID",
                                 KeyName="KEYNAME",
                                 MinCount=1,
                                 MaxCount =1,
                                 InstanceType="m3.medium",
                                 SecurityGroups=[security],
                                 BlockDeviceMappings=bdm,
                                 InstanceInitiatedShutdownBehavior="terminate",
                                 IamInstanceProfile={
                                   'Arn': ec2Arn
                                   })

    return "Done"

但是当我尝试调用s3或dynamoDB时,它会成功执行。我也希望以这种方式访问​​ec2,以便我不会不必要地硬编码访问密钥和秘密。

谢谢。

更新:我理解为什么。我传递给ec2的arn无权被lambda函数使用。如果我在不传递实例配置文件的情况下运行lambda函数,我就可以启动实例了。

但我不明白该怎么做?我应该编辑一些角色来为lambda函数添加策略吗?或者还有其他方法吗?

0 个答案:

没有答案
相关问题