【问题标题】:ec2client.describe_instances returns UnauthorizedOperation after adding condition to IAM policyec2client.describe_instances 在向 IAM 策略添加条件后返回 UnauthorizedOperation
【发布时间】:2019-12-14 12:40:17
【问题描述】:

我的目标是使用标签键限制对 ec2 的访问。如果我从 IAM 策略中删除条件,它工作正常。但是,如果我添加 aws:TagKeys 条件,则会收到 UnauthorizedOperation 错误。在修复 IAM 政策或使用 tagkey 的代码时需要一些帮助。

这是 IAM 政策:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "ec2:DescribeInstances",
            "ec2:DescribeKeyPairs"
        ],
        "Resource": "*",
        "Condition": {
            "ForAnyValue:StringEquals": {
                "aws:TagKeys": "mytag"
            }
        }
    }
]

}

这是我的python代码:

import os
import boto3
import json

os.environ['AWS_DEFAULT_REGION'] = 'ap-south-1'
os.environ['AWS_ACCESS_KEY_ID'] = 'myacceskey'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'secret'

def list_instances_by_tag_value(tagkey, tagvalue):
    # When passed a tag key, tag value this will return a list of InstanceIds that were found.
    ipdict={}
    ec2client = boto3.client('ec2')
    #response = ec2client.describe_key_pairs() 
    #print(response)
    response = ec2client.describe_instances(
        Filters=[
            {
                'Name':'tag:' + tagkey,
                'Values':[tagvalue]
            }
        ]
    )
    client_dict = {}
    for reservation in (response["Reservations"]):
        print(reservation)

#boto3.set_stream_logger(name='botocore')
output = list_instances_by_tag_value("mytag", "abcd")

这是一个例外:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    output = list_instances_by_tag_value("mytag", "abcd")
  File "test.py", line 20, in list_instances_by_tag_value
    'Values':[tagvalue]
  File "C:\python35\lib\site-packages\botocore\client.py", line 272, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\python35\lib\site-packages\botocore\client.py", line 576, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.

我已经检查过 describeinstances 是否支持 tagkey - https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html

还检查了几个 SO 线程,之后我将操作更改为来自 Describe* 的非常具体的 DescribeInstances 但它仍然不适合我。

【问题讨论】:

    标签: python-3.x amazon-ec2 boto3


    【解决方案1】:

    知道了:Why does applying a condition to ec2:DescribeInstances in an IAM policy fail?

    DescribeInstances 不支持资源级权限

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 2021-11-19
      • 2020-11-08
      • 2020-05-29
      • 2021-07-31
      • 2020-09-01
      • 2020-01-23
      • 2016-06-05
      相关资源
      最近更新 更多