AWS - Organizations

Manage Amazon Web Services accounts and their resources.

Identity and Access Management · AWS Organizations

Details

IDAWS - Organizations
ProviderAmazon
CategoryIdentity and Access Management
From Version6.10.0
Docker Imagedemisto/boto3py3:1.0.0.10221838
Supported ModulesAgentix XSIAM

README

Manage Amazon Web Services accounts and their resources.
For AWS Organizations quotas, guidelines and restrictions, see the AWS Organizations Quotas page.

Configure AWS - Organizations in Cortex

Parameter Description Required
Role Arn The Amazon Resource Name (ARN) of the role to assume. False
Role Session Name An identifier for the assumed role session. False
Role Session Duration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. False
Access Key   False
Secret Key   False
Timeout The time in seconds until a timeout exception is reached. You can specify just the read timeout (for example 60) or also the connect timeout followed after a comma (for example 60,10). If a connect timeout is not specified, a default of 10 seconds will be used. False
Retries The maximum number of retry attempts when connection or throttling errors are encountered. Set to 0 to disable retries. The default value is 5 and the limit is 10. Note: Increasing the number of retries will increase the execution time. False
Trust any certificate (not secure)   False
Use system proxy settings   False

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

aws-org-root-list


List the roots that are defined in the current organization.

Base Command

aws-org-root-list

Input

Argument Name Description Required
limit The number of roots to return. Default is 50. Optional
page_size The number of roots to return per page. The maximum is 1000. Optional
next_token The token denoting the next page of roots, as given by the response of the previous run of this command under the context key “AWS.Organizations.RootNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Root.Id String The unique identifier (ID) of the root.
AWS.Organizations.Root.Arn String The Amazon Resource Name (ARN) of the root.
AWS.Organizations.Root.Name String The friendly name of the root.
AWS.Organizations.Root.PolicyTypes.Type String The name of the policy type.
AWS.Organizations.Root.PolicyTypes.Status String The status of the policy type as it relates to the associated root.
AWS.Organizations.RootNextToken String If not null, indicates that more output is available than is included in the current response. Use this value in the next_token argument in a subsequent call of the command to get the next part of the output.

Command example


#### Context Example

```json
{
    "AWS": {
        "Organizations": {
            "Root": {
                "Arn": "arn:aws:organizations::111222333444:root/o-abcde12345/r-ab12",
                "Id": "r-ab12",
                "Name": "Root",
                "PolicyTypes": [
                    {
                        "Status": "ENABLED",
                        "Type": "BACKUP_POLICY"
                    },
                    {
                        "Status": "ENABLED",
                        "Type": "SERVICE_CONTROL_POLICY"
                    }
                ]
            },
            "RootNextToken": null
        }
    }
}

Human Readable Output

AWS Organization Roots

Id Arn Name
r-ab12 arn:aws:organizations::111222333444:root/o-abcde12345/r-ab12 Root

aws-org-children-list


List all of the organizational units (OUs) or accounts that are contained in the specified parent OU or root.

Base Command

aws-org-children-list

Input

Argument Name Description Required
parent_id The unique identifier (ID) for the parent root or organizational unit whose children are to be listed. Required
child_type Filters the output to include only the specified child type. Possible values are: Account, OrganizationalUnit. Required
limit The number of children to return. Default is 50. Optional
page_size The number of children to return per page. The maximum is 1000. Optional
next_token The token denoting the next page of children as given by the response of the previous run of this command under the context key “AWS.Organizations.ChildrenNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Children.Id String The unique identifier (ID) of the child entity.
AWS.Organizations.Children.Type String The type of the child entity.
AWS.Organizations.Children.ParentId String The unique identifier (ID) for the parent root or organizational unit of the child entity.
AWS.Organizations.ChildrenNextToken String If not null, indicates that more output is available than is included in the current response. Use this value in the next_token argument in a subsequent call of the command to get the next part of the output.

Command example

!aws-org-children-list parent_id="r-ab12" child_type="OrganizationalUnit"

Context Example

{
    "AWS": {
        "Organizations": {
            "Children": {
                "Id": "ou-ab12-abcd1234",
                "ParentId": "r-ab12",
                "Type": "ORGANIZATIONAL_UNIT"
            },
            "ChildrenNextToken": null
        }
    }
}

Human Readable Output

AWS Account r-ab12 Children

Id Type
ou-ab12-abcd1234 ORGANIZATIONAL_UNIT

aws-org-parent-list


Lists all of the organizational units (OUs) or accounts that are a parent OU or root of the specified child.
This command returns only the immediate parents in the hierarchy.

Base Command

aws-org-parent-list

Input

Argument Name Description Required
child_id The unique identifier (ID) of the organizational unit or account whose parent containers you want to list. Don’t specify a root.
This value can be retrieved by running the command “aws-org-account-list”.
Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Parent.Id String The unique identifier (ID) of the parent entity.
AWS.Organizations.Parent.Type String The type of the parent entity.
AWS.Organizations.Parent.ChildId String The unique identifier (ID) of the organizational unit or account of the child of the parent entity.

Command example

!aws-org-parent-list child_id="ou-ab12-abcd1234"

Context Example

{
    "AWS": {
        "Organizations": {
            "Parent": {
                "ChildId": "ou-ab12-abcd1234",
                "Id": "r-ab12",
                "Type": "ROOT"
            }
        }
    }
}

Human Readable Output

AWS Account ou-ab12-abcd1234 Parent

Id Type
r-ab12 ROOT

aws-org-organization-unit-get


Retrieve information about an organizational unit (OU).
This command can be called only from the organization’s management account or by a member account that is a delegated administrator for an Amazon Web Services service.

Base Command

aws-org-organization-unit-get

Input

Argument Name Description Required
organization_unit_id The unique identifier (ID) of the organizational unit to retrieve details about. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.OrganizationUnit.Id String The unique identifier (ID) associated with the organizational unit.
AWS.Organizations.OrganizationUnit.Arn String The Amazon Resource Name (ARN) of the organizational unit.
AWS.Organizations.OrganizationUnit.Name String The friendly name of the organizational unit.

Command example

!aws-org-organization-unit-get organization_unit_id=ou-ab12-abcd1234

Context Example

{
    "AWS": {
        "Organizations": {
            "OrganizationUnit": {
                "Arn": "arn:aws:organizations::111222333444:ou/o-abcde12345/ou-ab12-abcd1234",
                "Id": "ou-ab12-abcd1234",
                "Name": "Name OU"
            }
        }
    }
}

Human Readable Output

AWS Organization Unit

Id Arn Name
ou-ab12-abcd1234 arn:aws:organizations::111222333444:ou/o-abcde12345/ou-ab12-abcd1234 Name OU

aws-org-account-list


Lists all the accounts in the organization or a specific account by ID.

Base Command

aws-org-account-list

Input

Argument Name Description Required
account_id Get a specific account by ID. Optional
limit The number of accounts to return. Default is 50. Optional
page_size The number of accounts to return per page. The maximum is 1000. Optional
next_token The token denoting the next page of accounts, as given by the response of the previous run of this command under the context key “AWS.Organizations.AccountNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Account.Id String The unique identifier (ID) of the account.
AWS.Organizations.Account.Arn String The Amazon Resource Name (ARN) of the account.
AWS.Organizations.Account.Email String The email address associated with the Amazon Web Services account.
AWS.Organizations.Account.Name String The friendly name of the account.
AWS.Organizations.Account.Status String The status of the account in the organization.
AWS.Organizations.Account.JoinedMethod String The method by which the account joined the organization.
AWS.Organizations.Account.JoinedTimestamp Date The date the account became a part of the organization.
AWS.Organizations.AccountNextToken String If not null, indicates that more output is available than is included in the current response. Use this value in the next_token argument in a subsequent call of the command to get the next part of the output.

Command example

!aws-org-account-list account_id=111222333444

Context Example

{
    "AWS": {
        "Organizations": {
            "Account": {
                "Arn": "arn:aws:organizations::111222333444:account/o-abcde12345/111222333444",
                "Email": "user@xsoar.com",
                "Id": "111222333444",
                "JoinedMethod": "CREATED",
                "JoinedTimestamp": "2023-09-04 09:17:14.299000+00:00",
                "Name": "Name",
                "Status": "ACTIVE"
            }
        }
    }
}

Human Readable Output

AWS Organization Accounts

Id Arn Name Email JoinedMethod JoinedTimestamp Status
111222333444 arn:aws:organizations::111222333444:account/o-abcde12345/111222333444 Name user@xsoar.com CREATED 2023-09-04 09:17:14.299000+00:00 ACTIVE

Command example

Human Readable Output

AWS Organization Accounts

Id Arn Name Email JoinedMethod JoinedTimestamp Status
111222333444 arn:aws:organizations::111222333444:account/o-abcde12345/111222333444 Name user@xsoar.com CREATED 2023-09-04 09:17:14.299000+00:00 ACTIVE
111222333444 arn:aws:organizations::111222333444:account/o-abcde12345/111222333444 john-doe user@xsoar.com INVITED 2022-07-25 09:11:23.528000+00:00 SUSPENDED

aws-org-organization-get


Retrieves information about the organization that the user’s account belongs to.

Base Command

aws-org-organization-get

Input

Argument Name Description Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Organization.Id String The unique identifier (ID) of the organization.
AWS.Organizations.Organization.Arn String The Amazon Resource Name (ARN) of the organization.
AWS.Organizations.Organization.FeatureSet String Specifies the functionality that currently is available to the organization. If set to “ALL”, then all features are enabled and policies can be applied to accounts in the organization. If set to “CONSOLIDATED_BILLING”, then only consolidated billing functionality is available.
AWS.Organizations.Organization.MasterAccountArn String The Amazon Resource Name (ARN) of the account that is designated as the management account for the organization.
AWS.Organizations.Organization.MasterAccountId String The unique identifier (ID) of the management account of the organization.
AWS.Organizations.Organization.MasterAccountEmail String The email address that is associated with the Amazon Web Services account that is designated as the management account for the organization.

Command example


#### Context Example

```json
{
    "AWS": {
        "Organizations": {
            "Organization": {
                "Arn": "arn:aws:organizations::111222333444:organization/o-abcde12345",
                "AvailablePolicyTypes": [
                    {
                        "Status": "ENABLED",
                        "Type": "SERVICE_CONTROL_POLICY"
                    }
                ],
                "FeatureSet": "ALL",
                "Id": "o-abcde12345",
                "MasterAccountArn": "arn:aws:organizations::111222333444:account/o-abcde12345/111222333444",
                "MasterAccountEmail": "user@xsoar.com",
                "MasterAccountId": "111222333444"
            }
        }
    }
}

Human Readable Output

AWS Organization

Id Arn FeatureSet MasterAccountArn MasterAccountId MasterAccountEmail
o-abcde12345 arn:aws:organizations::111222333444:organization/o-abcde12345 ALL arn:aws:organizations::111222333444:account/o-abcde12345/111222333444 111222333444 user@xsoar.com

aws-org-organization-unit-create


Creates an organizational unit (OU) within a root or parent OU. An OU is a container for accounts that enables the organization of accounts to apply policies according to business requirements. The number of levels deep that OUs can be nested is dependent upon the policy types enabled for that root. For service control policies, the limit is five.

Base Command

aws-org-organization-unit-create

Input

Argument Name Description Required
name The friendly name to assign to the new organizational unit. Required
parent_id The unique identifier (ID) of the parent root or organizational unit to create the new organizational unit in. This value can be retrieved by running the command “aws-org-root-list”. Required
tags A comma-separated list of tags to attach to the newly created organizational unit. Each tag should be in the format: “key=value”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.OrganizationUnit.Id String The unique identifier (ID) associated with this organizational unit.
AWS.Organizations.OrganizationUnit.Arn String The Amazon Resource Name (ARN) of this organizational unit.
AWS.Organizations.OrganizationUnit.Name String The friendly name of this organizational unit.

Command example

!aws-org-organization-unit-create name=test parent_id=r-12ab tags="new=true,key=value"

Context Example

{
    "AWS": {
        "Organizations": {
            "OrganizationUnit": {
                "Arn": "arn:aws:organizations::111222333444:ou/o-abcde12345/ou-ab12-abcd1234",
                "Id": "ou-ab12-abcd1234",
                "Name": "test"
            }
        }
    }
}

Human Readable Output

AWS Organization Unit

Id Name Arn
ou-ab12-abcd1234 test arn:aws:organizations::111222333444:ou/o-abcde12345/ou-ab12-abcd1234

aws-org-organization-unit-rename


Renames the specified organizational unit (OU). The ID and ARN don’t change. The child OUs and accounts remain in place, and any attached policies of the OU remain attached.

Base Command

aws-org-organization-unit-rename

Input

Argument Name Description Required
organizational_unit_id The unique identifier (ID) of the OU to rename. This value can be retrieved by running the command “aws-org-parent-list”. Required
name The new name to assign to the organizational unit. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-organization-unit-rename name=new_name organizational_unit_id=ou-ab12-abcd1234

Human Readable Output

AWS organization unit ou-ab12-abcd1234 successfully renamed to new_name.

aws-org-organization-unit-delete


Deletes an organizational unit (OU) from a root or another OU. All accounts and child OUs must first be removed.

Base Command

aws-org-organization-unit-delete

Input

Argument Name Description Required
organizational_unit_id The unique identifier (ID) of the organizational unit that you want to delete. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-organization-unit-delete organizational_unit_id=ou-ab12-abcd1234

Human Readable Output

AWS organizational unit ou-ab12-abcd1234 deleted successfully.

aws-org-policy-list


Retrieves the list of all policies in an organization of a specified type.

Base Command

aws-org-policy-list

Input

Argument Name Description Required
policy_type Specifies the type of policy to include in the response. Possible values are: Service Control Policy, Tag Policy, Backup Policy, AI Services Opt Out Policy. Required
limit The number of policies to return. Default is 50. Optional
page_size The number of policies to return per page. The maximum is 1000. Optional
next_token The token denoting the next page of policies, as given by the response of the previous run of this command under the context key “AWS.Organizations.PolicyNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Policy.Id String The unique identifier (ID) of the policy.
AWS.Organizations.Policy.Arn String The Amazon Resource Name (ARN) of the policy.
AWS.Organizations.Policy.Name String The friendly name of the policy.
AWS.Organizations.Policy.Description String The description of the policy.
AWS.Organizations.Policy.Type String The type of policy.
AWS.Organizations.Policy.AwsManaged Boolean Indicates whether the specified policy is an Amazon Web Services managed policy. If true, the policy can be attached to roots, organizational units, or accounts, but cannot be edited.
AWS.Organizations.PolicyNextToken String If not null, indicates that more output is available than is included in the current response. Use this value as the next_token argument in a subsequent call of the command to get the next part of the output.

Command example

!aws-org-policy-list policy_type="Service Control Policy"

Context Example

{
    "AWS": {
        "Organizations": {
            "Policy": [
                {
                    "Arn": "arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess",
                    "AwsManaged": true,
                    "Description": "Allows access to every operation",
                    "Id": "p-FullAWSAccess",
                    "Name": "FullAWSAccess",
                    "Type": "SERVICE_CONTROL_POLICY"
                },
                {
                    "Arn": "arn:aws:organizations::111222333444:policy/o-abcde12345/service_control_policy/p-1234abcd",
                    "AwsManaged": false,
                    "Description": "Used for test purposes",
                    "Id": "p-1234abcd",
                    "Name": "Test",
                    "Type": "SERVICE_CONTROL_POLICY"
                }
            ],
            "PolicyNextToken": null
        }
    }
}

Human Readable Output

AWS Organization Policies

Id Arn Name Description Type AwsManaged
p-FullAWSAccess arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess FullAWSAccess Allows access to every operation SERVICE_CONTROL_POLICY true
p-1234abcd arn:aws:organizations::111222333444:policy/o-abcde12345/service_control_policy/p-1234abcd Test Used for test purposes SERVICE_CONTROL_POLICY false

aws-org-policy-get


Retrieves information about a policy.

Base Command

aws-org-policy-get

Input

Argument Name Description Required
policy_id The unique identifier (ID) of the policy that you want details about. This value can be retrieved by running the command “aws-org-policy-list”. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Policy.Id String The unique identifier (ID) of the policy.
AWS.Organizations.Policy.Arn String The Amazon Resource Name (ARN) of the policy.
AWS.Organizations.Policy.Name String The friendly name of the policy.
AWS.Organizations.Policy.Description String The description of the policy.
AWS.Organizations.Policy.Type String The type of policy.
AWS.Organizations.Policy.AwsManaged Boolean Indicates whether the specified policy is an Amazon Web Services managed policy. If true, the policy can be attached to roots, organizational units, or accounts, but cannot be edited.

Command example

!aws-org-policy-get policy_id=p-1234abcd

Context Example

{
    "AWS": {
        "Organizations": {
            "Policy": {
                "Arn": "arn:aws:organizations::111222333444:policy/o-abcde12345/service_control_policy/p-1234abcd",
                "AwsManaged": false,
                "Description": "Used for test purposes",
                "Id": "p-1234abcd",
                "Name": "Test",
                "Type": "SERVICE_CONTROL_POLICY"
            }
        }
    }
}

Human Readable Output

AWS Organization Policies

Id Arn Name Description Type AwsManaged
p-1234abcd arn:aws:organizations::111222333444:policy/o-abcde12345/service_control_policy/p-1234abcd Test Used for test purposes SERVICE_CONTROL_POLICY false

aws-org-policy-attach


Attaches a policy to a root, an organizational unit (OU), or an individual account.

Base Command

aws-org-policy-attach

Input

Argument Name Description Required
policy_id The unique identifier (ID) of the policy to attach to the target. This value can be retrieved by running the command “aws-org-policy-list”. Required
target_id The unique identifier (ID) of the root, organizational unit, or account to attach the policy to. This value can be retrieved by running the command “aws-org-root-list” or “aws-org-account-list”. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-policy-attach policy_id=p-1234abcd target_id=ou-ab12-abcd1234

Human Readable Output

AWS Organizations policy p-1234abcd successfully attached.

aws-org-policy-target-list


Lists all the roots, organizational units (OUs), and accounts that the specified policy is attached to.

Base Command

aws-org-policy-target-list

Input

Argument Name Description Required
policy_id The unique identifier (ID) of the policy whose attachments are to be listed. Required
limit The number of policies to return. Default is 50. Optional
page_size The number of policies to return per page. The maximum is 1000. Optional
next_token The token denoting the next page of policies, as given by the response of the previous run of this command under the context key “AWS.Organizations.PolicyTargetNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.PolicyTarget.TargetId String The unique identifier (ID) of the policy target.
AWS.Organizations.PolicyTarget.Arn String The Amazon Resource Name (ARN) of the policy target.
AWS.Organizations.PolicyTarget.Name String The friendly name of the policy target.
AWS.Organizations.PolicyTarget.Type String The type of the policy target.
AWS.Organizations.PolicyTarget.PolicyId String The unique identifier (ID) of the policy.
AWS.Organizations.PolicyTargetNextToken String If not null, indicates that more output is available than is included in the current response. Use this value as the next_token argument in a subsequent call of the command to get the next part of the output.

Command example

!aws-org-policy-target-list policy_id=p-1234abcd

Context Example

{
    "AWS": {
        "Organizations": {
            "PolicyTarget": {
                "Arn": "arn:aws:organizations::111222333444:ou/o-abcde12345/ou-ab12-abcd1234",
                "Name": "to_add_policy",
                "PolicyId": "p-1234abcd",
                "TargetId": "ou-ab12-abcd1234",
                "Type": "ORGANIZATIONAL_UNIT"
            },
            "PolicyTargetNextToken": null
        }
    }
}

Human Readable Output

AWS Organization p-1234abcd Targets

TargetId Arn Name Type
ou-ab12-abcd1234 arn:aws:organizations::111222333444:ou/o-abcde12345/ou-ab12-abcd1234 to_add_policy ORGANIZATIONAL_UNIT

aws-org-target-policy-list


Lists the policies that are directly attached to the specified target root, organizational unit (OU), or account.

Base Command

aws-org-target-policy-list

Input

Argument Name Description Required
policy_type The type of policy to include in the returned list. Possible values are: Service Control Policy, Tag Policy, Backup Policy, AI Services Opt Out Policy. Required
target_id The unique identifier (ID) of the root, organizational unit, or account whose policies are to be listed. Required
limit The number of policies to return. Default is 50. Optional
page_size The number of policies to return per page. The maximum is 1000. Optional
next_token The token denoting the next page of policies, as given by the response of the previous run of this command under the context key “AWS.Organizations.PolicyNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.TargetPolicy.Id String The unique identifier (ID) of the policy.
AWS.Organizations.TargetPolicy.Arn String The Amazon Resource Name (ARN) of the policy.
AWS.Organizations.TargetPolicy.Name String The friendly name of the policy.
AWS.Organizations.TargetPolicy.Description String The description of the policy.
AWS.Organizations.TargetPolicy.Type String The type of policy.
AWS.Organizations.TargetPolicy.AwsManaged Boolean Indicates whether the specified policy is an Amazon Web Services managed policy. If true, the policy can be attached to roots, organizational units, or accounts, but cannot be edited.
AWS.Organizations.TargetId String The unique identifier (ID) of the target.
AWS.Organizations.TargetPolicyNextToken String If not null, indicates that more output is available than is included in the current response. Use this value as the next_token argument in a subsequent call of the command to get the next part of the output.

Command example

!aws-org-target-policy-list target_id=ou-ab12-abcd1234 policy_type="Service Control Policy"

Context Example

{
    "AWS": {
        "Organizations": {
            "TargetPolicy": [
                {
                    "Arn": "arn:aws:organizations::111222333444:policy/o-abcde12345/service_control_policy/p-1234abcd",
                    "AwsManaged": false,
                    "Description": "Used for test purposes",
                    "Id": "p-1234abcd",
                    "Name": "Test",
                    "TargetId": "ou-ab12-abcd1234",
                    "Type": "SERVICE_CONTROL_POLICY"
                },
                {
                    "Arn": "arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess",
                    "AwsManaged": true,
                    "Description": "Allows access to every operation",
                    "Id": "p-FullAWSAccess",
                    "Name": "FullAWSAccess",
                    "TargetId": "ou-ab12-abcd1234",
                    "Type": "SERVICE_CONTROL_POLICY"
                }
            ],
            "TargetPolicyNextToken": null
        }
    }
}

Human Readable Output

AWS Organization ou-ab12-abcd1234 Policies

Id Arn Name Description Type AwsManaged
p-1234abcd arn:aws:organizations::111222333444:policy/o-abcde12345/service_control_policy/p-1234abcd Test Used for test purposes SERVICE_CONTROL_POLICY false
p-FullAWSAccess arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess FullAWSAccess Allows access to every operation SERVICE_CONTROL_POLICY true

aws-org-policy-delete


Deletes the specified policy from the organization. Before performing this operation, the policy must be detached from all organizational units (OUs), roots, and accounts.

Base Command

aws-org-policy-delete

Input

Argument Name Description Required
policy_id The unique identifier (ID) of the policy that you want to delete. This value can be retrieved by running the command “aws-org-policy-list”. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-policy-delete policy_id=p-1234abcd

Human Readable Output

AWS Organizations policy p-1234abcd successfully deleted.

aws-org-resource-tag-add


Adds one or more tags to the specified resource.

Base Command

aws-org-resource-tag-add

Input

Argument Name Description Required
resource_id The ID of the resource to add a tag to. This value can be retrieved by running the command “aws-org-root-list”, “aws-org-account-list”, “aws-org-root-list”, or “aws-org-policy-list”. Required
tags A comma-separated list of tags to attach to the resource. Each tag should be in the format: “key=value”. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-resource-tag-add resource_id=ou-ab12-abcd1234 tags="test=true,key=value"

Human Readable Output

AWS Organizations resource ou-ab12-abcd1234 successfully tagged.

aws-org-resource-tag-list


Lists tags that are attached to the specified resource.

Base Command

aws-org-resource-tag-list

Input

Argument Name Description Required
resource_id The ID of the resource with the tags to list. This value can be retrieved by running the command “aws-org-root-list”, “aws-org-account-list”, “aws-org-root-list”, or “aws-org-policy-list”. Required
next_token The token denoting the next page of tags, as given by the response of the previous run of this command under the context key “AWS.Organizations.TagNextToken”. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Tag.Key String The key identifier, or name, of the tag.
AWS.Organizations.Tag.Value String The string value that’s associated with the key of the tag.
AWS.Organizations.Tag.ResourceId String The unique identifier (ID) of the resource.
AWS.Organizations.TagNextToken String If not null, indicates that more output is available than is included in the current response. Use this value as the next_token argument in a subsequent call of the command to get the next part of the output.

Command example

!aws-org-resource-tag-list resource_id=ou-ab12-abcd1234

Context Example

{
    "AWS": {
        "Organizations": {
            "Tag": [
                {
                    "Key": "test",
                    "ResourceId": "ou-ab12-abcd1234",
                    "Value": "true"
                },
                {
                    "Key": "new",
                    "ResourceId": "ou-ab12-abcd1234",
                    "Value": "true"
                },
                {
                    "Key": "key",
                    "ResourceId": "ou-ab12-abcd1234",
                    "Value": "value"
                }
            ],
            "TagNextToken": null
        }
    }
}

Human Readable Output

AWS Organization ou-ab12-abcd1234 Tags

Key Value
test true
new true
key value

aws-org-account-create


Creates an AWS Account that is automatically a member of the organization.

Base Command

aws-org-account-create

Input

Argument Name Description Required
account_name The friendly name of the member account. Required
email The email address of the owner to assign to the new member account. This email address must not already be associated with another Amazon Web Services account. Use a valid email address to complete account creation. Required
iam_user_access_to_billing If set to ALLOW, the new account enables IAM users to access account billing information if they have the required permissions. If set to DENY, only the root user of the new account can access account billing information. Possible values are: Allow, Deny. Default is Allow. Optional
role_name The name of an IAM role that AWS Organizations automatically pre-configures in the new member account. This role trusts the management account, allowing users in the management account to assume the role, as permitted by the management account administrator. The role has administrator permissions in the new member account. Default is OrganizationAccountAccessRole. Optional
tags A comma-separated list of tags to attach to the newly created account. Each tag should be in the format: “key=value”. Optional
request_id The ID of the create request that is used for polling. Optional
interval_in_seconds Indicates how long to wait between command executions (in seconds) when the ‘polling’ argument is true. Minimum value is 10 seconds. Default is 30. Optional
timeout Indicates the time in seconds until the polling sequence times out. Default is 600. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.Organizations.Account.Id String The unique identifier (ID) of the account.
AWS.Organizations.Account.Arn String The Amazon Resource Name (ARN) of the account.
AWS.Organizations.Account.Email String The email address associated with the Amazon Web Services account.
AWS.Organizations.Account.Name String The friendly name of the account.
AWS.Organizations.Account.Status String The status of the account in the organization.
AWS.Organizations.Account.JoinedMethod String The method by which the account joined the organization.
AWS.Organizations.Account.JoinedTimestamp Date The date the account became a part of the organization.

Command example

!aws-org-account-create account_name="New" email="user@xsoar.com" tags="new=true,test=yes" iam_user_access_to_billing=Deny

Context Example

{
    "AWS": {
        "Organizations": {
            "Account": {
                "Arn": "arn:aws:organizations::111222333444:account/o-abcde12345/111222333444",
                "Email": "user@xsoar.com",
                "Id": "111222333444",
                "JoinedMethod": "CREATED",
                "JoinedTimestamp": "2023-09-04 09:17:14.299000+00:00",
                "Name": "New",
                "Status": "ACTIVE"
            }
        }
    }
}

Human Readable Output

Creating account:

AWS Organization Accounts

Id Arn Name Email JoinedMethod JoinedTimestamp Status
111222333444 arn:aws:organizations::111222333444:account/o-abcde12345/111222333444 New user@xsoar.com CREATED 2023-09-04 09:17:14.299000+00:00 ACTIVE

aws-org-account-move


Moves an account from one parent to another.

Base Command

aws-org-account-move

Input

Argument Name Description Required
account_id The unique identifier (ID) of the member account move. This value can be retrieved by running the command “aws-org-account-list”. Required
destination_parent_id The unique identifier (ID) of the root or organizational unit to move the account to.
This value can be retrieved by running the command “aws-org-root-list”.
.
Required
source_parent_id The unique identifier (ID) of the root or organizational unit to move the account from.
This value can be retrieved by running the command “aws-org-parent-list” with the child_id set to the account_id.
.
Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-account-move source_parent_id=r-12ab account_id=111222333444 destination_parent_id=ou-ab12-abcd1234

Human Readable Output

AWS account 111222333444 moved successfully.

aws-org-account-remove


Removes an account from the organization.
For more information on this action: https://docs.aws.amazon.com/organizations/latest/APIReference/API_RemoveAccountFromOrganization.html

Base Command

aws-org-account-remove

Input

Argument Name Description Required
account_id The unique identifier (ID) of the member account to be removed from the organization. This can be obtained with the command “aws-organizations-account-list”. Required
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-account-remove account_id=111222333444

Human Readable Output

AWS account 111222333444 removed successfully.

aws-org-account-close


Closes an AWS member account within an organization.

Base Command

aws-org-account-close

Input

Argument Name Description Required
account_id The unique identifier (ID) of the member account to close. This can be obtained with the command “aws-organizations-account-list”. Required
interval_in_seconds Indicates how long to wait between command executions (in seconds) when the ‘polling’ argument is true. Minimum value is 10 seconds. Default is 30. Optional
timeout Indicates the time in seconds until the polling sequence times out. Default is 600. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command example

!aws-org-account-close account_id=111222333444

Human Readable Output

Closing account:

AWS account 111222333444 closed successfully.

Configuration parameters

  • role_arn — Role Arn
  • role_session_name — Role Session Name
  • role_session_duration — Role Session Duration
  • credentials — Access Key
  • timeout — Timeout
  • retries — Retries
  • sts_regional_endpoint — AWS STS Regional Endpoints
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings

Commands (21)

  • aws-org-account-close

    Closes an AWS member account within an organization.

  • aws-org-account-create

    Creates an AWS Account that is automatically a member of the organization.

  • aws-org-account-list

    Lists all the accounts in the organization or a specific account by ID.

  • aws-org-account-move

    Moves an account from one parent to another.

  • aws-org-account-remove

    Removes an account from the organization. For more information on this action: https://docs.aws.amazon.com/organizations/latest/APIReference/API_RemoveAccountFromOrganization.html

  • aws-org-children-list

    List all of the organizational units (OUs) or accounts that are contained in the specified parent OU or root.

  • aws-org-organization-get

    Retrieves information about the organization that the user's account belongs to.

  • aws-org-organization-unit-create

    Creates an organizational unit (OU) within a root or parent OU. An OU is a container for accounts that enables the organization of accounts to apply policies according to business requirements. The number of levels deep that OUs can be nested is dependent upon the policy types enabled for that root. For service control policies, the limit is five.

  • aws-org-organization-unit-delete

    Deletes an organizational unit (OU) from a root or another OU. All accounts and child OUs must first be removed.

  • aws-org-organization-unit-get

    Retrieve information about an organizational unit (OU). This command can be called only from the organization's management account or by a member account that is a delegated administrator for an Amazon Web Services service.

  • aws-org-organization-unit-rename

    Renames the specified organizational unit (OU). The ID and ARN don't change. The child OUs and accounts remain in place, and any attached policies of the OU remain attached.

  • aws-org-parent-list

    Lists all of the organizational units (OUs) or accounts that are a parent OU or root of the specified child. This command returns only the immediate parents in the hierarchy.

  • aws-org-policy-attach

    Attaches a policy to a root, an organizational unit (OU), or an individual account.

  • aws-org-policy-delete

    Deletes the specified policy from the organization. Before performing this operation, the policy must be detached from all organizational units (OUs), roots, and accounts.

  • aws-org-policy-get

    Retrieves information about a policy.

  • aws-org-policy-list

    Retrieves the list of all policies in an organization of a specified type.

  • aws-org-policy-target-list

    Lists all the roots, organizational units (OUs), and accounts that the specified policy is attached to.

  • aws-org-resource-tag-add

    Adds one or more tags to the specified resource.

  • aws-org-resource-tag-list

    Lists tags that are attached to the specified resource.

  • aws-org-root-list

    List the roots that are defined in the current organization.

  • aws-org-target-policy-list

    Lists the policies that are directly attached to the specified target root, organizational unit (OU), or account.

from collections.abc import Callable
from typing import TYPE_CHECKING

import demistomock as demisto  # noqa
from AWSApiModule import *  # noqa
from CommonServerPython import *  # noqa

# The following imports are used only for type hints and autocomplete.
# They are not used at runtime, and are not in the docker image.
if TYPE_CHECKING:
    from mypy_boto3_organizations import OrganizationsClient
    from mypy_boto3_organizations.literals import CreateAccountFailureReasonType, PolicyTypeType

""" CONSTANTS """

SERVICE_NAME = "organizations"
REGION = "us-east-1"
MAX_PAGINATION = 20
POLICY_TYPE_MAP: dict[str, "PolicyTypeType"] = {
    "Service Control Policy": "SERVICE_CONTROL_POLICY",
    "Tag Policy": "TAG_POLICY",
    "Backup Policy": "BACKUP_POLICY",
    "AI Services Opt Out Policy": "AISERVICES_OPT_OUT_POLICY",
}
CREATE_ACCOUNT_FAILURE_MAP: dict["CreateAccountFailureReasonType", str] = {
    "ACCOUNT_LIMIT_EXCEEDED": "The account couldn't be created because you reached the limit"
    " on the number of accounts in your organization.",
    "CONCURRENT_ACCOUNT_MODIFICATION": "You already submitted a request with the same information.",
    "EMAIL_ALREADY_EXISTS": "The account could not be created because another Amazon Web Services account with that email"
    " address already exists.",
    "FAILED_BUSINESS_VALIDATION": "The Amazon Web Services account that owns your organization failed to receive business"
    " license validation.",
    "GOVCLOUD_ACCOUNT_ALREADY_EXISTS": "The account in the Amazon Web Services GovCloud (US) Region could not be created"
    " because this"
    " Region already includes an account with that email address.",
    "INVALID_IDENTITY_FOR_BUSINESS_VALIDATION": "The Amazon Web Services account that owns your organization can't complete"
    " business license validation"
    "because it doesn't have valid identity data.",
    "INVALID_ADDRESS": "The account could not be created because the address you provided is not valid.",
    "INVALID_EMAIL": "The account could not be created because the email address you provided is not valid.",
    "INVALID_PAYMENT_INSTRUMENT": "The Amazon Web Services account that owns your organization does not have a "
    "supported payment method associated with the account.",
    "INTERNAL_FAILURE": "The account could not be created because of an internal failure. Try again later."
    " If the problem persists, contact Amazon Web Services Customer Support.",
    "MISSING_BUSINESS_VALIDATION": "The Amazon Web Services account that owns your organization has not received Business"
    " Validation.",
    "MISSING_PAYMENT_INSTRUMENT": "You must configure the management account with a valid payment method, such as a credit card.",
    "PENDING_BUSINESS_VALIDATION": "The Amazon Web Services account that owns your organization is still in the"
    " process of completing business license validation.",
    "UNKNOWN_BUSINESS_VALIDATION": "The Amazon Web Services account that owns your organization"
    " has an unknown issue with business license validation.",
}

""" HELPER FUNCTIONS """


def create_client(args: dict, params: dict) -> "OrganizationsClient":
    """Creates the AWS Organizations client and initiates a session."""

    aws_access_key_id = dict_safe_get(params, ("credentials", "identifier"))
    aws_secret_access_key = dict_safe_get(params, ("credentials", "password"))
    aws_default_region = REGION
    aws_role_arn = params.get("role_arn")
    aws_role_session_name = params.get("role_session_name")
    aws_role_session_duration = params.get("role_session_duration")
    aws_role_policy = None

    validate_params(
        aws_default_region,
        aws_role_arn,
        aws_role_session_name,
        aws_access_key_id,
        aws_secret_access_key,
    )

    return AWSClient(
        aws_default_region,
        aws_role_arn,
        aws_role_session_name,
        aws_role_session_duration,
        aws_role_policy,
        aws_access_key_id,
        aws_secret_access_key,
        not params.get("insecure", True),
        params.get("timeout"),
        params.get("retries"),
    ).aws_session(
        service=SERVICE_NAME,
        region=REGION,
        role_arn=args.get("roleArn"),
        role_session_name=args.get("roleSessionName"),
        role_session_duration=args.get("roleSessionDuration"),
    )


def paginate(
    client_func: Callable, key_to_pages: str, limit=None, page_size=None, next_token=None, **kwargs
) -> tuple[list, str | None]:
    """This function exists because AWS doesn't guarantee that the client functions will
    return all results specified in a single call.
    This function also handles the XSOAR pagination conventions such as the limit, page_size and next_token args.
    """

    if not page_size and not next_token:
        next_token = None
        page_size = limit
    page_size = arg_to_number(page_size) or 50
    pages: list = []

    while page_size:
        response: dict = client_func(
            **assign_params(NextToken=next_token),
            MaxResults=min(page_size, MAX_PAGINATION),
            **kwargs,
        )
        page = response.get(key_to_pages, [])
        next_token = response.get("NextToken")
        pages.extend(page)
        page_size -= len(page)
        if next_token is None:
            break

    return pages, next_token


def next_token_output_dict(outputs_prefix: str, next_token: str | None, page_outputs: Any, page_outputs_key: str = "Id") -> dict:
    """Creates a dict for CommandResults.output with the next token."""
    return {
        (
            f"AWS.Organizations.{outputs_prefix}(val.{page_outputs_key} && val.{page_outputs_key} == obj.{page_outputs_key})"
        ): page_outputs,
        "AWS.Organizations(true)": {f"{outputs_prefix}NextToken": next_token},
    }


def dict_values_to_str(d: dict, *keys) -> dict:
    """Converts values in a dict to strings and returns the dict.
    Used mainly when a client function output contains a datetime.
    """
    for key in keys:
        if key in d:
            d[key] = str(d[key])
    return d


def build_tags(tags: str | None) -> list:
    """Turns the tags provided by the args in the format "key=value" into the format expected by AWS"""
    result = []
    for tag in argToList(tags):
        key, eq, value = tag.partition("=")
        if not eq:
            raise DemistoException('Tags must be provided in the format "key=value".')
        result.append({"Key": key, "Value": value})
    return result


""" COMMAND FUNCTIONS """


def test_module(aws_client: "OrganizationsClient") -> str:
    aws_client.describe_organization()
    return "ok"


def root_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    roots, next_token = paginate(
        aws_client.list_roots,
        "Roots",
        limit=args.get("limit"),
        next_token=args.get("next_token"),
        page_size=args.get("page_size"),
    )

    return CommandResults(
        outputs=next_token_output_dict(
            "Root",
            next_token,
            roots,
            "Id",
        ),
        readable_output=tableToMarkdown(
            "AWS Organization Roots",
            roots,
            ["Id", "Arn", "Name"],
            removeNull=True,
        ),
    )


def children_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    children, next_token = paginate(
        aws_client.list_children,
        "Children",
        limit=args.get("limit"),
        next_token=args.get("next_token"),
        page_size=args.get("page_size"),
        ParentId=args["parent_id"],
        ChildType={  # type: ignore
            "Account": "ACCOUNT",
            "OrganizationalUnit": "ORGANIZATIONAL_UNIT",
        }[args["child_type"]],
    )

    return CommandResults(
        outputs=next_token_output_dict(
            "Children",
            next_token,
            [child | {"ParentId": args["parent_id"]} for child in children],
            "Id",
        ),
        readable_output=tableToMarkdown(
            f'AWS Account *{args["parent_id"]}* Children',
            children,
            removeNull=True,
        ),
    )


def parent_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    parents, _ = paginate(
        aws_client.list_parents,
        "Parents",
        limit=1,  # at of the time of this writing, an account can have only one parent
        ChildId=args["child_id"],
    )

    return CommandResults(
        outputs_key_field="Id",
        outputs_prefix="AWS.Organizations.Parent",
        outputs=[parent | {"ChildId": args["child_id"]} for parent in parents],
        readable_output=tableToMarkdown(
            f'AWS Account *{args["child_id"]}* Parent',
            parents,
            removeNull=True,
        ),
    )


def organization_unit_get_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    ou = aws_client.describe_organizational_unit(OrganizationalUnitId=args["organization_unit_id"])

    return CommandResults(
        outputs_key_field="Id",
        outputs_prefix="AWS.Organizations.OrganizationUnit",
        outputs=ou.get("OrganizationalUnit", {}),
        readable_output=tableToMarkdown(
            "AWS Organization Unit",
            ou.get("OrganizationalUnit", {}),
            ["Id", "Arn", "Name"],
            removeNull=True,
        ),
    )


def account_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    def response_to_readable(accounts) -> str:
        return tableToMarkdown(
            "AWS Organization Accounts",
            accounts,
            [
                "Id",
                "Arn",
                "Name",
                "Email",
                "JoinedMethod",
                "JoinedTimestamp",
                "Status",
            ],
            removeNull=True,
        )

    def account_get() -> CommandResults:
        description = aws_client.describe_account(AccountId=args["account_id"])

        account = dict_values_to_str(description.get("Account", {}), "JoinedTimestamp")

        return CommandResults(
            readable_output=response_to_readable(account),
            outputs_key_field="Id",
            outputs_prefix="AWS.Organizations.Account",
            outputs=account,
        )

    def account_list() -> CommandResults:
        accounts, next_token = paginate(
            aws_client.list_accounts,
            "Accounts",
            limit=args.get("limit"),
            next_token=args.get("next_token"),
            page_size=args.get("page_size"),
        )

        accounts = [dict_values_to_str(account, "JoinedTimestamp") for account in accounts]

        return CommandResults(
            outputs=next_token_output_dict(
                "Account",
                next_token,
                accounts,
                "Id",
            ),
            readable_output=response_to_readable(accounts),
        )

    if args.get("account_id"):
        return account_get()
    else:
        return account_list()


def organization_get_command(aws_client: "OrganizationsClient") -> CommandResults:
    organization = aws_client.describe_organization()

    return CommandResults(
        outputs=organization.get("Organization", {}),
        outputs_prefix="AWS.Organizations.Organization",
        outputs_key_field="Id",
        readable_output=tableToMarkdown(
            "AWS Organization",
            organization.get("Organization", {}),
            ["Id", "Arn", "FeatureSet", "MasterAccountArn", "MasterAccountId", "MasterAccountEmail"],
            removeNull=True,
        ),
    )


def account_remove_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.remove_account_from_organization(AccountId=args["account_id"])

    return CommandResults(readable_output=f'AWS account *{args["account_id"]}* removed successfully.')


def account_move_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.move_account(
        AccountId=args["account_id"],
        SourceParentId=args["source_parent_id"],
        DestinationParentId=args["destination_parent_id"],
    )

    return CommandResults(readable_output=f'AWS account *{args["account_id"]}* moved successfully.')


@polling_function(
    "aws-org-account-create",
    interval=arg_to_number(demisto.getArg("interval_in_seconds")),
    timeout=arg_to_number(demisto.getArg("timeout")),
    poll_message="Creating account:",
    requires_polling_arg=False,
)
def account_create_command(args: dict, aws_client: "OrganizationsClient") -> PollResult:
    def initial_call() -> dict:
        account = aws_client.create_account(
            Email=args["email"],
            AccountName=args["account_name"],
            RoleName=args["role_name"],
            IamUserAccessToBilling=args["iam_user_access_to_billing"].upper(),
            **assign_params(Tags=build_tags(args.get("tags"))),
        )
        args["request_id"] = account["CreateAccountStatus"]["Id"]
        return account["CreateAccountStatus"]

    def polling_call() -> dict:
        account = aws_client.describe_create_account_status(CreateAccountRequestId=args["request_id"])
        return account["CreateAccountStatus"]

    def create_response(account: dict) -> PollResult:
        match account["State"]:
            case "SUCCEEDED":
                return PollResult(
                    response=account_list_command({"account_id": account["AccountId"]}, aws_client), continue_to_poll=False
                )
            case "FAILED":
                reason = account.get("FailureReason")
                raise DemistoException(f"Failed to create account. Reason: {CREATE_ACCOUNT_FAILURE_MAP.get(reason, reason)}")
            case _:
                return PollResult(response=None, continue_to_poll=True)

    if not args.get("request_id"):
        account = initial_call()
    else:
        account = polling_call()

    return create_response(account)


@polling_function(
    "aws-org-account-close",
    interval=arg_to_number(demisto.getArg("interval_in_seconds")),
    timeout=arg_to_number(demisto.getArg("timeout")),
    poll_message="Closing account:",
    requires_polling_arg=False,
)
def account_close_command(args: dict, aws_client: "OrganizationsClient") -> PollResult:
    if not argToBoolean(args["is_closed"]):
        aws_client.close_account(AccountId=args["account_id"])
        args["is_closed"] = True

    account = aws_client.describe_account(AccountId=args["account_id"])

    return PollResult(
        response=CommandResults(readable_output=f'AWS account *{args["account_id"]}* closed successfully.'),
        continue_to_poll=(dict_safe_get(account, ["Account", "Status"]) != "SUSPENDED"),
    )


def organization_unit_create_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    ou = aws_client.create_organizational_unit(
        ParentId=args["parent_id"], Name=args["name"], **assign_params(Tags=build_tags(args.get("tags")))
    )

    return CommandResults(
        outputs_prefix="AWS.Organizations.OrganizationUnit",
        outputs_key_field="Id",
        outputs=ou["OrganizationalUnit"],
        readable_output=tableToMarkdown(
            "AWS Organization Unit", ou["OrganizationalUnit"], ["Id", "Name", "Arn"], removeNull=True
        ),
    )


def organization_unit_delete_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.delete_organizational_unit(OrganizationalUnitId=args["organizational_unit_id"])

    return CommandResults(readable_output=f'AWS organizational unit *{args["organizational_unit_id"]}* deleted successfully.')


def organization_unit_rename_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.update_organizational_unit(OrganizationalUnitId=args["organizational_unit_id"], Name=args["name"])

    return CommandResults(
        readable_output=f'AWS organization unit *{args["organizational_unit_id"]}* successfully renamed to *{args["name"]}*.'
    )


def policy_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    policies, next_token = paginate(
        aws_client.list_policies,
        "Policies",
        limit=args.get("limit"),
        next_token=args.get("next_token"),
        page_size=args.get("page_size"),
        Filter=POLICY_TYPE_MAP[args["policy_type"]],
    )

    return CommandResults(
        outputs=next_token_output_dict(
            "Policy",
            next_token,
            policies,
        ),
        readable_output=tableToMarkdown(
            "AWS Organization Policies",
            policies,
            ["Id", "Arn", "Name", "Description", "Type", "AwsManaged"],
            removeNull=True,
        ),
    )


def target_policy_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    policies, next_token = paginate(
        aws_client.list_policies_for_target,
        "Policies",
        limit=args.get("limit"),
        next_token=args.get("next_token"),
        page_size=args.get("page_size"),
        TargetId=args["target_id"],
        Filter=POLICY_TYPE_MAP[args["policy_type"]],
    )

    return CommandResults(
        outputs=next_token_output_dict(
            "TargetPolicy",
            next_token,
            [policy | {"TargetId": args["target_id"]} for policy in policies],
        ),
        readable_output=tableToMarkdown(
            f'AWS Organization *{args["target_id"]}* Policies',
            policies,
            ["Id", "Arn", "Name", "Description", "Type", "AwsManaged"],
            removeNull=True,
        ),
    )


def policy_get_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    response = aws_client.describe_policy(PolicyId=args["policy_id"])

    policy = dict_safe_get(response, ["Policy", "PolicySummary"])

    return CommandResults(
        raw_response=response,
        outputs=policy,
        outputs_key_field="Id",
        outputs_prefix="AWS.Organizations.Policy",
        readable_output=tableToMarkdown(
            "AWS Organization Policies",
            policy,
            ["Id", "Arn", "Name", "Description", "Type", "AwsManaged"],
            removeNull=True,
        ),
    )


def policy_delete_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.delete_policy(PolicyId=args["policy_id"])

    return CommandResults(readable_output=f'AWS Organizations policy *{args["policy_id"]}* successfully deleted.')


def policy_attach_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.attach_policy(PolicyId=args["policy_id"], TargetId=args["target_id"])

    return CommandResults(readable_output=f'AWS Organizations policy *{args["policy_id"]}* successfully attached.')


def policy_target_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    targets, next_token = paginate(
        aws_client.list_targets_for_policy,
        "Targets",
        limit=args.get("limit"),
        next_token=args.get("next_token"),
        page_size=args.get("page_size"),
        PolicyId=args["policy_id"],
    )

    return CommandResults(
        outputs=next_token_output_dict(
            "PolicyTarget", next_token, [target | {"PolicyId": args["policy_id"]} for target in targets], "TargetId"
        ),
        readable_output=tableToMarkdown(
            f'AWS Organization *{args["policy_id"]}* Targets', targets, ["TargetId", "Arn", "Name", "Type"], removeNull=True
        ),
    )


def resource_tag_add_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    aws_client.tag_resource(ResourceId=args["resource_id"], Tags=build_tags(args["tags"]))

    return CommandResults(readable_output=f'AWS Organizations resource *{args["resource_id"]}* successfully tagged.')


def resource_tag_list_command(args: dict, aws_client: "OrganizationsClient") -> CommandResults:
    tags = aws_client.list_tags_for_resource(ResourceId=args["resource_id"], **assign_params(NextToken=args.get("next_token")))

    return CommandResults(
        outputs=next_token_output_dict(
            "Tag", tags.get("NextToken"), [tag | {"ResourceId": args["resource_id"]} for tag in tags.get("Tags", [])], "Key"
        ),
        readable_output=tableToMarkdown(
            f'AWS Organization *{args["resource_id"]}* Tags',
            tags.get("Tags", []),
            ["Key", "Value"],
        ),
    )


""" MAIN FUNCTION """


def main():
    command = demisto.command()
    params = demisto.params()
    args = demisto.args()

    aws_client = create_client(args, params)

    demisto.debug(f"Command being called is {command}")

    try:
        if command == "test-module":
            return_results(test_module(aws_client))
        elif command == "aws-org-root-list":
            return_results(root_list_command(args, aws_client))
        elif command == "aws-org-children-list":
            return_results(children_list_command(args, aws_client))
        elif command == "aws-org-parent-list":
            return_results(parent_list_command(args, aws_client))
        elif command == "aws-org-organization-unit-get":
            return_results(organization_unit_get_command(args, aws_client))
        elif command == "aws-org-account-list":
            return_results(account_list_command(args, aws_client))
        elif command == "aws-org-organization-get":
            return_results(organization_get_command(aws_client))
        elif command == "aws-org-account-remove":
            return_results(account_remove_command(args, aws_client))
        elif command == "aws-org-account-move":
            return_results(account_move_command(args, aws_client))
        elif command == "aws-org-account-create":
            return_results(account_create_command(args, aws_client))
        elif command == "aws-org-account-close":
            return_results(account_close_command(args, aws_client))
        elif command == "aws-org-organization-unit-create":
            return_results(organization_unit_create_command(args, aws_client))
        elif command == "aws-org-organization-unit-delete":
            return_results(organization_unit_delete_command(args, aws_client))
        elif command == "aws-org-organization-unit-rename":
            return_results(organization_unit_rename_command(args, aws_client))
        elif command == "aws-org-policy-list":
            return_results(policy_list_command(args, aws_client))
        elif command == "aws-org-target-policy-list":
            return_results(target_policy_list_command(args, aws_client))
        elif command == "aws-org-policy-get":
            return_results(policy_get_command(args, aws_client))
        elif command == "aws-org-policy-delete":
            return_results(policy_delete_command(args, aws_client))
        elif command == "aws-org-policy-attach":
            return_results(policy_attach_command(args, aws_client))
        elif command == "aws-org-policy-target-list":
            return_results(policy_target_list_command(args, aws_client))
        elif command == "aws-org-resource-tag-add":
            return_results(resource_tag_add_command(args, aws_client))
        elif command == "aws-org-resource-tag-list":
            return_results(resource_tag_list_command(args, aws_client))
        else:
            raise NotImplementedError(f"AWS-Organizations error: command {command!r} is not implemented")

    except Exception as error:
        demisto.debug(f"{error.args=}")
        return_error(f"Failed to execute {command!r}.\n{error}")


""" ENTRY POINT """

if __name__ in ("__main__", "__builtin__", "builtins"):  # pragma: no cover
    main()