Add Permission to SQS Queue - PrincipalId is Invalid

Viewed 1042

I am creating an SQS queue and adding permissions to that queue for a specific user inline, but the add_permission call is failing in an unexpected way.

import boto3

queue_name = 'test-queue'
sqs_client = boto3.client('sqs')

response = sqs_client.create_queue(QueueName=queue_name)
queue = boto3.resource('sqs').Queue(response.get('QueueUrl')
queue.add_permission(
    Label='TestReceivePermissions',
    AWSAccountIds=['arn:aws:iam::<account_id>:user/test_user'],
    Actions=['ReceiveMessage']
)

When I execute this code, I receive the following error:

botocore.exceptions.ClientError: An error occurred (InvalidParameterValue) when calling the AddPermission operation: Value [arn:aws:iam::<account_id>:user/test_user] for parameter PrincipalId is invalid. Reason: Unable to verify.

However, I am able to add this same permission to the queue via the AWS console. What am I missing here? Is there another approach I should consider?

UPDATE: One viable workaround is to create a managed policy and then attach the user to the policy like so:

import json, boto3

sqs = boto3.resource('sqs')
iam = boto3.resource('iam')

queue_name = 'test-queue'
USER_NAME = 'test_user'

queue = sqs.create_queue(QueueName=queue_name)
policy = iam.create_policy(
    PolicyName='{}-ReceiveAccess'.format(queue_name),
    PolicyDocument=json.dumps({
        'Version': '2012-10-17',
        'Statement': [
            {
                'Effect': 'Allow',
                'Action': [
                    'sqs:ReceiveMessage*'
                ],
                'Resource': [queue.attributes['QueueArn']]
            }
        ]
    })
)

policy.attach_user(UserName=USER_NAME)

This works for now, but I still do not understand why the other approach was not working.

0 Answers
Related