要为AWS SNS主题的AWS SQS订阅设置访问控制,可以使用IAM策略来限制对此订阅的访问权限。下面是一个包含代码示例的解决方法:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowSQSAccess",
"Effect": "Allow",
"Action": [
"sqs:SendMessage",
"sqs:ReceiveMessage",
"sqs:DeleteMessage"
],
"Resource": "arn:aws:sqs:region:account-id:queue-name"
}
]
}
请将region替换为您的AWS区域,account-id替换为您的AWS账号ID,queue-name替换为您的SQS队列名称。
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowSNSToSQSAccess",
"Effect": "Allow",
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:region:account-id:queue-name"
}
]
}
请将region替换为您的AWS区域,account-id替换为您的AWS账号ID,queue-name替换为您的SQS队列名称。
import boto3
# 创建SNS客户端
sns_client = boto3.client('sns')
# 创建SQS客户端
sqs_client = boto3.client('sqs')
# 创建SNS主题
response = sns_client.create_topic(Name='my-topic')
topic_arn = response['TopicArn']
# 创建SQS队列
response = sqs_client.create_queue(QueueName='my-queue')
queue_url = response['QueueUrl']
# 创建IAM角色
iam_client = boto3.client('iam')
response = iam_client.create_role(
RoleName='sns-sqs-role',
AssumeRolePolicyDocument=json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
})
)
role_arn = response['Role']['Arn']
# 为角色附加策略
iam_client.attach_role_policy(
RoleName='sns-sqs-role',
PolicyArn='arn:aws:iam::aws:policy/service-role/AmazonSQSFullAccess'
)
# 将IAM角色授权给SNS主题
sns_client.set_topic_attributes(
TopicArn=topic_arn,
AttributeName='SQSQueuePolicy',
AttributeValue=json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "SQS:SendMessage",
"Resource": queue_url,
"Condition": {
"ArnEquals": {
"aws:SourceArn": topic_arn
}
}
}
]
})
)
# 创建SNS主题的SQS订阅
response = sns_client.subscribe(
TopicArn=topic_arn,
Protocol='sqs',
Endpoint=queue_url
)
print("订阅已创建")
在上面的代码中,我们首先创建了一个SNS主题和一个SQS队列。然后,我们创建了一个IAM角色,并将AmazonSQSFullAccess策略附加到该角色上。最后,我们将IAM角色授权给SNS主题,并创建了一个SQS订阅。
通过以上步骤,您可以为AWS SNS主题的AWS SQS订阅设置访问控制。