YAML文件无效参数值错误

Invalid parameter value error of YAML file

我在 AWS 组织工作:目前正在 AWS 组织下创建如下 scp 策略:

Python 文件:

policies = config['policies']

for policy in policies:
 try:
   OUPolicy = client.create_policy(
      Description=policy['description'],
      Name= policy['Name'],
      Content=policy['content'],
      Type='SERVICE_CONTROL_POLICY'
    )

YAML 文件:

 policies:
 - Name: xyz
   description: Service Control Policies for xyz
   content:
     Version: 2012-10-17
     Statement:
     - Effect: Allow
       Resource: "*"
       Action: "*"
     - Effect: Deny
       Resource: "*"
       Action: "*

我验证了 YAML 模板,它的格式正确,但仍然出现如下错误:

Parameter validation failed:
Invalid type for parameter Content, value: {'Version': datetime.date(2012, 10, 17), 'Statement': [{'Effect': 'Allow', 'Resource': '*', 'Action': '*'}, {'Effect': 'Deny', 'Resource': '*', 'Action': '*'}]}, type: <class 'dict'>, valid types: <class 'str'>

根据您显示的 create_policy 的文档,

Content (string) -- [REQUIRED] The policy content to add to the new policy. For example, if you create a service control policy (SCP), this string must be JSON text that specifies the permissions that admins in attached accounts can delegate to their users, groups, and roles.

您需要将字典 policy['content'](您已从 YAML 文档解码)编码回 JSON 字符串。

您可以使用 json.dumps:

import json

...

client.create_policy(
  ...
  Content=json.dumps(policy['content']),
  ...
)

答案:

policies = config['policies']

for policy in policies:
 try:
   OUPolicy = client.create_policy(
      Description=policy['description'],
      Name= policy['Name'],
      Content=json.dumps(policy['content']),
      Type='SERVICE_CONTROL_POLICY'
    )