将 CreatePolicyVersion 与 Amazon SDK 或 CLI 配合使用 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

CreatePolicyVersion 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 CreatePolicyVersion

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

CLI
Amazon CLI

要创建新版本的托管策略

此示例创建了一个新的 v2 版本的 IAM policy,其 ARN 为 arn:aws:iam::123456789012:policy/MyPolicy,并设为默认版本。

aws iam create-policy-version \ --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \ --policy-document file://NewPolicyVersion.json \ --set-as-default

输出:

{ "PolicyVersion": { "CreateDate": "2015-06-16T18:56:03.721Z", "VersionId": "v2", "IsDefaultVersion": true } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的 IAM policy 版本控制

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 CreatePolicyVersion

PowerShell
适用于 PowerShell 的工具

示例 1:此示例创建了一个新“v2”版本的 IAM 策略,其 ARN 为 arn:aws:iam::123456789012:policy/MyPolicy,并设为默认版本。NewPolicyVersion.json 文件提供了策略内容。请注意,必须使用 -Raw 开关参数才能成功处理 JSON 策略文件。

New-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -PolicyDocument (Get-content -Raw NewPolicyVersion.json) -SetAsDefault $true

输出:

CreateDate Document IsDefaultVersion VersionId ---------- -------- ---------------- --------- 4/15/2015 10:54:54 AM True v2
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 CreatePolicyVersion

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

def create_policy_version(policy_arn, actions, resource_arn, set_as_default): """ Creates a policy version. Policies can have up to five versions. The default version is the one that is used for all resources that reference the policy. :param policy_arn: The ARN of the policy. :param actions: The actions to allow in the policy version. :param resource_arn: The ARN of the resource this policy version applies to. :param set_as_default: When True, this policy version is set as the default version for the policy. Otherwise, the default is not changed. :return: The newly created policy version. """ policy_doc = { "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}], } try: policy = iam.Policy(policy_arn) policy_version = policy.create_version( PolicyDocument=json.dumps(policy_doc), SetAsDefault=set_as_default ) logger.info( "Created policy version %s for policy %s.", policy_version.version_id, policy_version.arn, ) except ClientError: logger.exception("Couldn't create a policy version for %s.", policy_arn) raise else: return policy_version
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 CreatePolicyVersion

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。