如何使用AWS CLI为SQS添加SendMessage权限并配置SNS订阅
Here's how you can replicate the console setup using the AWS CLI, split into two essential steps:
1. Update the SQS Queue Policy
First, you need to apply the permission policy to your SQS queue to allow the target SNS topic to send messages to it. You can do this in two ways:
Option A: Use a JSON file (recommended for readability)
Save your policy into a file named sqs-sns-policy.json with the exact content you provided:
{ "Version": "2012-10-17", "Id": "arn:aws:sqs:us-east-1:7670234568007:stdsourcequeue/SQSDefaultPolicy", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-east-1:7670234568007:stdsourcequeue", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-1:7670234568007:new_posts" } } } ] }
Then run this CLI command (replace <your-queue-url> with your actual SQS queue URL, or use --queue-arn instead if you prefer):
aws sqs set-queue-attributes --queue-url <your-queue-url> --attributes file://sqs-sns-policy.json
Option B: Inline JSON (escape quotes properly)
If you want to run it all in one line, escape the double quotes in the policy:
aws sqs set-queue-attributes --queue-url <your-queue-url> --attributes '{"Policy": "{\"Version\": \"2012-10-17\", \"Id\": \"arn:aws:sqs:us-east-1:7670234568007:stdsourcequeue/SQSDefaultPolicy\", \"Statement\": [{\"Effect\": \"Allow\", \"Principal\": \"*\", \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:us-east-1:7670234568007:stdsourcequeue\", \"Condition\": {\"ArnEquals\": {\"aws:SourceArn\": \"arn:aws:sns:us-east-1:7670234568007:new_posts\"}}}]}" }'
Note: The inline method is error-prone due to quote escaping, so the file approach is better.
2. Subscribe the SQS Queue to the SNS Topic
Next, link your SQS queue to the SNS topic using the subscribe command. Use the exact ARNs from your policy:
aws sns subscribe --topic-arn arn:aws:sns:us-east-1:7670234568007:new_posts --protocol sqs --endpoint arn:aws:sqs:us-east-1:7670234568007:stdsourcequeue
This command will return a subscription ARN, confirming the subscription is created.
Verification (Optional)
To check if the policy was applied correctly, you can retrieve the queue attributes:
aws sqs get-queue-attributes --queue-url <your-queue-url> --attribute-names Policy
And to list subscriptions for your SNS topic:
aws sns list-subscriptions-by-topic --topic-arn arn:aws:sns:us-east-1:7670234568007:new_posts
内容的提问来源于stack exchange,提问作者shrek_23




