【发布时间】:2021-05-13 01:11:54
【问题描述】:
我正在编写一个使用 python 函数创建 IAM 策略的 boto 脚本。该策略已使用“json.dumps()”转换为 JSON 格式,但 AWS 仍不会将其视为有效格式。 功能是:
##### Global variables ####
region="us-east-2"
instance_type="t2.micro"
ebs_volume_size="20"
meta_template_name="ec2_policy_meta_template"
###############################
start_time_1 = input("What's the start time")
end_time1 = input("What's the end time")
def create_aws_iam_policy_template(**kwargs):
template_data = {}
template_data["region"] = kwargs.get('region')
template_data["start_time"] = kwargs.get('end_time')
template_data["end_time"] = kwargs.get('start_time')
template_data["instance_type"] = kwargs.get('instance_type')
template_data["ebs_volume_size"] = kwargs.get('ebs_volume_size')
template_data["meta_template_name"] = kwargs.get('meta_template_name')
meta_template_dict = getattr(meta_templates, template_data["meta_template_name"])
meta_template_json = json.dumps(meta_template_dict)
template_json = Template(meta_template_json).render(template_data)
return template_json
template_json = create_aws_iam_policy_template(
region=region,
instance_type=instance_type,
ebs_volume_size=ebs_volume_size,
meta_template_name=meta_template_name,
start_time = start_time_1,
end_time = end_time1
)
这是我用来将 dict 转换为 JSON 的方法:
app_json = json.dumps(template_json)
print(app_json)
这是 IAM 政策的输出:
"{"Version": "2012-10-17", "Statement": [{"Sid": "VisualEditor0", "Effect": "Allow", "Action": "ec2:RunInstances", "资源": ["arn:aws:ec2:us-east-2::instance/", "arn:aws:ec2:us-east-2::network-interface/", " arn:aws:ec2:us-east-2::key-pair/", "arn:aws:ec2:us-east-2::security-group/", "arn:aws :ec2:us-east-2::subnet/", "arn:aws:ec2:us-east-2::volume/", "arn:aws:ec2:us-east- 2::image/ami-"], "条件": {"ForAllValues:NumericLessThanEquals": {"ec2:VolumeSize": "20"}, "ForAllValues:StringEquals": {"ec2:InstanceType": " t2.micro"}}}, {"Sid": "VisualEditor1", "Effect": "Allow", "Action": ["ec2:TerminateInstances", "ec2:StartInstances", "ec2:StopInstances"], "资源”:“arn:aws:ec2:us-east-2::instance/”,“条件”:{“ForAllValues:StringEquals”:{“ec2:InstanceType”:“t2.micro”}} }、{“Sid”:“VisualEditor2”、“效果”:“允许”、“操作”:[“ec2:Describe*”、“ec2:GetConsole*”、“cloudwatch:DescribeAlarms”、“iam:ListInstanceProfiles”、 “云观察:GetMetricStat istics”、“ec2:DescribeKeyPairs”、“ec2:CreateKeyPair”]、“资源”:“*”、“条件”:{“DateGreaterThan”:{“aws:CurrentTime”:“2020-06-30T23:59:59Z "}, "DateLessThanEquals": {"aws:CurrentTime": "2020-04-01T00:00:00Z"}}}]}" 这是我在尝试创建 IAM 策略时遇到的错误:
botocore.errorfactory.MalformedPolicyDocumentException: An error occurred (MalformedPolicyDocument) when calling the CreatePolicy operation: Syntax errors in policy.
【问题讨论】:
-
能否提供更完整的示例代码?您在哪里以及如何生成
template_json并调用CreatePolicy? -
我已对问题进行了更改。请检查一下。
标签: python json amazon-web-services boto3 amazon-iam