python - AWS boto3 create_policy() - 指定policyDocument

标签 python amazon-web-services iot boto3 policy

我正在使用 python 的 boto3 库来连接 AWS IoT。我想使用 create_policy() API 创建策略但我不明白 policyDocument 字段使用什么。我认为这与policyStatement有关,但我无法弄清楚语法。这是我到目前为止所拥有的。

from __future__ import print_function
import os
import sys
import boto3
from botocore.exceptions import ClientError
from colorama import Fore, Back, Style
from colorama import init
init()

thingType = 'TpmStation'
thingBaseName = thingType + '-'
thingPolicy = thingType + '-Policy-GenDerivedKey'

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

try:
    # Use system hosted credentials - see
    # http://docs.aws.amazon.com/cli/latest/userguide/installing.html
    # http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
    client = boto3.client('iot')

    policyDocument = {}
    policyDocument['Statement'] = []
    policyDocument['Statement'].append({})
    policyDocument['Statement'][0]['Effect'] = 'Allow'
    policyDocument['Statement'][0]['Action'] = []
    policyDocument['Statement'][0]['Action'].append('iot:Connect')
    policyDocument['Statement'][0]['Action'].append('iot:Publish')
    policyDocument['Statement'][0]['Action'].append('iot:Subscribe')
    policyDocument['Statement'][0]['Action'].append('iot:Receive')
    policyDocument['Statement'][0]['Action'].append('iot:GetThingShadow')
    policyDocument['Statement'][0]['Action'].append('iot:UpdateThingShadow')
    policyDocument['Statement'][0]['Resource'] = '*'
    response = client.create_policy(
        policyName = thingPolicy,
        policyDocument = policyDocument
    )
    if 200 != response['ResponseMetadata']['HTTPStatusCode']:
        eprint(Fore.RED + "ERROR: Unable to 'create_thing_type' " + Style.RESET_ALL)
        sys.exit(1)
    print(Fore.GREEN + "Created new policy '" + thingPolicy + "'" +
            Style.RESET_ALL)

except ClientError as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    eprint(Fore.RED + "ERROR in " + fname + ':' + str(exc_tb.tb_lineno) + ' - ' + e.response['Error']['Code'] + ' - ' + e.response['Error']['Message'] + Style.RESET_ALL)
    sys.exit(1)

最佳答案

经过多次迭代,我发现以下是有效的

from __future__ import print_function
import os
import sys
import re
import boto3
from botocore.exceptions import ClientError
from colorama import Fore, Back, Style
from colorama import init
init()

thingType = 'TpmStation'
thingBaseName = thingType + '-'
thingPolicy = thingType + '-Policy-GenDerivedKey'

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

try:
    # Use system hosted credentials - see
    # http://docs.aws.amazon.com/cli/latest/userguide/installing.html
    # http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
    client = boto3.client('iot')

    awsAccount = boto3.client('sts').get_caller_identity().get('Account')
    awsRegion = boto3.session.Session().region_name
    policyDocumentStr = '''
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "iot:Publish"
                    ],
                    "Resource": ["arn:aws:iot:%s:%s:topic/Request"]
                },
                {
                    "Effect": "Allow",
                    "Action": [
                        "iot:Subscribe"
                    ],
                    "Resource": ["arn:aws:iot:%s:%s:topicfilter/Response"]
                },
                {
                    "Effect": "Allow",
                    "Action": [
                        "iot:Receive"
                    ],
                    "Resource": ["arn:aws:iot:%s:%s:topic/Response"]
                },
                {
                    "Effect": "Allow",
                    "Action": ["iot:Connect"],
                    "Resource": ["*"]
                }
            ]
        }
    '''%(awsRegion, awsAccount, awsRegion, awsAccount, awsRegion, awsAccount)
    pattern = re.compile(r'[\s\r\n]+')
    policyDocumentStr = re.sub(pattern, '', policyDocumentStr)

    response = client.create_policy(
        policyName = thingPolicy,
        policyDocument = policyDocumentStr
    )
    if 200 != response['ResponseMetadata']['HTTPStatusCode']:
        eprint(Fore.RED + "ERROR: Unable to 'create_thing_type' " + Style.RESET_ALL)
        sys.exit(1)
    print(Fore.GREEN + "Created new policy '" + thingPolicy + "'" +
            Style.RESET_ALL)

except ClientError as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    eprint(Fore.RED + "ERROR in " + fname + ':' + str(exc_tb.tb_lineno) + ' - ' + e.response['Error']['Code'] + ' - ' + e.response['Error']['Message'] + Style.RESET_ALL)
    sys.exit(1)

关于python - AWS boto3 create_policy() - 指定policyDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42928656/

相关文章:

Python regex\w 不匹配组合变音符号?

python - 如何从较大的数组创建一个新的较小的数组,并取旧数组元素的平均值?

java - 为什么我可以从 getClass().getResource() 获取有效的 url,但返回的 url 创建了一个不存在的文件

amazon-web-services - 如何检查 VPC 中两个资源之间的连接性/可达性?

amazon-web-services - Pyspark:如何检查s3中是否存在带有通配符的文件路径

javascript - 获取 CPU 温度作为 Node 红色中的数字

ios - 什么是 iOS Home App URL Scheme

python - 从 numpy 2D 数组中随机选择特定百分比的单元格

azure - 设备每 65 分钟重新连接到 Azure IoT 中心

python - 计算 x % y == 0 的出现次数