0

My goals is to restrict access to ec2 using tag key. It works fine if I remove the condition from the IAM policy. However, if I add the aws:TagKeys condition then I get UnauthorizedOperation error. Need some assistance in fixing the IAM policy or either the code to work with tagkey.

Here's the IAM policy:

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

}

Here's my python code:

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")

Here's the exception:

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.

I have checked that tagkey is supported by describeinstances - https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html

Also checked couple of SO threads after which I changed my action to very specific DescribeInstances from Describe* But its still not working for me.

Ganesh S
  • 371
  • 6
  • 26

1 Answers1

0

Got it: Why does applying a condition to ec2:DescribeInstances in an IAM policy fail?

DescribeInstances does not support resource level permissions

Ganesh S
  • 371
  • 6
  • 26