I wrote Python script to create AWS IoT thing and policy. I attach policy to the IoT thing with the code as follows.
iot_client.attach_policy(policyName=policy_name, target=thing_arn)
I got the errors as follows:
create-iot-device.py", line 36, in iot_client.attach_policy(policyName=policy_name, target=thing_arn)
botocore.errorfactory.InvalidRequestException: An error occurred (InvalidRequestException) when calling the AttachPolicy operation: Invalid Target: arn:aws:iot:us-east-1:428999999999:thing/YourIoTThingName
The following is the related code.
import boto3
import os
from OpenSSL import crypto
# AWS IoT settings
iot_client = boto3.client('iot')
iot_thing_name = 'YourIoTThingName'
policy_name = 'YourPolicyName'
# Create IoT thing
response = iot_client.create_thing(thingName=iot_thing_name)
thing_arn = response['thingArn']
policy_document = '''
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:*",
"Resource": "*"
}
]
}
'''
# Remove leading spaces from policy_document
policy_document = policy_document.strip()
response = iot_client.create_policy(policyName=policy_name, policyDocument=str(policy_document))
# Attach policy to thing
iot_client.attach_policy(policyName=policy_name, target=thing_arn)
You cannot attach an IoT policy to a thing, you attach it to a certificate. The certificate is then attached to a thing.
You can find in the documentation how to do it: https://docs.aws.amazon.com/iot/latest/developerguide/attach-to-cert.html