

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 [AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# 使用 AWS SDKs 的組織程式碼範例
<a name="organizations_code_examples"></a>

下列程式碼範例示範如何使用 AWS Organizations 搭配 AWS 軟體開發套件 (SDK)。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

*案例*是向您展示如何呼叫服務中的多個函數或與其他 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 自動化套用建議的動作](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 Automation 完整存取權的許可政策](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.5_section.md)
  + [授予獨立 AWS 帳戶 Compute Optimizer Automation 完整存取權的許可政策](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.3_section.md)
  + [授予組織管理帳戶 Compute Optimizer Automation 唯讀存取權的許可政策](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.6_section.md)
  + [授予獨立 AWS 帳戶 Compute Optimizer Automation 唯讀存取權的許可政策](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 SDKs 的組織的基本範例
<a name="organizations_code_examples_basics"></a>

下列程式碼範例示範如何 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)

# 使用 AWS SDKs 的組織動作
<a name="organizations_code_examples_actions"></a>

下列程式碼範例示範如何使用 AWS SDKs 執行個別 Organizations 動作。每個範例均包含 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 詳細資訊，請參閱《AWS SDK for Python (Boto3) API 參考》**中的 [AttachPolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/AttachPolicy)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [AttachPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

# `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**  
**建立會自動成為組織一部分的成員帳戶**  
下列範例示範如何在組織中建立成員帳戶。成員帳戶是以生產帳戶名稱和 susan@example.com 的電子郵件地址來設定。Organizations 會使用 OrganizationAccountAccessRole 的預設名稱自動建立 IAM 角色，因為未指定 roleName 參數。此外，由於未指定 IamUserAccessToBilling 參數，因此允許具有足夠許可存取帳戶帳單資料的 IAM 使用者或角色的設定會設定為預設值 ALLOW。Organizations 會自動傳送「歡迎 AWS」電子郵件給 Susan：  

```
aws organizations create-account --email susan@example.com --account-name "Production Account"
```
輸出包含一個請求物件，顯示狀態現在為 `IN_PROGRESS`：  

```
{
        "CreateAccountStatus": {
                "State": "IN_PROGRESS",
                "Id": "car-examplecreateaccountrequestid111"
        }
}
```
您稍後可以將 Id 回應值作為 create-account-request-id 參數的值提供給 describe-create-account-status 命令，以查詢請求的目前狀態。  
如需詳細資訊，請參閱《 *AWS Organizations 使用者指南*》中的在您的組織中建立 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**  
下列範例示範如何建立名為 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 Reference* 中的 [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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API Reference* 中的 [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/CreatePolicy)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [CreatePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

# `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**  
**刪除組織**  
下列範例顯示如何刪除組織。若要執行此操作，您必須是組織中主帳戶的管理員。此範例假設您先前已從組織移除所有成員帳戶、OU 和政策：  

```
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。此範例假設您先前已從 OU 移除所有帳戶和其他 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 Reference* 中的 [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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API Reference* 中的 [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DeletePolicy)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [DeletePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

# `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 詳細資訊，請參閱《AWS SDK for Python (Boto3) API 參考》**中的 [DescribePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DescribePolicy)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [DescribePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

# `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 詳細資訊，請參閱《AWS SDK for Python (Boto3) API 參考》**中的 [DetachPolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DetachPolicy)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [DetachPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

# `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 或根帳戶中的 OU 清單**  
下列範例示範如何取得指定根帳戶中的 OU 清單：  

```
aws organizations list-organizational-units-for-parent --parent-id r-examplerootid111
```
輸出顯示指定的根帳戶包含兩個 OU 並顯示每個的詳細資訊：  

```
{
        "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 Reference* 中的 [ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListPolicies)。

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

**AWS CLI**  
**擷取特定類型組織中所有政策的清單**  
下列範例示範如何取得篩選條件參數所指定的 SCP 清單：  

```
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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API Reference* 中的 [ListPolicies](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/ListPolicies)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [ListPolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

# 使用 AWS SDKs 的組織案例
<a name="organizations_code_examples_scenarios"></a>

下列程式碼範例示範如何在 Organizations AWS SDKs中實作常見案例。這些案例說明如何透過在 Organizations 中呼叫多個函數或與其他函數結合，來完成特定任務 AWS 服務。每個案例均包含完整原始碼的連結，您可在連結中找到如何設定和執行程式碼的相關指示。

案例的目標是獲得中等水平的經驗，協助您了解內容中的服務動作。

**Topics**
+ [許可政策允許 AWS Compute Optimizer 自動化套用建議的動作](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 Automation 完整存取權的許可政策](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.5_section.md)
+ [授予獨立 AWS 帳戶 Compute Optimizer Automation 完整存取權的許可政策](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.3_section.md)
+ [授予組織管理帳戶 Compute Optimizer Automation 唯讀存取權的許可政策](organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.6_section.md)
+ [授予獨立 AWS 帳戶 Compute Optimizer Automation 唯讀存取權的許可政策](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>

下列程式碼範例示範如何為您的帳戶啟用以許可為基礎的政策 enablesAutomation 

------
#### [ 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 Automation 完整存取權的政策
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.5_section"></a>

下列程式碼範例示範如何將此以許可為基礎的政策授予組織管理帳戶對 Compute Optimizer Automation 的完整存取權

------
#### [ 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": "*"
        }
    ]
}
```

------

# 授予獨立 AWS 帳戶 Compute Optimizer Automation 完整存取權的政策
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.3_section"></a>

下列程式碼範例示範如何將此以許可為基礎的政策授予獨立 AWS 帳戶對 Compute Optimizer Automation 的完整存取權

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

****  

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

------

# 為組織的管理帳戶授予 Compute Optimizer Automation 唯讀存取權的政策
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.6_section"></a>

下列程式碼範例示範如何針對組織的管理帳戶，此以許可為基礎的政策授予 Compute Optimizer Automation 的唯讀存取權

------
#### [ 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": "*"
        }
    ]
}
```

------

# 授予獨立 AWS 帳戶 Compute Optimizer Automation 唯讀存取權的政策
<a name="organizations_example_iam-policies.AWSMettleDocs.latest.userguide.automation.xml.4_section"></a>

下列程式碼範例示範如何將此以許可為基礎的政策授予獨立 AWS 帳戶的 Compute Optimizer Automation 唯讀存取權

------
#### [ 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"
        }
    ]
}
```

------