未授权错误:使用boto3从启动模板运行AWS Lambda EC2实例

huangapple go评论100阅读模式
英文:

Not Authorised Error: AWS lambda ec2.run_instances from launch template with boto3

问题

我试图从我的Lambda运行AWS EC2实例。从本地计算机创建实例时,我尝试过以下操作:

  1. import boto3
  2. launchTemplateId = 'lt-000'
  3. ec2 = boto3.client('ec2', region_name='ap-xx-1')
  4. template_specifics = {
  5. 'LaunchTemplateId': launchTemplateId
  6. }
  7. resp = ec2.run_instances(
  8. MaxCount=1,
  9. MinCount=1,
  10. LaunchTemplate=template_specifics,
  11. ImageId='ami-00000'
  12. )
  13. print(resp['ResponseMetadata']['HTTPStatusCode'])

而我在Lambda上尝试了以下操作:

  1. def create_instance(lt_id, img_id, region):
  2. """从启动模板创建实例。"""
  3. ec2 = boto3.client('ec2', region_name=region)
  4. resp = ec2.run_instances(
  5. MaxCount=1,
  6. MinCount=1,
  7. LaunchTemplate={
  8. 'LaunchTemplateId': lt_id
  9. },
  10. ImageId=img_id
  11. )
  12. return(resp['ResponseMetadata']['HTTPStatusCode'])

使用IAM策略如下:

  1. ....
  2. {
  3. "Effect": "Allow",
  4. "Action": [
  5. "iam:PassRole",
  6. ],
  7. "Resource": "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${aws_iam_role.xx_role.name}"
  8. },
  9. {
  10. "Effect": "Allow",
  11. "Action": [
  12. "ec2:*"
  13. ],
  14. "Resource": "arn:aws:ec2:${var.aws_region}:${data.aws_caller_identity.current.account_id}:*"
  15. }
  16. ......

请注意,我甚至尝试了通配符*,甚至根据这个评论建议添加了PassRole,但每次都显示以下错误:

  1. ClientError: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. ......
  2. Traceback (most recent call last):
  3. File "/var/task/xxxx.py", line 153, in xxxx_handler
  4. instance_create_resp = create_instance(lt_id, img_id, region)
  5. File "/var/task/xxxx.py", line 79, in create_instance
  6. resp = ec2.run_instances(
  7. File "/var/runtime/botocore/client.py", line 391, in _api_call
  8. return self._make_api_call(operation_name, kwargs)
  9. File "/var/runtime/botocore/client.py", line 719, in _make_api_call
  10. raise error_class(parsed_response, operation_name)

我做错了什么?有任何想法将非常有帮助。

更新
我能够追踪到问题,它是由于“tags”和“InstanceProfile”引起的此错误。

  1. TagSpecifications=[{
  2. 'ResourceType': 'instance',
  3. 'Tags': [
  4. { 'Key': 'Name',
  5. 'Value': 'name'
  6. }]
  7. }],
  8. IamInstanceProfile={
  9. 'Name': PROFILE
  10. },

这会导致相同的错误,否则它可以正常工作。

英文:

I am trying to run aws ec2 instances from my lambda.
Creating instance from local machine works when I tried this -

  1. import boto3
  2. launchTemplateId = 'lt-000'
  3. ec2 = boto3.client('ec2', region_name='ap-xx-1')
  4. template_specifics = {
  5. 'LaunchTemplateId': launchTemplateId
  6. }
  7. resp = ec2.run_instances(
  8. MaxCount=1,
  9. MinCount=1,
  10. LaunchTemplate=template_specifics,
  11. ImageId='ami-00000'
  12. )
  13. print(resp['ResponseMetadata']['HTTPStatusCode'])

And I am trying this on lambda -

  1. def create_instance(lt_id, img_id, region):
  2. """ creates instance from launch template. """
  3. ec2 = boto3.client('ec2', region_name=region)
  4. resp = ec2.run_instances(
  5. MaxCount=1,
  6. MinCount=1,
  7. LaunchTemplate={
  8. 'LaunchTemplateId':lt_id
  9. },
  10. ImageId=img_id
  11. )
  12. return(resp['ResponseMetadata']['HTTPStatusCode'])

with IAM policy -

  1. ....
  2. {
  3. # "Sid": "PassExecutionRole",
  4. "Effect": "Allow",
  5. "Action": [
  6. "iam:PassRole",
  7. ],
  8. "Resource": "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${aws_iam_role.xx_role.name}"
  9. },
  10. {
  11. "Effect": "Allow",
  12. "Action": [
  13. "ec2:*"
  14. # "ec2:StartInstances",
  15. # "ec2:RunInstances"
  16. ],
  17. # "resource": "*"
  18. "Resource": "arn:aws:ec2:${var.aws_region}:${data.aws_caller_identity.current.account_id}:*"
  19. }
  20. ......

Notice I even tried with wildcard * too, even added passRole as a comment suggested but every time it just shows this error -

  1. ClientError: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. ......
  2. Traceback (most recent call last):
  3. File "/var/task/xxxx.py", line 153, in xxxx_handler
  4. instance_create_resp = create_instance(lt_id, img_id, region)
  5. File "/var/task/xxxx.py", line 79, in create_instance
  6. resp = ec2.run_instances(
  7. File "/var/runtime/botocore/client.py", line 391, in _api_call
  8. return self._make_api_call(operation_name, kwargs)
  9. File "/var/runtime/botocore/client.py", line 719, in _make_api_call
  10. raise error_class(parsed_response, operation_name)

What am I doing wrong?
Any ideas will be much helpful.

UPDATE
I was able to track down the problem and it's 'tags' and 'InstanceProfile' which are causing this error.

  1. TagSpecifications=[{
  2. 'ResourceType': 'instance',
  3. 'Tags': [
  4. { 'Key': 'Name',
  5. 'Value': 'name'
  6. }]
  7. }],
  8. IamInstanceProfile={
  9. 'Name': PROFILE
  10. },

This causes the same error, else it works.

答案1

得分: 0

解决方案:
在创建时,Lambda 没有权限来“标记”资源“ec2”。我不得不根据文档建议,将“ec2:CreateTags”添加到策略中,这解决了问题。

  1. {
  2. "Action": [
  3. "ec2:RunInstances"
  4. ],
  5. "Effect": "Allow",
  6. "Resource": "*"
  7. },
  8. {
  9. "Effect": "Allow",
  10. "Action": [
  11. "ec2:CreateTags"
  12. ],
  13. "Resource": "arn:aws:ec2:${var.aws_region}:${data.aws_caller_identity.current.account_id}:*/*",
  14. "Condition": {
  15. "StringEquals": {
  16. "ec2:CreateAction": "RunInstances"
  17. }
  18. }
  19. }

注意:您还需要添加sts权限以传递角色。

祝一切顺利。

英文:

Solution:
The lambda did not have permission to Tag resource ec2 while creating. I had to add "ec2:CreateTags" to the policy as the doc suggested, and this solved the issue.

  1. {
  2. "Action": [
  3. "ec2:RunInstances"
  4. ],
  5. "Effect": "Allow",
  6. "Resource": "*"
  7. },
  8. {
  9. "Effect": "Allow",
  10. "Action": [
  11. "ec2:CreateTags"
  12. ],
  13. "Resource": "arn:aws:ec2:${var.aws_region}:${data.aws_caller_identity.current.account_id}:*/*",
  14. "Condition": {
  15. "StringEquals": {
  16. "ec2:CreateAction" : "RunInstances"
  17. }
  18. }
  19. }

> Note: You will also need to add sts permission for passing role.

Best wishes.

huangapple
  • 本文由 发表于 2023年1月9日 15:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定