

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 组织使用的代码示例 AWS SDKs
<a name="organizations_code_examples"></a>

以下代码示例向您展示了如何 AWS Organizations 使用 AWS 软件开发套件 (SDK)。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

*场景*是向您展示如何通过在一个服务中调用多个函数或与其他 AWS 服务服务结合来完成特定任务的代码示例。

**更多资源**
+  **[Organizations 用户指南](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)**——有关 Organizations 的更多信息。
+ **[Organizations API 参考](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)**——有关所有可用的 Organizations 操作的详细信息。
+ **[AWS 开发者中心](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23organizations)** — 您可以按类别或全文搜索筛选的代码示例。
+ **[AWS SDK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 包含首选语言完整代码的 GitHub 存储库。包括有关设置和运行代码的说明。

**Contents**
+ [基本功能](organizations_code_examples_basics.md)
  + [操作](organizations_code_examples_actions.md)
    + [`AttachPolicy`](organizations_example_organizations_AttachPolicy_section.md)
    + [`CreateAccount`](organizations_example_organizations_CreateAccount_section.md)
    + [`CreateOrganization`](organizations_example_organizations_CreateOrganization_section.md)
    + [`CreateOrganizationalUnit`](organizations_example_organizations_CreateOrganizationalUnit_section.md)
    + [`CreatePolicy`](organizations_example_organizations_CreatePolicy_section.md)
    + [`DeleteOrganization`](organizations_example_organizations_DeleteOrganization_section.md)
    + [`DeleteOrganizationalUnit`](organizations_example_organizations_DeleteOrganizationalUnit_section.md)
    + [`DeletePolicy`](organizations_example_organizations_DeletePolicy_section.md)
    + [`DescribePolicy`](organizations_example_organizations_DescribePolicy_section.md)
    + [`DetachPolicy`](organizations_example_organizations_DetachPolicy_section.md)
    + [`ListAccounts`](organizations_example_organizations_ListAccounts_section.md)
    + [`ListOrganizationalUnitsForParent`](organizations_example_organizations_ListOrganizationalUnitsForParent_section.md)
    + [`ListPolicies`](organizations_example_organizations_ListPolicies_section.md)
+ [场景](organizations_code_examples_scenarios.md)
  + [权限策略允许 AWS Compute Optimizer Automation 应用建议的操作](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.managed-policies.xml.10_section.md)
  + [在整个组织中启用自动化功能的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.2_section.md)
  + [启用账户自动化功能的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.1_section.md)
  + [向组织管理账户授予对 Compute Optimizer 自动化功能完全访问权限的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.5_section.md)
  + [向独立账户授予对 Compute Optimizer Automizer 自动化的完全访问权限的权限策略 AWS](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.3_section.md)
  + [向组织管理账户授予对 Compute Optimizer 自动化功能只读访问权限的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.6_section.md)
  + [向独立账户授予 Compute Optimizer Automizer Automizer 只读权限的权限策略 AWS](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.4_section.md)
  + [授予计算优化自动化功能的服务相关角色权限的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.slr-automation.xml.1_section.md)

# Organizations 的基本示例 AWS SDKs
<a name="organizations_code_examples_basics"></a>

以下代码示例说明如何使用 with 的基础 AWS Organizations 知识 AWS SDKs。

**Contents**
+ [操作](organizations_code_examples_actions.md)
  + [`AttachPolicy`](organizations_example_organizations_AttachPolicy_section.md)
  + [`CreateAccount`](organizations_example_organizations_CreateAccount_section.md)
  + [`CreateOrganization`](organizations_example_organizations_CreateOrganization_section.md)
  + [`CreateOrganizationalUnit`](organizations_example_organizations_CreateOrganizationalUnit_section.md)
  + [`CreatePolicy`](organizations_example_organizations_CreatePolicy_section.md)
  + [`DeleteOrganization`](organizations_example_organizations_DeleteOrganization_section.md)
  + [`DeleteOrganizationalUnit`](organizations_example_organizations_DeleteOrganizationalUnit_section.md)
  + [`DeletePolicy`](organizations_example_organizations_DeletePolicy_section.md)
  + [`DescribePolicy`](organizations_example_organizations_DescribePolicy_section.md)
  + [`DetachPolicy`](organizations_example_organizations_DetachPolicy_section.md)
  + [`ListAccounts`](organizations_example_organizations_ListAccounts_section.md)
  + [`ListOrganizationalUnitsForParent`](organizations_example_organizations_ListOrganizationalUnitsForParent_section.md)
  + [`ListPolicies`](organizations_example_organizations_ListPolicies_section.md)

# 使用 Organizations AWS SDKs
<a name="organizations_code_examples_actions"></a>

以下代码示例演示了如何使用执行各个 Organizations 操作 AWS SDKs。每个示例都包含一个指向的链接 GitHub，您可以在其中找到有关设置和运行代码的说明。

这些代码节选调用了 Organizations API，是必须在上下文中运行的大型程序的代码节选。您可以在[组织使用场景 AWS SDKs](organizations_code_examples_scenarios.md)中结合上下文查看操作。

 以下示例仅包括最常用的操作。有关完整列表，请参阅 [AWS Organizations API 参考](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)。

**Topics**
+ [`AttachPolicy`](organizations_example_organizations_AttachPolicy_section.md)
+ [`CreateAccount`](organizations_example_organizations_CreateAccount_section.md)
+ [`CreateOrganization`](organizations_example_organizations_CreateOrganization_section.md)
+ [`CreateOrganizationalUnit`](organizations_example_organizations_CreateOrganizationalUnit_section.md)
+ [`CreatePolicy`](organizations_example_organizations_CreatePolicy_section.md)
+ [`DeleteOrganization`](organizations_example_organizations_DeleteOrganization_section.md)
+ [`DeleteOrganizationalUnit`](organizations_example_organizations_DeleteOrganizationalUnit_section.md)
+ [`DeletePolicy`](organizations_example_organizations_DeletePolicy_section.md)
+ [`DescribePolicy`](organizations_example_organizations_DescribePolicy_section.md)
+ [`DetachPolicy`](organizations_example_organizations_DetachPolicy_section.md)
+ [`ListAccounts`](organizations_example_organizations_ListAccounts_section.md)
+ [`ListOrganizationalUnitsForParent`](organizations_example_organizations_ListOrganizationalUnitsForParent_section.md)
+ [`ListPolicies`](organizations_example_organizations_ListPolicies_section.md)

# `AttachPolicy`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_AttachPolicy_section"></a>

以下代码示例演示如何使用 `AttachPolicy`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    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 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[AttachPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/AttachPolicy)*中的。

------
#### [ 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](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/attach-policy.html)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/AttachPolicy)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        lo_org->attachpolicy(
          iv_policyid = iv_policy_id
          iv_targetid = iv_target_id ).
        MESSAGE 'Policy attached to target.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to attach the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgtargetnotfoundex.
        MESSAGE 'The specified target does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgduplicateplyatta00.
        MESSAGE 'The policy is already attached to the target.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[AttachPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# `CreateAccount`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_CreateAccount_section"></a>

以下代码示例演示如何使用 `CreateAccount`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates a new AWS Organizations account.
    /// </summary>
    public class CreateAccount
    {
        /// <summary>
        /// Initializes an Organizations client object and uses it to create
        /// the new account with the name specified in accountName.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();
            var accountName = "ExampleAccount";
            var email = "someone@example.com";

            var request = new CreateAccountRequest
            {
                AccountName = accountName,
                Email = email,
            };

            var response = await client.CreateAccountAsync(request);
            var status = response.CreateAccountStatus;

            Console.WriteLine($"The staus of {status.AccountName} is {status.State}.");
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateAccount](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreateAccount)*中的。

------
#### [ CLI ]

**AWS CLI**  
**创建自动属于组织的成员账户**  
以下示例演示如何创建组织的成员账户。为成员账户配置的名称为 Production Account，电子邮件地址为 susan@example.com。 OrganizationAccountAccessRole 由于未指定 roleName 参数，Organizations 会使用默认名称自动创建 IAM 角色。此外，由于未指定 IamUserAccessToBilling 参数，允许具有足够权限的 IAM 用户或角色访问账户账单数据的设置被设置为默认值 ALLOW。Organiations 会自动向 Susan 发送一封 “欢迎来到 AWS” 电子邮件：  

```
aws organizations create-account --email susan@example.com --account-name "Production Account"
```
输出包括一个请求对象，以显示状态目前为 `IN_PROGRESS`：  

```
{
        "CreateAccountStatus": {
                "State": "IN_PROGRESS",
                "Id": "car-examplecreateaccountrequestid111"
        }
}
```
稍后，您可以通过向 describe-create-account-status命令提供 Id 响应值作为 create-account-request-id参数值来查询请求的当前状态。  
有关更多信息，请参阅《Organi AWS zations *用户指南》中的在AWS 组织*中创建帐户。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-account.html)*中的。

------

# `CreateOrganization`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_CreateOrganization_section"></a>

以下代码示例演示如何使用 `CreateOrganization`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates an organization in AWS Organizations.
    /// </summary>
    public class CreateOrganization
    {
        /// <summary>
        /// Creates an Organizations client object and then uses it to create
        /// a new organization with the default user as the administrator, and
        /// then displays information about the new organization.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var response = await client.CreateOrganizationAsync(new CreateOrganizationRequest
            {
                FeatureSet = "ALL",
            });

            Organization newOrg = response.Organization;

            Console.WriteLine($"Organization: {newOrg.Id} Main Accoount: {newOrg.MasterAccountId}");
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateOrganization](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreateOrganization)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：创建新组织**  
Bill 想使用账户 111111111111 中的凭证创建一个组织。以下示例显示该账户成为新组织中的主账户。由于他没有指定功能集，因此，新组织默认为在根上启用所有功能并启用服务控制策略。  

```
aws organizations create-organization
```
输出包括一个组织对象，其中包含有关新组织的详细信息：  

```
{
        "Organization": {
                "AvailablePolicyTypes": [
                        {
                                "Status": "ENABLED",
                                "Type": "SERVICE_CONTROL_POLICY"
                        }
                ],
                "MasterAccountId": "111111111111",
                "MasterAccountArn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                "MasterAccountEmail": "bill@example.com",
                "FeatureSet": "ALL",
                "Id": "o-exampleorgid",
                "Arn": "arn:aws:organizations::111111111111:organization/o-exampleorgid"
        }
}
```
**示例 2：创建仅启用整合账单功能的新组织**  
以下示例创建仅支持整合账单功能的组织：  

```
aws organizations create-organization --feature-set CONSOLIDATED_BILLING
```
输出包括一个组织对象，其中包含有关新组织的详细信息：  

```
{
        "Organization": {
                "Arn": "arn:aws:organizations::111111111111:organization/o-exampleorgid",
                "AvailablePolicyTypes": [],
                "Id": "o-exampleorgid",
                "MasterAccountArn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                "MasterAccountEmail": "bill@example.com",
                "MasterAccountId": "111111111111",
                "FeatureSet": "CONSOLIDATED_BILLING"
        }
}
```
有关更多信息，请参阅《AWS Organizations 用户指南》**中的“创建组织”。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-organization.html)*中的。

------

# `CreateOrganizationalUnit`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_CreateOrganizationalUnit_section"></a>

以下代码示例演示如何使用 `CreateOrganizationalUnit`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates a new organizational unit in AWS Organizations.
    /// </summary>
    public class CreateOrganizationalUnit
    {
        /// <summary>
        /// Initializes an Organizations client object and then uses it to call
        /// the CreateOrganizationalUnit method. If the call succeeds, it
        /// displays information about the new organizational unit.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var orgUnitName = "ProductDevelopmentUnit";

            var request = new CreateOrganizationalUnitRequest
            {
                Name = orgUnitName,
                ParentId = "r-0000",
            };

            var response = await client.CreateOrganizationalUnitAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully created organizational unit: {orgUnitName}.");
                Console.WriteLine($"Organizational unit {orgUnitName} Details");
                Console.WriteLine($"ARN: {response.OrganizationalUnit.Arn} Id: {response.OrganizationalUnit.Id}");
            }
            else
            {
                Console.WriteLine("Could not create new organizational unit.");
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateOrganizationalUnit](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreateOrganizationalUnit)*中的。

------
#### [ CLI ]

**AWS CLI**  
**在根 OU 或父 OU 中创建 OU**  
以下示例演示如何创建名为 AccountingOU 的 OU：  

```
aws organizations create-organizational-unit --parent-id r-examplerootid111 --name AccountingOU
```
输出包括一个 organizationalUnit 对象，其中包含有关新 OU 的详细信息：  

```
{
        "OrganizationalUnit": {
                "Id": "ou-examplerootid111-exampleouid111",
                "Arn": "arn:aws:organizations::111111111111:ou/o-exampleorgid/ou-examplerootid111-exampleouid111",
                "Name": "AccountingOU"
        }
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateOrganizationalUnit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-organizational-unit.html)*中的。

------

# `CreatePolicy`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_CreatePolicy_section"></a>

以下代码示例演示如何使用 `CreatePolicy`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates a new AWS Organizations Policy.
    /// </summary>
    public class CreatePolicy
    {
        /// <summary>
        /// Initializes the AWS Organizations client object, uses it to
        /// create a new Organizations Policy, and then displays information
        /// about the newly created Policy.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();
            var policyContent = "{" +
                "   \"Version\": \"2012-10-17\"," +
                "	\"Statement\" : [{" +
                    "	\"Action\" : [\"s3:*\"]," +
                    "	\"Effect\" : \"Allow\"," +
                    "	\"Resource\" : \"*\"" +
                "}]" +
            "}";

            try
            {
                var response = await client.CreatePolicyAsync(new CreatePolicyRequest
                {
                    Content = policyContent,
                    Description = "Enables admins of attached accounts to delegate all Amazon S3 permissions",
                    Name = "AllowAllS3Actions",
                    Type = "SERVICE_CONTROL_POLICY",
                });

                Policy policy = response.Policy;
                Console.WriteLine($"{policy.PolicySummary.Name} has the following content: {policy.Content}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreatePolicy)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：使用 JSON 策略的文本源文件创建策略**  
以下示例演示如何创建名为 `AllowAllS3Actions` 的服务控制策略（SCP）。策略内容取自本地计算机上名为 `policy.json` 的文件。  

```
aws organizations create-policy --content file://policy.json --name AllowAllS3Actions, --type SERVICE_CONTROL_POLICY --description "Allows delegation of all S3 actions"
```
输出包括一个策略对象，其中包含有关新策略的详细信息：  

```
{
        "Policy": {
                "Content": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}",
                "PolicySummary": {
                        "Arn": "arn:aws:organizations::o-exampleorgid:policy/service_control_policy/p-examplepolicyid111",
                        "Description": "Allows delegation of all S3 actions",
                        "Name": "AllowAllS3Actions",
                        "Type":"SERVICE_CONTROL_POLICY"
                }
        }
}
```
**示例 2：创建以 JSON 策略作为参数的策略**  
以下示例演示了如何创建相同的 SCP，这次是将策略内容作为 JSON 字符串嵌入到参数中。字符串必须在双引号前使用反斜杠进行转义，以确保在参数中将其视为文本，参数本身用双引号引起来：  

```
aws organizations create-policy --content "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}" --name AllowAllS3Actions --type SERVICE_CONTROL_POLICY --description "Allows delegation of all S3 actions"
```
有关在组织中创建和使用策略的更多信息，请参阅《AWS Organizations 用户指南》**中的“管理组织策略”。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-policy.html)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
def create_policy(name, description, content, policy_type, orgs_client):
    """
    Creates a policy.

    :param name: The name of the policy.
    :param description: The description of the policy.
    :param content: The policy content as a dict. This is converted to JSON before
                    it is sent to AWS. The specific format depends on the policy type.
    :param policy_type: The type of the policy.
    :param orgs_client: The Boto3 Organizations client.
    :return: The newly created policy.
    """
    try:
        response = orgs_client.create_policy(
            Name=name,
            Description=description,
            Content=json.dumps(content),
            Type=policy_type,
        )
        policy = response["Policy"]
        logger.info("Created policy %s.", name)
    except ClientError:
        logger.exception("Couldn't create policy %s.", name)
        raise
    else:
        return policy
```
+  有关 API 的详细信息，请参阅适用[CreatePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/CreatePolicy)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_org->createpolicy(       " oo_result is returned for testing purposes. "
          iv_name        = iv_policy_name
          iv_description = iv_policy_description
          iv_content     = iv_policy_content
          iv_type        = iv_policy_type ).
        MESSAGE 'Policy created.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to create a policy.' TYPE 'E'.
      CATCH /aws1/cx_orgduplicatepolicyex.
        MESSAGE 'A policy with this name already exists.' TYPE 'E'.
      CATCH /aws1/cx_orgmalformedplydocex.
        MESSAGE 'The policy content is malformed.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[CreatePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# `DeleteOrganization`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_DeleteOrganization_section"></a>

以下代码示例演示如何使用 `DeleteOrganization`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to delete an existing organization using the AWS
    /// Organizations Service.
    /// </summary>
    public class DeleteOrganization
    {
        /// <summary>
        /// Initializes the Organizations client and then calls
        /// DeleteOrganizationAsync to delete the organization.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var response = await client.DeleteOrganizationAsync(new DeleteOrganizationRequest());

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Successfully deleted organization.");
            }
            else
            {
                Console.WriteLine("Could not delete organization.");
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DeleteOrganization](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DeleteOrganization)*中的。

------
#### [ CLI ]

**AWS CLI**  
**删除组织**  
以下示例演示如何删除组织。要执行此操作，您必须是组织中主账户的管理员。该示例假设您之前已从组织中删除了所有成员账户和政策： OUs  

```
aws organizations delete-organization
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/delete-organization.html)*中的。

------

# `DeleteOrganizationalUnit`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_DeleteOrganizationalUnit_section"></a>

以下代码示例演示如何使用 `DeleteOrganizationalUnit`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to delete an existing AWS Organizations organizational unit.
    /// </summary>
    public class DeleteOrganizationalUnit
    {
        /// <summary>
        /// Initializes the Organizations client object and calls
        /// DeleteOrganizationalUnitAsync to delete the organizational unit
        /// with the selected ID.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var orgUnitId = "ou-0000-00000000";

            var request = new DeleteOrganizationalUnitRequest
            {
                OrganizationalUnitId = orgUnitId,
            };

            var response = await client.DeleteOrganizationalUnitAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully deleted the organizational unit with ID: {orgUnitId}.");
            }
            else
            {
                Console.WriteLine($"Could not delete the organizational unit with ID: {orgUnitId}.");
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DeleteOrganizationalUnit](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DeleteOrganizationalUnit)*中的。

------
#### [ CLI ]

**AWS CLI**  
**删除 OU**  
以下示例说明如何删除 OU。该示例假设您之前已 OUs 从 OU 中删除了所有账户和其他账户：  

```
aws organizations delete-organizational-unit --organizational-unit-id ou-examplerootid111-exampleouid111
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteOrganizationalUnit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/delete-organizational-unit.html)*中的。

------

# `DeletePolicy`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_DeletePolicy_section"></a>

以下代码示例演示如何使用 `DeletePolicy`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Deletes an existing AWS Organizations policy.
    /// </summary>
    public class DeletePolicy
    {
        /// <summary>
        /// Initializes the Organizations client object and then uses it to
        /// delete the policy with the specified policyId.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var policyId = "p-00000000";

            var request = new DeletePolicyRequest
            {
                PolicyId = policyId,
            };

            var response = await client.DeletePolicyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully deleted Policy: {policyId}.");
            }
            else
            {
                Console.WriteLine($"Could not delete Policy: {policyId}.");
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DeletePolicy)*中的。

------
#### [ CLI ]

**AWS CLI**  
**删除策略**  
以下示例演示如何删除组织的策略。该示例假设您之前已将策略与所有实体分离：  

```
aws organizations delete-policy --policy-id p-examplepolicyid111
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/delete-policy.html)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
def delete_policy(policy_id, orgs_client):
    """
    Deletes a policy.

    :param policy_id: The ID of the policy to delete.
    :param orgs_client: The Boto3 Organizations client.
    """
    try:
        orgs_client.delete_policy(PolicyId=policy_id)
        logger.info("Deleted policy %s.", policy_id)
    except ClientError:
        logger.exception("Couldn't delete policy %s.", policy_id)
        raise
```
+  有关 API 的详细信息，请参阅适用[DeletePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DeletePolicy)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        lo_org->deletepolicy(
          iv_policyid = iv_policy_id ).
        MESSAGE 'Policy deleted.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to delete the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicyinuseex.
        MESSAGE 'The policy is still attached to one or more targets.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DeletePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# `DescribePolicy`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_DescribePolicy_section"></a>

以下代码示例演示如何使用 `DescribePolicy`。

------
#### [ CLI ]

**AWS CLI**  
**获取有关策略的信息**  
以下示例演示如何请求有关策略的信息：  

```
aws organizations describe-policy --policy-id p-examplepolicyid111
```
输出包括一个策略对象，其中包含有关策略的详细信息：  

```
{
        "Policy": {
                "Content": "{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Action\": \"*\",\n      \"Resource\": \"*\"\n    }\n  ]\n}",
                "PolicySummary": {
                        "Arn": "arn:aws:organizations::111111111111:policy/o-exampleorgid/service_control_policy/p-examplepolicyid111",
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Id": "p-examplepolicyid111",
                        "AwsManaged": false,
                        "Name": "AllowAllS3Actions",
                        "Description": "Enables admins to delegate S3 permissions"
                }
        }
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-policy.html)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
def describe_policy(policy_id, orgs_client):
    """
    Describes a policy.

    :param policy_id: The ID of the policy to describe.
    :param orgs_client: The Boto3 Organizations client.
    :return: The description of the policy.
    """
    try:
        response = orgs_client.describe_policy(PolicyId=policy_id)
        policy = response["Policy"]
        logger.info("Got policy %s.", policy_id)
    except ClientError:
        logger.exception("Couldn't get policy %s.", policy_id)
        raise
    else:
        return policy
```
+  有关 API 的详细信息，请参阅适用[DescribePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DescribePolicy)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_org->describepolicy(     " oo_result is returned for testing purposes. "
          iv_policyid = iv_policy_id ).
        DATA(lo_policy) = oo_result->get_policy( ).
        MESSAGE 'Retrieved policy details.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to describe the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DescribePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# `DetachPolicy`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_DetachPolicy_section"></a>

以下代码示例演示如何使用 `DetachPolicy`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to detach a policy from an AWS Organizations organization,
    /// organizational unit, or account.
    /// </summary>
    public class DetachPolicy
    {
        /// <summary>
        /// Initializes the Organizations client object and uses it to call
        /// DetachPolicyAsync to detach the policy.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var policyId = "p-00000000";
            var targetId = "r-0000";

            var request = new DetachPolicyRequest
            {
                PolicyId = policyId,
                TargetId = targetId,
            };

            var response = await client.DetachPolicyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully detached policy with Policy Id: {policyId}.");
            }
            else
            {
                Console.WriteLine("Could not detach the policy.");
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DetachPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DetachPolicy)*中的。

------
#### [ CLI ]

**AWS CLI**  
**从根、OU 或账户分离策略**  
以下示例演示了如何从 OU 分离策略：  

```
aws organizations  detach-policy  --target-id ou-examplerootid111-exampleouid111 --policy-id p-examplepolicyid111
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DetachPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/detach-policy.html)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
def detach_policy(policy_id, target_id, orgs_client):
    """
    Detaches a policy from a target.

    :param policy_id: The ID of the policy to detach.
    :param target_id: The ID of the resource where the policy is currently attached.
    :param orgs_client: The Boto3 Organizations client.
    """
    try:
        orgs_client.detach_policy(PolicyId=policy_id, TargetId=target_id)
        logger.info("Detached policy %s from target %s.", policy_id, target_id)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from target %s.", policy_id, target_id
        )
        raise
```
+  有关 API 的详细信息，请参阅适用[DetachPolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DetachPolicy)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        lo_org->detachpolicy(
          iv_policyid = iv_policy_id
          iv_targetid = iv_target_id ).
        MESSAGE 'Policy detached from target.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to detach the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgtargetnotfoundex.
        MESSAGE 'The specified target does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotattex.
        MESSAGE 'The policy is not attached to the target.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DetachPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# `ListAccounts`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_ListAccounts_section"></a>

以下代码示例演示如何使用 `ListAccounts`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Uses the AWS Organizations service to list the accounts associated
    /// with the default account.
    /// </summary>
    public class ListAccounts
    {
        /// <summary>
        /// Creates the Organizations client and then calls its
        /// ListAccountsAsync method.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var request = new ListAccountsRequest
            {
                MaxResults = 5,
            };

            var response = new ListAccountsResponse();
            try
            {
                do
                {
                    response = await client.ListAccountsAsync(request);
                    response.Accounts.ForEach(a => DisplayAccounts(a));
                    if (response.NextToken is not null)
                    {
                        request.NextToken = response.NextToken;
                    }
                }
                while (response.NextToken is not null);
            }
            catch (AWSOrganizationsNotInUseException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Displays information about an Organizations account.
        /// </summary>
        /// <param name="account">An Organizations account for which to display
        /// information on the console.</param>
        private static void DisplayAccounts(Account account)
        {
            string accountInfo = $"{account.Id} {account.Name}\t{account.Status}";

            Console.WriteLine(accountInfo);
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[ListAccounts](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListAccounts)*中的。

------
#### [ CLI ]

**AWS CLI**  
**检索组织中所有账户的列表**  
以下示例演示了如何请求组织中的账户列表：  

```
aws organizations list-accounts
```
输出包含账户摘要对象的列表。  

```
{
        "Accounts": [
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481830215.45,
                        "Id": "111111111111",
                        "Name": "Master Account",
                        "Email": "bill@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/222222222222",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835741.044,
                        "Id": "222222222222",
                        "Name": "Production Account",
                        "Email": "alice@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/333333333333",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835795.536,
                        "Id": "333333333333",
                        "Name": "Development Account",
                        "Email": "juan@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/444444444444",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835812.143,
                        "Id": "444444444444",
                        "Name": "Test Account",
                        "Email": "anika@example.com",
                        "Status": "ACTIVE"
                }
        ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ListAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-accounts.html)*中的。

------

# `ListOrganizationalUnitsForParent`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_ListOrganizationalUnitsForParent_section"></a>

以下代码示例演示如何使用 `ListOrganizationalUnitsForParent`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Lists the AWS Organizations organizational units that belong to an
    /// organization.
    /// </summary>
    public class ListOrganizationalUnitsForParent
    {
        /// <summary>
        /// Initializes the Organizations client object and then uses it to
        /// call the ListOrganizationalUnitsForParentAsync method to retrieve
        /// the list of organizational units.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var parentId = "r-0000";

            var request = new ListOrganizationalUnitsForParentRequest
            {
                ParentId = parentId,
                MaxResults = 5,
            };

            var response = new ListOrganizationalUnitsForParentResponse();
            try
            {
                do
                {
                    response = await client.ListOrganizationalUnitsForParentAsync(request);
                    response.OrganizationalUnits.ForEach(u => DisplayOrganizationalUnit(u));
                    if (response.NextToken is not null)
                    {
                        request.NextToken = response.NextToken;
                    }
                }
                while (response.NextToken is not null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Displays information about an Organizations organizational unit.
        /// </summary>
        /// <param name="unit">The OrganizationalUnit for which to display
        /// information.</param>
        public static void DisplayOrganizationalUnit(OrganizationalUnit unit)
        {
            string accountInfo = $"{unit.Id} {unit.Name}\t{unit.Arn}";

            Console.WriteLine(accountInfo);
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[ListOrganizationalUnitsForParent](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListOrganizationalUnitsForParent)*中的。

------
#### [ CLI ]

**AWS CLI**  
**检索父 OU 或根目录 OUs 中的列表**  
以下示例说明如何获取指定根目录 OUs 中的列表：  

```
aws organizations list-organizational-units-for-parent --parent-id r-examplerootid111
```
输出显示指定的根包含两个， OUs 并显示每个根的详细信息：  

```
{
        "OrganizationalUnits": [
                {
                        "Name": "AccountingDepartment",
                        "Arn": "arn:aws:organizations::o-exampleorgid:ou/r-examplerootid111/ou-examplerootid111-exampleouid111"
                },
                {
                        "Name": "ProductionDepartment",
                        "Arn": "arn:aws:organizations::o-exampleorgid:ou/r-examplerootid111/ou-examplerootid111-exampleouid222"
                }
        ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ListOrganizationalUnitsForParent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-organizational-units-for-parent.html)*中的。

------

# `ListPolicies`与 AWS SDK 或 CLI 配合使用
<a name="organizations_example_organizations_ListPolicies_section"></a>

以下代码示例演示如何使用 `ListPolicies`。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to list the AWS Organizations policies associated with an
    /// organization.
    /// </summary>
    public class ListPolicies
    {
        /// <summary>
        /// Initializes an Organizations client object, and then calls its
        /// ListPoliciesAsync method.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            // The value for the Filter parameter is required and must must be
            // one of the following:
            //     AISERVICES_OPT_OUT_POLICY
            //     BACKUP_POLICY
            //     SERVICE_CONTROL_POLICY
            //     TAG_POLICY
            var request = new ListPoliciesRequest
            {
                Filter = "SERVICE_CONTROL_POLICY",
                MaxResults = 5,
            };

            var response = new ListPoliciesResponse();
            try
            {
                do
                {
                    response = await client.ListPoliciesAsync(request);
                    response.Policies.ForEach(p => DisplayPolicies(p));
                    if (response.NextToken is not null)
                    {
                        request.NextToken = response.NextToken;
                    }
                }
                while (response.NextToken is not null);
            }
            catch (AWSOrganizationsNotInUseException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Displays information about the Organizations policies associated
        /// with an organization.
        /// </summary>
        /// <param name="policy">An Organizations policy summary to display
        /// information on the console.</param>
        private static void DisplayPolicies(PolicySummary policy)
        {
            string policyInfo = $"{policy.Id} {policy.Name}\t{policy.Description}";

            Console.WriteLine(policyInfo);
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListPolicies)*中的。

------
#### [ CLI ]

**AWS CLI**  
**检索特定类型组织中所有策略的列表**  
以下示例向您展示了如何获取 filter 参数所指定的列表： SCPs  

```
aws organizations list-policies --filter SERVICE_CONTROL_POLICY
```
输出包括含摘要信息的策略列表：  

```
{
        "Policies": [
                {
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Name": "AllowAllS3Actions",
                        "AwsManaged": false,
                        "Id": "p-examplepolicyid111",
                        "Arn": "arn:aws:organizations::111111111111:policy/service_control_policy/p-examplepolicyid111",
                        "Description": "Enables account admins to delegate permissions for any S3 actions to users and roles in their accounts."
                },
                {
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Name": "AllowAllEC2Actions",
                        "AwsManaged": false,
                        "Id": "p-examplepolicyid222",
                        "Arn": "arn:aws:organizations::111111111111:policy/service_control_policy/p-examplepolicyid222",
                        "Description": "Enables account admins to delegate permissions for any EC2 actions to users and roles in their accounts."
                },
                {
                        "AwsManaged": true,
                        "Description": "Allows access to every operation",
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Id": "p-FullAWSAccess",
                        "Arn": "arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess",
                        "Name": "FullAWSAccess"
                }
        ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-policies.html)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)中查找完整示例，了解如何进行设置和运行。

```
def list_policies(policy_filter, orgs_client):
    """
    Lists the policies for the account, limited to the specified filter.

    :param policy_filter: The kind of policies to return.
    :param orgs_client: The Boto3 Organizations client.
    :return: The list of policies found.
    """
    try:
        response = orgs_client.list_policies(Filter=policy_filter)
        policies = response["Policies"]
        logger.info("Found %s %s policies.", len(policies), policy_filter)
    except ClientError:
        logger.exception("Couldn't get %s policies.", policy_filter)
        raise
    else:
        return policies
```
+  有关 API 的详细信息，请参阅适用[ListPolicies](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/ListPolicies)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_org->listpolicies(       " oo_result is returned for testing purposes. "
          iv_filter = iv_filter ).
        DATA(lt_policies) = oo_result->get_policies( ).
        MESSAGE 'Retrieved list of policies.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to list policies.' TYPE 'E'.
      CATCH /aws1/cx_orgawsorgsnotinuseex.
        MESSAGE 'Your account is not a member of an organization.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[ListPolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

# 组织使用场景 AWS SDKs
<a name="organizations_code_examples_scenarios"></a>

以下代码示例向您展示了如何使用在 Organizations 中实现常见场景 AWS SDKs。这些情境向您展示了如何通过调用 Organizations 中的多个函数或与其他 AWS 服务结合来完成特定任务。每个场景都包含完整源代码的链接，您可以在其中找到有关如何设置和运行代码的说明。

场景以中等水平的经验为目标，可帮助您结合具体环境了解服务操作。

**Topics**
+ [权限策略允许 AWS Compute Optimizer Automation 应用建议的操作](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.managed-policies.xml.10_section.md)
+ [在整个组织中启用自动化功能的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.2_section.md)
+ [启用账户自动化功能的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.1_section.md)
+ [向组织管理账户授予对 Compute Optimizer 自动化功能完全访问权限的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.5_section.md)
+ [向独立账户授予对 Compute Optimizer Automizer 自动化的完全访问权限的权限策略 AWS](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.3_section.md)
+ [向组织管理账户授予对 Compute Optimizer 自动化功能只读访问权限的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.6_section.md)
+ [向独立账户授予 Compute Optimizer Automizer Automizer 只读权限的权限策略 AWS](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.4_section.md)
+ [授予计算优化自动化功能的服务相关角色权限的权限策略](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.slr-automation.xml.1_section.md)

# 允许 “ AWS Compute Optimizer 自动化” 功能应用建议的操作
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.managed-policies.xml.10_section"></a>

以下代码示例显示了如何使用此基于权限的策略允许 AWS Compute Optimizer 自动化功能应用建议的操作

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "aco-automation.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

------

# 在整个组织中启用自动化功能的策略
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.2_section"></a>

以下代码示例展示如何通过此基于权限的策略在整个组织中启用自动化功能

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/aco-automation.amazonaws.com/AWSServiceRoleForComputeOptimizerAutomation",
            "Condition": {"StringLike": {"iam:AWSServiceName": "aco-automation.amazonaws.com"}}
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:PutRolePolicy", 
                "iam:AttachRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/aws-service-role/aco-automation.amazonaws.com/AWSServiceRoleForComputeOptimizerAutomation"
        },
        {
            "Effect": "Allow",
            "Action": "aco-automation:UpdateEnrollmentConfiguration",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "aco-automation:AssociateAccounts",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "aco-automation:DisassociateAccounts",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "aco-automation:ListAccounts",
            "Resource": "*"
        }
    ]
}
```

------

# 启用账户自动化功能的策略
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.1_section"></a>

以下代码示例展示如何通过此基于权限的策略启用账户自动化功能

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/aco-automation.amazonaws.com/AWSServiceRoleForComputeOptimizerAutomation",
            "Condition": {"StringLike": {"iam:AWSServiceName": "aco-automation.amazonaws.com"}}
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:PutRolePolicy", 
                "iam:AttachRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/aws-service-role/aco-automation.amazonaws.com/AWSServiceRoleForComputeOptimizerAutomation"
        },
        {
            "Effect": "Allow",
            "Action": "aco-automation:UpdateEnrollmentConfiguration",
            "Resource": "*"
        }
    ]
}
```

------

# 向组织管理账户授予对 Compute Optimizer 自动化功能完全访问权限的策略
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.5_section"></a>

以下代码示例展示如何通过此基于权限的策略向组织的管理账户授予对 Compute Optimizer 自动化功能的完全访问权限

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
               "aco-automation:*",
               "ec2:DescribeVolumes",
               "organizations:ListAccounts",
               "organizations:DescribeOrganization",
               "organizations:DescribeAccount",
               "organizations:EnableAWSServiceAccess",
               "organizations:ListDelegatedAdministrators",
               "organizations:RegisterDelegatedAdministrator",
               "organizations:DeregisterDelegatedAdministrator"
            ],
            "Resource": "*"
        }
    ]
}
```

------

# 向独立账户授予对 Compute Optimizer Automizer 自动化的完全访问权限的政策 AWS
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.3_section"></a>

以下代码示例显示了如何使用此基于权限的策略为独立账户授予对 Compute Optimizer Automizer Automizer Automizer 自动化的完全访问权限 AWS 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
               "aco-automation:*",
            "ec2:DescribeVolumes"
            ],
            "Resource": "*"
        }
    ]
}
```

------

# 向组织管理账户授予对 Compute Optimizer 自动化功能只读访问权限的策略
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.6_section"></a>

以下代码示例展示如何通过此基于权限的策略向组织的管理账户授予对 Compute Optimizer 自动化功能的只读访问权限

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
               "aco-automation:GetEnrollmentConfiguration",
               "aco-automation:GetAutomationEvent",
               "aco-automation:GetAutomationRule",
               "aco-automation:ListAccounts",
               "aco-automation:ListAutomationEvents",
               "aco-automation:ListAutomationEventSteps",
               "aco-automation:ListAutomationEventSummaries",
               "aco-automation:ListAutomationRules",
               "aco-automation:ListAutomationRulePreview",
               "aco-automation:ListAutomationRulePreviewSummaries",
               "aco-automation:ListRecommendedActions",
               "aco-automation:ListRecommendedActionSummaries",
               "aco-automation:ListTagsForResource",
               "ec2:DescribeVolumes"
            ],
            "Resource": "*"
        }
    ]
}
```

------

# 向独立账户授予对 Compute Optimizer Automizer 自动化的只读访问权限的政策 AWS
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.4_section"></a>

以下代码示例显示了如何使用此基于权限的策略为独立账户授予对 Compute Optimizer Automizer Automizer Automatizer 的只读访问 AWS 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
               "aco-automation:GetEnrollmentConfiguration",
               "aco-automation:GetAutomationEvent",
               "aco-automation:GetAutomationRule",
               "aco-automation:ListAutomationEvents",
               "aco-automation:ListAutomationEventSteps",
               "aco-automation:ListAutomationEventSummaries",
               "aco-automation:ListAutomationRules",
               "aco-automation:ListAutomationRulePreview",
               "aco-automation:ListAutomationRulePreviewSummaries",
               "aco-automation:ListRecommendedActions",
               "aco-automation:ListRecommendedActionSummaries",
               "aco-automation:ListTagsForResource",
               "ec2:DescribeVolumes"
            ],
            "Resource": "*"
        }
    ]
}
```

------

# 授予计算优化自动化功能的服务相关角色权限的策略
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.slr-automation.xml.1_section"></a>

以下代码示例展示如何通过此基于权限的策略授予计算优化自动化功能的服务相关角色权限

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	                    
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/aco-automation.amazonaws.com/AWSServiceRoleForComputeOptimizerAutomation",
            "Condition": {"StringLike": {"iam:AWSServiceName": "aco-automation.amazonaws.com"}}
        },
        {
            "Effect": "Allow",
            "Action": "iam:PutRolePolicy",
            "Resource": "arn:aws:iam::*:role/aws-service-role/aco-automation.amazonaws.com/AWSServiceRoleForComputeOptimizerAutomation"
        }
    ]
}
```

------