与 IoTDataPlane 一起使用 boto3 发布方法时出现 ForbiddenException 错误

0

【以下的问题经过翻译处理】 我正在尝试使用 boto3 IoTDataPlane 客户端的发布方法在 lambda 中发布到 IoT 主题。但是,当我调用 lambda 时,出现以下异常:

[错误] ClientError:调用发布操作时发生错误(ForbiddenException):无

我还向 lambda 添加了 AWS IoT 策略。

这是 lambda 的片段:

import boto3
import json
import logging

logger = logging.getLogger(__name__)
logger.setLevel("DEBUG")

iot_client = boto3.client('iot', region_name='us-east-1')
endpoint_response = iot_client.describe_endpoint(endpointType='iot:Data-ATS')
endpoint_url = f"https://{endpoint_response['endpointAddress']}"
logger.debug(endpoint_url)
client = boto3.client('iot-data', region_name='us-east-1', endpoint_url=endpoint_url)

def handler(event, context):
    topic = "test/topic"
    datum = json.dumps({"a": "b"})
    logger.debug(datum)

    response = client.publish(
        topic=topic,
        qos=0,
        payload=datum,
        retain=True
    )

    logger.debug(response)

这是与 lambda 相关的策略声明:

self._handler.add_to_role_policy(
    iam.PolicyStatement(
        actions=[
            "iot-data:Publish",
            "iot-data:Close",
            "iot-data:AttachPolicy",
            "iot-data:ListNamedShadowsForThing",
            "iot:DescribeEndpoint"
        ],
        resources=[
            "*"
        ],
    )
)

1 Antwort
0

【以下的回答经过翻译处理】 你可能认为有 iot-data 服务,但我可以看到没有。你可以将策略中所有的 iot-data 引用替换为 iot,然后你就能够发布内容了。顺便说一下,没有 iot:Close 操作。

另外(如果Lambda与你想要使用的IoT Core端点在同一个帐户和区域中),你不需要显式设置端点或区域,所以你可以将代码简化为类似以下的形式:

import boto3
import json
import logging

logger = logging.getLogger(__name__)
logger.setLevel("DEBUG")

client = boto3.client('iot-data')

def handler(event, context):
    topic = "test/topic"
    datum = json.dumps({"a": "b"})
    logger.debug(datum)

    response = client.publish(
        topic=topic,
        qos=0,
        payload=datum,
        retain=True
    )

    logger.debug(response)

然后你也可以从策略中删除 DescribeEndpoint 操作。目前,你没有使用 ListNamedShadowsForThingAttachPolicy 操作,因此这些也可以被删除(但你可能已经知道这一点)。

profile picture
EXPERTE
beantwortet vor 6 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen