我创建了一个lambda函数,我想通过该函数使用预烘焙的AMI以及许多其他标签来启动ec2实例。
Lambda函数:
require 'json'
require 'aws-sdk'
def lambda_handler(event:, context:)
client = Aws::EC2::Client.new(region: 'us-west-2')
images = client.describe_images({
filters: [
{
name: "tag:metatag",
values: ["app"],
},
],
owners: ["<owner_id>"],
dry_run: false,
}).images
latest_image_id = images.first.image_id
ec2 = Aws::EC2::Resource.new(region: 'us-west-2')
instance = ec2.create_instances({
image_id: latest_image_id,
min_count: 1,
max_count: 1,
key_name: '<key-name>',
security_group_ids: ['ApplicationSG'],
instance_type: 't3.large',
subnet_id: '<subnet>',
iam_instance_profile: {
arn: '<arn>'
}
})
instance.batch_create_tags({ tags: [
{ key: 'Name', value: 'testapp08' }
]})
{ statusCode: 200, body: JSON.generate("latest_image_id:#{latest_image_id}, instance: #{instance.inspect}") }
end
使用内联策略创建角色以提供所需的ec2启动权限:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:DetachVolume",
"ec2:AttachVolume",
"ec2:RebootInstances",
"ec2:ResetImageAttribute",
"ec2:DeregisterImage",
"ec2:DeleteTags",
"ec2:CreateTags",
"ec2:ResetSnapshotAttribute",
"ec2:RunInstances",
"ec2:StopInstances",
"ec2:CreateVolume",
"ec2:Describe*",
"ec2:ModifySnapshotAttribute",
"ec2:StartInstances"
],
"Resource": "*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": "logs:*",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
在启用ec2:RunInstances权限时当前出现以下错误
{
"errorMessage": "You are not authorized to perform this operation. Encoded authorization failure message: sGOne-.....",
"errorType": "Function<Aws::EC2::Errors::UnauthorizedOperation>",
"stackTrace": [
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/seahorse/client/plugins/raise_response_errors.rb:15:in `call'",
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/aws-sdk-core/plugins/jsonvalue_converter.rb:20:in `call'",
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/aws-sdk-core/plugins/idempotency_token.rb:17:in `call'",
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/aws-sdk-core/plugins/param_converter.rb:24:in `call'",
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/aws-sdk-core/plugins/response_paging.rb:10:in `call'",
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/seahorse/client/plugins/response_target.rb:23:in `call'",
"/var/runtime/gems/aws-sdk-core-3.40.0/lib/seahorse/client/request.rb:70:in `send_request'",
"/var/runtime/gems/aws-sdk-ec2-1.60.0/lib/aws-sdk-ec2/client.rb:27423:in `run_instances'",
"/var/runtime/gems/aws-sdk-ec2-1.60.0/lib/aws-sdk-ec2/resource.rb:392:in `create_instances'",
"/var/task/lambda_function.rb:21:in `lambda_handler'"
]
}
答案 0 :(得分:1)
此属性:
iam_instance_profile: {
arn: '<arn>'
}
需要iam:PassRole
权限。
这是因为仅具有有限权限的普通用户可能会尝试使用具有超级用户访问权限的角色来启动EC2实例。因此,他们需要iam:PassRole
权限才能启动具有角色的实例。然后,授予此权限的策略可以限制允许他们“通过”哪些角色。
因此,向策略添加iam:PassRole
权限。