AttachPolicy 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

AttachPolicy 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 AttachPolicy

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

using System; using System.Threading.Tasks; using Amazon.Organizations; using Amazon.Organizations.Model; /// <summary> /// Shows how to attach an AWS Organizations policy to an organization, /// an organizational unit, or an account. /// </summary> public class AttachPolicy { /// <summary> /// Initializes the Organizations client object and then calls the /// AttachPolicyAsync method to attach the policy to the root /// organization. /// </summary> public static async Task Main() { IAmazonOrganizations client = new AmazonOrganizationsClient(); var policyId = "p-00000000"; var targetId = "r-0000"; var request = new AttachPolicyRequest { PolicyId = policyId, TargetId = targetId, }; var response = await client.AttachPolicyAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Successfully attached Policy ID {policyId} to Target ID: {targetId}."); } else { Console.WriteLine("Was not successful in attaching the policy."); } } }
  • 如需 API 詳細資訊,請參閱 AttachPolicy AWS SDK for .NET 參考中的 API

CLI
AWS CLI

將政策連接至根、OU 或帳戶

範例 1

下列範例示範如何將服務控制政策 (SCP) 連接至 OU:

aws organizations attach-policy --policy-id p-examplepolicyid111 --target-id ou-examplerootid111-exampleouid111

範例 2

下列範例示範如何將服務控制政策直接連接至 帳戶:

aws organizations attach-policy --policy-id p-examplepolicyid111 --target-id 333333333333
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 AttachPolicy

Python
SDK for Python (Boto3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

def attach_policy(policy_id, target_id, orgs_client): """ Attaches a policy to a target. The target is an organization root, account, or organizational unit. :param policy_id: The ID of the policy to attach. :param target_id: The ID of the resources to attach the policy to. :param orgs_client: The Boto3 Organizations client. """ try: orgs_client.attach_policy(PolicyId=policy_id, TargetId=target_id) logger.info("Attached policy %s to target %s.", policy_id, target_id) except ClientError: logger.exception( "Couldn't attach policy %s to target %s.", policy_id, target_id ) raise
  • 如需 API 詳細資訊,請參閱 AttachPolicy AWS SDK for Python (Boto3) Word 參考中的 API