AWS - IAM

Amazon Web Services Identity and Access Management (IAM).

IT Services · AWS - IAM

Details

IDAWS - IAM
ProviderAmazon
CategoryIT Services
From Version5.0.0
Docker Imagedemisto/boto3py3:1.0.0.10221838
Supported ModulesAgentix Cloud Runtime Security Cloud Posture Security XSIAM EDR Cortex Cloud

README

Amazon Web Services Identity and Access Management (IAM)

For detailed instructions about setting up authentication, see: AWS Integrations - Authentication.

Configure AWS - IAM in Cortex

Parameter Description Required
roleArn Role Arn False
roleSessionName Role Session Name False
defaultRegion AWS Default Region False
sessionDuration Role Session Duration False
access_key Access Key False
secret_key Secret Key False
timeout The time in seconds till 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 second 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
insecure Trust any certificate (not secure) False
proxy 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-iam-create-user


Creates a new IAM user for your AWS account.

Base Command

aws-iam-create-user

Input

Argument Name Description Required
userName The name of the user to create. Required
path The path for the user name. This parameter is optional. If it is not included, it defaults to a slash (/). 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.IAM.Users.UserName string The friendly name identifying the user.
AWS.IAM.Users.UserId string The stable and unique string identifying the user.
AWS.IAM.Users.Arn string The Amazon Resource Name (ARN) that identifies the user.
AWS.IAM.Users.CreateDate date The date and time, when the user was created.
AWS.IAM.Users.Path string The path to the user.

Command Example

!aws-iam-create-user userName=Test path=/testusers/

aws-iam-get-user


Retrieves information about the specified IAM user, including the user’s creation date, path, unique ID, and ARN.

Base Command

aws-iam-get-user

Input

Argument Name Description Required
userName The name of the user to get information 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.IAM.Users.UserName string The friendly name identifying the user.
AWS.IAM.Users.UserId string The stable and unique string identifying the user.
AWS.IAM.Users.Arn string The Amazon Resource Name (ARN) that identifies the user.
AWS.IAM.Users.CreateDate date The date and time when the user was created.
AWS.IAM.Users.Path string The path to the user.
AWS.IAM.Users.PasswordLastUsed date The date and time, when the user’s password was last used to sign in to an AWS website.

Command Example

!aws-iam-get-user userName=test

aws-iam-list-users


Lists the IAM users, returns all users in the AWS account.

Base Command

aws-iam-list-users

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.IAM.Users.UserName string The friendly name identifying the user.
AWS.IAM.Users.UserId string The stable and unique string identifying the user.
AWS.IAM.Users.Arn string The Amazon Resource Name (ARN) that identifies the user.
AWS.IAM.Users.CreateDate date The date and time when the user was created.
AWS.IAM.Users.Path string The path to the user.
AWS.IAM.Users.PasswordLastUsed date The date and time when the password was last used.

Command Example


### aws-iam-update-user

***
Updates the name and/or the path of the specified IAM user.

#### Base Command

`aws-iam-update-user`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| oldUserName | Name of the user to update. | Required |
| newUserName | New name for the user. Include this parameter only if you're changing the user's name. | Optional |
| newPath | New path for the IAM user. Include this parameter only if you're changing the user's path. | 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-iam-update-user oldUserName=test newUserName=NewUserName34 newPath=/iamtest/```

### aws-iam-delete-user

***
Deletes the specified IAM user. The user must not belong to any groups or have any access keys, signing certificates, or attached policies.

#### Base Command

`aws-iam-delete-user`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user 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-iam-delete-user userName=userName34```

### aws-iam-update-login-profile

***
Changes the password for the specified IAM user.

#### Base Command

`aws-iam-update-login-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user whose password you want to update. | Required |
| newPassword | The new password for the specified IAM user. | Required |
| passwordResetRequired | Allows this new password to be used only once by requiring the specified IAM user to set a new password on next sign-in. Possible values are: True, False. | 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-iam-update-login-profile userName=userName34 newPassword=ArdVaEC@1#$F%g% passwordResetRequired=True raw-response=true```

### aws-iam-create-group

***
Creates a new iam group.

#### Base Command

`aws-iam-create-group`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| groupName | The name of the group to create. Do not include the path in this value. | Optional |
| path | The path to the group. | 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.IAM.Groups.GroupName | string | The friendly name that identifies the group. |
| AWS.IAM.Groups.GroupId | string | The stable and unique string identifying the group. |
| AWS.IAM.Groups.Arn | string | The Amazon Resource Name \(ARN\) specifying the group. |
| AWS.IAM.Groups.CreateDate | date | The date and time when the group was created. |
| AWS.IAM.Groups.Path | string | The path to the group. |

#### Command Example

```!aws-iam-create-group groupName=test path=/testgroups/```

### aws-iam-list-groups

***
Lists all the IAM groups in the AWS account

#### Base Command

`aws-iam-list-groups`

#### 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.IAM.Groups.GroupName | string | The friendly name that identifies the group. |
| AWS.IAM.Groups.GroupId | string | The stable and unique string identifying the group. |
| AWS.IAM.Groups.Arn | string | The Amazon Resource Name \(ARN\) specifying the group. |
| AWS.IAM.Groups.CreateDate | date | The date and time when the group was created. |
| AWS.IAM.Groups.Path | string | The path to the group. |

#### Command Example

```!aws-iam-list-groups```

### aws-iam-list-groups-for-user

***
Lists the IAM groups that the specified IAM user belongs to.

#### Base Command

`aws-iam-list-groups-for-user`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user to list groups for. | 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.IAM.Users.Groups.GroupName | string | The friendly name that identifies the group. |
| AWS.IAM.Users.Groups.GroupId | string | The stable and unique string identifying the group |
| AWS.IAM.Users.Groups.Arn | string | The Amazon Resource Name \(ARN\) specifying the group. |
| AWS.IAM.Users.Groups.CreateDate | date | The date and time when the group was created. |
| AWS.IAM.Users.Groups.Path | string | The path to the group. |

#### Command Example

```aws-iam-list-groups-for-user userName=test```

### aws-iam-add-user-to-group

***
Adds the specified user to the specified group.

#### Base Command

`aws-iam-add-user-to-group`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user to add. | Required |
| groupName | The name of the group to update. | 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-iam-add-user-to-group userName=userName34 groupName=test```

### aws-iam-create-access-key

***
Creates a new AWS secret access key and corresponding AWS access key ID for the specified user. The default status for new keys is Active .

#### Base Command

`aws-iam-create-access-key`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the IAM user that the new key will belong to. If username is not provided, the account name configured in your integration will be used. | 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.IAM.Users.AccessKeys.AccessKeyId | string | The ID for this access key. |
| AWS.IAM.Users.AccessKeys.SecretAccessKey | string | The secret key used to sign requests. |
| AWS.IAM.Users.AccessKeys.Status | string | The status of the access key. Active means that the key is valid for API calls, while Inactive means it is not. |
| AWS.IAM.Users.AccessKeys.CreateDate | date | The date when the access key was created. |

#### Command Example

```!aws-iam-create-access-key userName=userName34```

### aws-iam-update-access-key

***
Changes the status of the specified access key from Active to Inactive, or vice versa. This operation can be used to disable a user's key as part of a key rotation workflow.

#### Base Command

`aws-iam-update-access-key`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user whose key you want to update. If username is not provided, the account name configured in your integration . | Optional |
| accessKeyId | The access key ID of the secret access key you want to update. | Required |
| status | The status you want to assign to the secret access key. Active means that the key can be used for API calls to AWS, while Inactive means that the key cannot be used. Possible values are: Active, Inactive. | 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-iam-update-access-key userName=test accessKeyId=AKIAJSFAUQ7EDFPN7Y2D2A status=Inactive```

### aws-iam-list-access-keys-for-user

***
Returns information about the access key IDs associated with the specified IAM user.

#### Base Command

`aws-iam-list-access-keys-for-user`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user. | 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.IAM.Users.AccessKeys.AccessKeyId | string | The ID for this access key. |
| AWS.IAM.Users.AccessKeys.Status | string | The status of the access key. Active means the key is valid for API calls; Inactive means it is not. |
| AWS.IAM.Users.AccessKeys.CreateDate | date | The date when the access key was created. |
| AWS.IAM.Users.AccessKeys.UserName | string | The name of the IAM user that the key is associated with. |

#### Command Example

```!aws-iam-list-access-keys-for-user userName=userName34```

### aws-iam-list-policies

***
Lists all the managed policies that are available in your AWS account, including your own customer-defined managed policies and all AWS managed policies.

#### Base Command

`aws-iam-list-policies`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| scope | The scope to use for filtering the results. To list only AWS managed policies, set Scope to AWS. To list only the customer managed policies in your AWS account, set Scope to Local. Possible values are: All, AWS, Local. Default is All. | Optional |
| onlyAttached | A flag to filter the results to only the attached policies.  When OnlyAttached is true , the returned list contains only the policies that are attached to an IAM user, group, or role. When OnlyAttached is false , or when the parameter is not included, all policies are returned. Possible values are: True, False. Default is False. | 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.IAM.Policies.PolicyName | string | The friendly name \(not ARN\) identifying the policy. |
| AWS.IAM.Policies.PolicyId | string | The stable and unique string identifying the policy. |
| AWS.IAM.Policies.Arn | string | The Amazon Resource Name \(ARN\). |
| AWS.IAM.Policies.Path | string | The path to the policy. |
| AWS.IAM.Policies.DefaultVersionId | string | The identifier for the version of the policy that is set as the default version. |
| AWS.IAM.Policies.IsAttachable | string | Specifies whether the policy can be attached to an IAM user, group, or role. |
| AWS.IAM.Policies.CreateDate | date | when the policy was created. |
| AWS.IAM.Policies.UpdateDate | date | when the policy was last updated. |
| AWS.IAM.Policies.AttachmentCount | number | The number of entities \(users, groups, and roles\) that the policy is attached to. |

#### Command Example

```!aws-iam-list-policies scope=AWS onlyAttached=True```

### aws-iam-list-roles

***
Lists all IAM roles

#### Base Command

`aws-iam-list-roles`

#### 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.IAM.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.Roles.CreateDate | date | The date and time when the role was created. |
| AWS.IAM.Roles.Path | string | The path to the role. |
| AWS.IAM.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. Anyone who uses the AWS CLI or API to assume the role can specify the duration using the optional DurationSeconds API parameter or duration-seconds CLI parameter. |

#### Command Example

```!aws-iam-list-roles```

### aws-iam-attach-policy

***
Attaches the specified managed policy to the specified IAM Entity.

#### Base Command

`aws-iam-attach-policy`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| type | The Type of IAM Entity. Possible values are: User, Group, Role. | Required |
| entityName | The name (friendly name, not ARN) of the IAM Entity to attach the policy to. | Optional |
| policyArn | The Amazon Resource Name (ARN) of the IAM policy you want to attach. | Optional |

#### Context Output

There is no context output for this command.

#### Command Example

```!aws-iam-attach-policy type=User entityName=userName34 policyArn=arn:aws:iam::aws:policy/AmazonSQSFullAccess```

### aws-iam-detach-policy

***
Removes the specified managed policy from the specified IAM Entity.

#### Base Command

`aws-iam-detach-policy`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| type | IAM Entity Type. Possible values are: User, Group, Role. | Required |
| entityName | The name (friendly name, not ARN) of the IAM Entity to detach the policy from. | Optional |
| policyArn | The Amazon Resource Name (ARN) of the IAM policy you want to detach. | 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-iam-detach-policy type=User entityName=userName34 policyArn=arn:aws:iam::aws:policy/AmazonSQSFullAccess```

### aws-iam-delete-login-profile

***
Deletes the password for the specified IAM user, which terminates the user's ability to access AWS services through the AWS Management Console.

#### Base Command

`aws-iam-delete-login-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user whose password 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-iam-delete-login-profile userName=userName34```

### aws-iam-delete-group

***
Deletes the specified IAM group. The group must not contain any users or have any attached policies.

#### Base Command

`aws-iam-delete-group`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| groupName | The name of the IAM group 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-iam-delete-group groupName=Group123```

### aws-iam-remove-user-from-group

***
Removes the specified user from the specified group.

#### Base Command

`aws-iam-remove-user-from-group`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the user to remove. | Required |
| groupName | The name of the group to update. | 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-iam-remove-user-from-group userName=userName34 groupName=Group123```

### aws-iam-create-login-profile

***
Creates a password for the specified user, giving the user the ability to access AWS services through the AWS Management Console.

#### Base Command

`aws-iam-create-login-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | The name of the IAM user to create a password for. The user must already exist. | Required |
| password | The new password for the user. | Required |
| passwordResetRequired | Specifies whether the user is required to set a new password on next sign-in. Possible values are: True, False. | 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-iam-create-login-profile userName=userName34 password=Avd#sdf$12VB6*cvg passwordResetRequired=True```

### aws-iam-delete-access-key

***
Deletes the access key pair associated with the specified IAM user.

#### Base Command

`aws-iam-delete-access-key`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| userName | he name of the user whose access key pair you want to delete. If username is not provided, the account name configured in your integration will be used. | Optional |
| AccessKeyId | The access key ID for the access key ID and secret access key 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-iam-delete-access-key userName=userName34 AccessKeyId=ABCDEFGGHDJQ7E7X5PADN7Y2D2A```

### aws-iam-create-instance-profile

***
Creates a new instance profile.

#### Base Command

`aws-iam-create-instance-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| instanceProfileName | The name of the instance profile to create. | Required |
| path | The path to the instance profile. | 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.IAM.InstanceProfiles.Path | string | The path to the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileName | string | The name identifying the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileId | string | The stable and unique string identifying the instance profile. |
| AWS.IAM.InstanceProfiles.Arn | string | The Amazon Resource Name \(ARN\) specifying the instance profile. |
| AWS.IAM.InstanceProfiles.CreateDate | date | The date when the instance profile was created. |

#### Command Example

```!aws-iam-create-instance-profile instanceProfileName=testprofile path=/test/```

### aws-iam-delete-instance-profile

***
Deletes the specified instance profile. The instance profile must not have an associated role.

#### Base Command

`aws-iam-delete-instance-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| instanceProfileName | The name of the instance profile 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-iam-delete-instance-profile instanceProfileName=testprofile```

### aws-iam-list-instance-profiles

***
Lists all the instance profiles tin your AWS account.

#### Base Command

`aws-iam-list-instance-profiles`

#### 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.IAM.InstanceProfiles.Path | string | The path to the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileName | string | The name identifying the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileId | string | The stable and unique string identifying the instance profile. |
| AWS.IAM.InstanceProfiles.Arn | string | The Amazon Resource Name \(ARN\) specifying the instance profile. |
| AWS.IAM.InstanceProfiles.CreateDate | date | The date when the instance profile was created. |
| AWS.IAM.InstanceProfiles.Roles.Path | string | The path to the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.InstanceProfiles.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.InstanceProfiles.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.InstanceProfiles.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.InstanceProfiles.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.InstanceProfiles.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |

#### Command Example

```!aws-iam-list-instance-profiles```

### aws-iam-add-role-to-instance-profile

***
Adds the specified IAM role to the specified instance profile. An instance profile can contain only one role, and this limit cannot be increased. You can remove the existing role and then add a different role to an instance profile.

#### Base Command

`aws-iam-add-role-to-instance-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| instanceProfileName | The name of the instance profile to update. | Required |
| roleName | The name of the role to add. | 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.IAM.InstanceProfiles.Path | string | The path to the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileName | string | The name identifying the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileId | string | The stable and unique string identifying the instance profile. |
| AWS.IAM.InstanceProfiles.Arn | string | The Amazon Resource Name \(ARN\) specifying the instance profile. |
| AWS.IAM.InstanceProfiles.CreateDate | date | The date when the instance profile was created. |
| AWS.IAM.InstanceProfiles.Roles.Path | string | The path to the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.InstanceProfiles.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.InstanceProfiles.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.InstanceProfiles.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.InstanceProfiles.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.InstanceProfiles.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |

#### Command Example

```!aws-iam-add-role-to-instance-profile instanceProfileName=testprofile roleName=EC2ReadOnly```

### aws-iam-remove-role-from-instance-profile

***
Removes the specified IAM role from the specified EC2 instance profile.

#### Base Command

`aws-iam-remove-role-from-instance-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| instanceProfileName | The name of the instance profile to update. | Required |
| roleName | The name of the role to remove. | 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.IAM.InstanceProfiles.Path | string | The path to the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileName | string | The name identifying the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileId | string | The stable and unique string identifying the instance profile. |
| AWS.IAM.InstanceProfiles.Arn | string | The Amazon Resource Name \(ARN\) specifying the instance profile. |
| AWS.IAM.InstanceProfiles.CreateDate | date | The date when the instance profile was created. |
| AWS.IAM.InstanceProfiles.Roles.Path | string | The path to the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.InstanceProfiles.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.InstanceProfiles.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.InstanceProfiles.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.InstanceProfiles.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.InstanceProfiles.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |

#### Command Example

```!aws-iam-remove-role-from-instance-profile instanceProfileName=testprofile roleName=EC2ReadOnly```

### aws-iam-list-instance-profiles-for-role

***
Lists the instance profiles that have the specified associated IAM role.

#### Base Command

`aws-iam-list-instance-profiles-for-role`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| roleName | The name of the role to list instance profiles for. | 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.IAM.InstanceProfiles.Path | string | The path to the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileName | string | The name identifying the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileId | string | The stable and unique string identifying the instance profile. |
| AWS.IAM.InstanceProfiles.Arn | string | The Amazon Resource Name \(ARN\) specifying the instance profile. |
| AWS.IAM.InstanceProfiles.CreateDate | date | The date when the instance profile was created. |
| AWS.IAM.InstanceProfiles.Roles.Path | string | The path to the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.InstanceProfiles.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.InstanceProfiles.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.InstanceProfiles.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.InstanceProfiles.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.InstanceProfiles.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |

#### Command Example

```!aws-iam-list-instance-profiles-for-role roleName=EC2ReadOnly```

### aws-iam-get-instance-profile

***
Retrieves information about the specified instance profile.

#### Base Command

`aws-iam-get-instance-profile`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| instanceProfileName | The name of the instance profile to get information 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.IAM.InstanceProfiles.Path | string | The path to the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileName | string | The name identifying the instance profile. |
| AWS.IAM.InstanceProfiles.InstanceProfileId | string | The stable and unique string identifying the instance profile. |
| AWS.IAM.InstanceProfiles.Arn | string | The Amazon Resource Name \(ARN\) specifying the instance profile. |
| AWS.IAM.InstanceProfiles.CreateDate | date | The date when the instance profile was created. |
| AWS.IAM.InstanceProfiles.Roles.Path | string | The path to the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.InstanceProfiles.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.InstanceProfiles.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.InstanceProfiles.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.InstanceProfiles.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.InstanceProfiles.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.InstanceProfiles.Roles. MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |

#### Command Example

```!aws-iam-get-instance-profile instanceProfileName=testprofile```

### aws-iam-get-role

***
Retrieves information about the specified role.

#### Base Command

`aws-iam-get-role`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| roleName | The name of the IAM role to get information 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.IAM.Roles.Path | string | The path to the role. |
| AWS.IAM.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.Roles.AssumeRolePolicyDocument | string | The policy that grants an entity permission to assume the role. |
| AWS.IAM.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |
| AWS.IAM.Roles.Tags.Key | string | The tag key. |
| AWS.IAM.Roles.Tags.Value | string | The tag value. |

#### Command Example

```!aws-iam-get-role roleName=ec2readonly```

### aws-iam-delete-role

***
Deletes the specified role. The role must not have any policies attached.

#### Base Command

`aws-iam-delete-role`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| roleName | The name of the role 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-iam-delete-role roleName=test-role```

### aws-iam-create-role

***
Creates a new role for your AWS account.

#### Base Command

`aws-iam-create-role`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| roleName | The name of the role to create. | Required |
| assumeRolePolicyDocument | The trust relationship policy document that grants an entity permission to assume the role. | Required |
| path | The path to the role. | Optional |
| description | A description of the role. | Optional |
| maxSessionDuration | The maximum session duration (in seconds) that you want to set for the specified role. If you do not specify a value for this setting, the default maximum of one hour is applied. This setting can have a value from 1 hour to 12 hours. | 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.IAM.Roles.RoleName | string | The friendly name that identifies the role. |
| AWS.IAM.Roles.RoleId | string | The stable and unique string identifying the role. |
| AWS.IAM.Roles.Arn | string | The Amazon Resource Name \(ARN\) specifying the role. |
| AWS.IAM.Roles.CreateDate | date | The date and time, when the role was created. |
| AWS.IAM.Roles.Path | string | The path to the role. |
| AWS.IAM.Roles.AssumeRolePolicyDocument | string | he policy that grants an entity permission to assume the role. |
| AWS.IAM.Roles.Description | string | A description of the role that you provide. |
| AWS.IAM.Roles.MaxSessionDuration | number | The maximum session duration \(in seconds\) for the specified role. |

#### Command Example

!aws-iam-create-role roleName=testrole assumeRolePolicyDocument="{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}" description="a test role"   ```

aws-iam-create-policy


Creates a new managed policy for your AWS account. This operation creates a policy version with a version identifier of v1 and sets v1 as the policy’s default version.

Base Command

aws-iam-create-policy

Input

Argument Name Description Required
policyName The friendly name of the policy. Required
policyDocument The JSON policy document that you want to use as the content for the new policy. Required
path The path for the policy. Optional
description A friendly description of the policy. 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.IAM.Policies.PolicyName string The friendly name (not ARN) identifying the policy.
AWS.IAM.Policies.PolicyId string The stable and unique string identifying the policy.
AWS.IAM.Policies.Arn string The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources.
AWS.IAM.Policies.Path string The path to the policy.
AWS.IAM.Policies.DefaultVersionId string The identifier for the version of the policy that is set as the default version.
AWS.IAM.Policies.AttachmentCount number The number of entities (users, groups, and roles) that the policy is attached to.
AWS.IAM.Policies.PermissionsBoundaryUsageCount number The number of entities (users and roles) for which the policy is used to set the permissions boundary.
AWS.IAM.Policies.IsAttachable boolean Specifies whether the policy can be attached to an IAM user, group, or role.
AWS.IAM.Policies.Description string A friendly description of the policy.
AWS.IAM.Policies.CreateDate date The date and time, in ISO 8601 date-time format , when the policy was created.
AWS.IAM.Policies.UpdateDate date The date and time, in ISO 8601 date-time format , when the policy was last updated.

Command Example

!aws-iam-create-policy policyName=test-policy policyDocument="{  
"Version": "2012-10-17",  
"Statement": \[  
{  
"Sid": "VisualEditor0",  
"Effect": "Allow",  
"Action": "guardduty:CreateIPSet",  
"Resource": "arn:aws:guardduty:_:_:detector/_"  
},  
{  
"Sid": "VisualEditor1",  
"Effect": "Allow",  
"Action": "guardduty:CreateDetector",  
"Resource": "_"  
}  
\]  
}"

aws-iam-delete-policy


Deletes the specified managed policy. Before you can delete a managed policy, you must first detach the policy from all users, groups, and roles that it is attached to. In addition you must delete all the policy’s versions.

Base Command

aws-iam-delete-policy

Input

Argument Name Description Required
policyArn The Amazon Resource Name (ARN) of the IAM policy 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-iam-delete-policy policyArn=arn:aws:iam::123456789:policy/test-policy

aws-iam-create-policy-version


Creates a new version of the specified managed policy. To update a managed policy, you create a new policy version. A managed policy can have up to five versions. If the policy has five versions, you must delete an existing version using DeletePolicyVersion before you create a new version. Optionally, you can set the new version as the policy’s default version. The default version is the version that is in effect for the IAM users, groups, and roles to which the policy is attached.

Base Command

aws-iam-create-policy-version

Input

Argument Name Description Required
policyArn The Amazon Resource Name (ARN) of the IAM policy to which you want to add a new version. Required
policyDocument The JSON policy document that you want to use as the content for this new version of the policy. Required
setAsDefault Specifies whether to set this version as the policy’s default version. Possible values are: True, False. 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.IAM.Policies.Versions.Document string The policy document.
AWS.IAM.Policies.Versions.VersionId string The identifier for the policy version.
AWS.IAM.Policies.Versions.IsDefaultVersion string The identifier for the policy version.
AWS.IAM.Policies.Versions.CreateDate string The date and time, in ISO 8601 date-time format , when the policy version was created.

Command Example

!aws-iam-create-policy-version policyArn=arn:aws:iam::123456789:policy/test-policy policyDocument="{  
"Version": "2012-10-17",  
"Statement": \[  
{  
"Sid": "VisualEditor0",  
"Effect": "Allow",  
"Action": "guardduty:CreateIPSet",  
"Resource": "arn:aws:guardduty:_:_:detector/_"  
},  
{  
"Sid": "VisualEditor1",  
"Effect": "Allow",  
"Action": "guardduty:CreateDetector",  
"Resource": "_"  
}  
\]  
}" setAsDefault=True

aws-iam-delete-policy-version


Deletes the specified version from the specified managed policy. You cannot delete the default version from a policy using this API. To delete the default version from a policy, use DeletePolicy . To find out which version of a policy is marked as the default version, use ListPolicyVersions .

Base Command

aws-iam-delete-policy-version

Input

Argument Name Description Required
policyArn The Amazon Resource Name (ARN) of the IAM policy from which you want to delete a version. Required
versionId The policy version 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-iam-delete-policy-version policyArn=arn:aws:iam::123456789:policy/test-policy versionId=v1

aws-iam-list-policy-versions


Lists information about the versions of the specified managed policy, including the version that is currently set as the policy’s default version.

Base Command

aws-iam-list-policy-versions

Input

Argument Name Description Required
policyArn The Amazon Resource Name (ARN) of the IAM policy for which you want the versions. Required

Context Output

Path Type Description
AWS.IAM.Policies.Versions.Document string The policy document.
AWS.IAM.Policies.Versions.VersionId string The identifier for the policy version.
AWS.IAM.Policies.Versions.IsDefaultVersion boolean Specifies whether the policy version is set as the policy’s default version.
AWS.IAM.Policies.Versions.CreateDate date The date and time, in ISO 8601 date-time format , when the policy version was created.

Command Example

!aws-iam-list-policy-versions policyArn=arn:aws:iam::123456789:policy/test-policy

aws-iam-get-policy-version


Retrieves information about the specified version of the specified managed policy, including the policy document.

Base Command

aws-iam-get-policy-version

Input

Argument Name Description Required
policyArn The Amazon Resource Name (ARN) of the managed policy that you want information about. Required
versionId Identifies the policy version to retrieve. 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.IAM.Policies.Versions.Document unknown The policy document.
AWS.IAM.Policies.Versions.VersionId unknown The identifier for the policy version.
AWS.IAM.Policies.Versions.IsDefaultVersion unknown Specifies whether the policy version is set as the policy’s default version.
AWS.IAM.Policies.Versions.CreateDate unknown The date and time, in ISO 8601 date-time format , when the policy version was created.

Command Example

!aws-iam-get-policy-version policyArn=arn:aws:iam::123456789:policy/test-policy versionId=v3

aws-iam-set-default-policy-version


Sets the specified version of the specified policy as the policy’s default (operative) version. This operation affects all users, groups, and roles that the policy is attached to.

Base Command

aws-iam-set-default-policy-version

Input

Argument Name Description Required
policyArn The Amazon Resource Name (ARN) of the IAM policy whose default version you want to set. Required
versionId The version of the policy to set as the default (operative) version. 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-iam-set-default-policy-version policyArn=arn:aws:iam::123456789:policy/test-policy versionId=v2

aws-iam-create-account-alias


Creates an alias for your AWS account.

Base Command

aws-iam-create-account-alias

Input

Argument Name Description Required
accountAlias The account alias to create. 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-iam-create-account-alias accountAlias=test-alias

aws-iam-delete-account-alias


Deletes the specified AWS account alias.

Base Command

aws-iam-delete-account-alias

Input

Argument Name Description Required
accountAlias The name of the account alias 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-iam-delete-account-alias accountAlias=demisto-test-alias

aws-iam-get-account-password-policy


Get AWS account’s password policy

Base Command

aws-iam-get-account-password-policy

Input

| Argument Name | Description | Required |
| — | — | — |

Context Output

Path Type Description
AWS.IAM.PasswordPolicy Unknown Account’s password policy.

aws-iam-update-account-password-policy


Create/update password policy

Base Command

aws-iam-update-account-password-policy

Input

Argument Name Description Required
minimumPasswordLength The minimum number of characters allowed in an IAM user password. Possible values are: . Optional
requireSymbols Specifies whether IAM user passwords must contain at least one of the non-alphanumeric characters. Can be “True” or “False”. Possible values are: True, False. Optional
requireNumbers Specifies whether IAM user passwords must contain at least one numeric character (0 to 9). Can be “True” or “False”. Possible values are: True, False. Optional
requireUppercaseCharacters Specifies whether IAM user passwords must contain at least one uppercase character from the ISO basic Latin alphabet (A to Z). Can be “True” or “False”. Possible values are: True, False. Optional
requireLowercaseCharacters Specifies whether IAM user passwords must contain at least one lowercase character from the ISO basic Latin alphabet (a to z). Can be “True” or “False”. Possible values are: True, False. Optional
allowUsersToChangePassword Allows all IAM users in your account to use the AWS Management Console to change their own passwords. Can be “True” or “False”. Possible values are: True, False. Optional
maxPasswordAge The number of days that an IAM user password is valid. Possible values are: . Optional
passwordReusePrevention Specifies the number of previous passwords that IAM users are prevented from reusing. Possible values are: . Optional
hardExpiry Prevents IAM users from setting a new password after their password has expired. Can be “True” or “False”. Possible values are: True, False. Optional

Context Output

There is no context output for this command.

aws-iam-list-role-policies


Lists the names of the inline policies that are embedded in the specified IAM role.

Base Command

aws-iam-list-role-policies

Input

Argument Name Description Required
roleName The name of the role to list policies for. Required

Context Output

Path Type Description
AWS.IAM.Roles.RoleName.Policies Unknown A list of policy names.

Command Example

!aws-iam-list-role-policies roleName=test-RoleARN

aws-iam-get-role-policy


Retrieves the specified inline policy document that is embedded with the specified IAM role.

Base Command

aws-iam-get-role-policy

Input

Argument Name Description Required
roleName The name of the role associated with the policy. Required
policyName The name of the policy document to get. Required

Context Output

Path Type Description
AWS.IAM.Roles.PolicyDocument string The policy document.

Command Example

!aws-iam-get-role-policy roleName=test-RoleARN policyName=testPolicy

aws-iam-get-policy


Retrieves information about the specified managed policy, including the policy’s default version and the total number of
IAM users, groups, and roles to which the policy is attached.

Base Command

aws-iam-get-policy

Input

Argument Name Description Required
policyName The Amazon Resource Name (ARN) of the managed policy that you want information about. Required

Context Output

Path Type Description
AWS.IAM.Policy.PolicyName string The friendly name (not ARN) identifying the policy.
AWS.IAM.Policy.PolicyId string The stable and unique string identifying the policy.
AWS.IAM.Policy.Arn string The Amazon Resource Name (ARN). ARNs are unique identifiers for Amazon Web Services resources.
AWS.IAM.Policy.Path string The path to the policy.
AWS.IAM.Policy.Description string A friendly description of the policy.

Command Example

!aws-iam-get-policy policyName=testPolicy

aws-iam-list-user-policies


Lists the names of the inline policies embedded in the specified IAM user.

Base Command

aws-iam-list-user-policies

Input

Argument Name Description Required
userName The name (friendly name, not ARN) of the user to list inline policies for. Required
limit Number of results to display. Default value is 50. Optional
page Page number you would like to view. Each page contains page_size values. Must be used along with page_size. Optional
page_size Number of results per page to display. Optional
marker Starting item of the next page to view. Can be retrieved from context (AttachedPoliciesMarker). Optional

Context Output

Path Type Description
AWS.IAM.UserPolicies.UserName string A list of the user’s inline policy names.
AWS.IAM.UserPolicies.PolicyName string The name of the policy.
AWS.IAM.Users.InlinePoliciesMarker string First element of next page of items.

Command Example

!aws-iam-list-user-policies userName=testUser

aws-iam-list-attached-user-polices


Lists all managed policies that are attached to the specified IAM user.

Base Command

aws-iam-list-attached-user-policies

Input

Argument Name Description Required
userName The name (friendly name, not ARN) of the user to list attached policies for. Required
limit Number of results to display. Default value is 50. Optional
page Page number you would like to view. Each page contains page_size values. Must be used along with page_size. Optional
page_size Number of results per page to display. Optional
marker Starting item of the next page to view. Can be retrieved from context (AttachedPoliciesMarker). Optional

Context Output

Path Type Description
AWS.IAM.AttachedUserPolicies.UserName string The name (friendly name, not ARN) of the user to list attached policies for.
AWS.IAM.AttachedUserPolicies.PolicyName string Policy Name
AWS.IAM.AttachedUserPolicies.PolicyArn string The Amazon Resource Name (ARN) of the attached policy.
AWS.IAM.Users.AttachedPoliciesMarker string First element of next page of items.

Command Example

!aws-iam-list-attached-user-policies userName=testUser

aws-iam-list-attached-group-policies


Lists all managed policies that are attached to the specified IAM group.

Base Command

aws-iam-list-attached-group-policies

Input

Argument Name Description Required
groupName The name (friendly name, not ARN) of the group to list attached policies for. Required
limit Number of results to display. Default value is 50. Optional
page Page number you would like to view. Each page contains page_size values. Must be used along with page_size. Optional
page_size Number of results per page to display. Optional
marker Starting item of the next page to view. Can be retrieved from context (AttachedPoliciesMarker). Optional

Context Output

Path Type Description
AWS.IAM.AttachedGroupPolicies.GroupName string The name (friendly name, not ARN) of the group to list attached policies for.
AWS.IAM.AttachedGroupPolicies.PolicyName string Policy Name
AWS.IAM.AttachedGroupPolicies.PolicyArn string The Amazon Resource Name (ARN) of the attached policy.
AWS.IAM.Groups.AttachedPoliciesMarker string First element of next page of items.

Command Example

!aws-iam-list-attached-group-policies groupName=testGroup

aws-iam-get-user-login-profile


Lists all managed policies that are attached to the specified IAM user.

Base Command

aws-iam-get-user-login-profile

Input

Argument Name Description Required
userName The name (friendly name, not ARN) of the user to retrieve login profile for. Required

Context Output

Path Type Description
AWS.IAM.Users.LoginProfile.CreateDate date The date when the password for the user was created.
AWS.IAM.Users.LoginProfile.PasswordResetRequired boolean Specifies whether the user is required to set a new password on next sign-in.

Command Example

!aws-iam-get-user-login-profile userName=testUser

aws-iam-put-role-policy


Adds or updates an inline policy document that is embedded in the specified IAM role.

Base Command

aws-iam-put-role-policy

Input

Argument Name Description Required
policyDocument The policy document. You must provide policies in JSON format in IAM. Required
policyName The name of the policy document. Required
roleName The name of the role to associate the policy with. Required

Human Readable Output

Policy {policy_name} was added to role {role_name}

Context Output

There is no context output for this command.

aws-iam-put-user-policy


Adds or updates an inline policy document that is embedded in the specified IAM user.

Base Command

aws-iam-put-user-policy

Input

Argument Name Description Required
policyDocument The policy document. You must provide policies in JSON format in IAM. Required
policyName The name of the policy document. Required
userName The name of the user to associate the policy with. Required

Context Output

There is no context output for this command.

Human Readable Output

Policy {policy_name} was added to role {user_name}

aws-iam-put-group-policy


Adds or updates an inline policy document that is embedded in the specified IAM group.

Base Command

aws-iam-put-group-policy

Input

Argument Name Description Required
policyDocument The policy document. You must provide policies in JSON format in IAM. Required
policyName The name of the policy document. Required
groupName The name of the group to associate the policy with. Required

Context Output

There is no context output for this command.

Human Readable Output

Policy {policy_name} was added to role {group_name}

aws-iam-tag-role


Adds one or more tags to an IAM role. The role can be a regular role or a service-linked role. If a tag with the same key name already exists, then that tag is overwritten with the new value.

Base Command

aws-iam-tag-role

Input

Argument Name Description Required
roleName The name of the IAM role to which you want to add tags. Required
tags A comma-separated list of Key:Value tag objects. Required

Context Output

There is no context output for this command.

Human Readable Output

Added the following tags to role {role_name}

Key Value
Key Value

aws-iam-tag-user


Adds one or more tags to an IAM user. If a tag with the same key name already exists, then that tag is overwritten with the new value.

Base Command

aws-iam-tag-user

Input

Argument Name Description Required
userName The name of the IAM user to which you want to add tags. Required
tags A comma-separated list of Key:Value tag objects. Required

Context Output

There is no context output for this command.

Human Readable Output

Added the following tags to user {user_name}

Key Value
Key Value

aws-iam-untag-user


Removes the specified tags from the user.

Base Command

aws-iam-untag-user

Input

Argument Name Description Required
userName The name of the IAM role to which you want to untag. Required
tagKeys A comma-separated list of tag keys. Required

Context Output

There is no context output for this command.

Human Readable Output

Untagged the following tags from user {user_name}

Removed keys
Key1

aws-iam-untag-role


Removes the specified tags from the role.

Base Command

aws-iam-untag-role

Input

Argument Name Description Required
roleName The name of the IAM role to which you want to untag. Required
tagKeys A comma-separated list of tag keys. Required

Context Output

There is no context output for this command.

Human Readable Output

Untagged the following tags from role {role_name}

Removed keys
Key1

aws-iam-get-access-key-last-used


Retrieves information about when the specified access key was last used. The information includes the date and time of last use, along with the AWS service and region that were specified in the last request made with that key.

Base Command

aws-iam-get-access-key-last-used

Input

Argument Name Description Required
accessKeyId The identifier of an access key. Required

Context Output

Path Type Description
AWS.IAM.AccessKey.ID string The access key ID.
AWS.IAM.AccessKey.UserName string The username owning the given access key.
AWS.IAM.AccessKey.LastUsedServiceName string The name of the service that last used the given access key.
AWS.IAM.AccessKey.LastUsedRegion string The name of the region where the given access key was last used.
AWS.IAM.AccessKey.LastUsedDate string The date when the given access key was last used.

Human Readable Output

Found the following information about access key access_Key_Id

ID UserName LastUsedDate LastUsedServiceName LastUsedRegion
access_Key_Id user_name 2023-06-06T14:32:00 test Here

aws-iam-list-attached-role-policies


List all managed policies that are attached to the specified IAM role.

Base Command

aws-iam-list-attached-role-policies

Input

Argument Name Description Required
roleName The name (friendly name, not ARN) of the role to list attached policies for. Required
pathPrefix The path prefix for filtering the results. This parameter is optional. If it is not included, it defaults to a slash (/), listing all policies. Optional
maxItems The maximum number of items to return in the command’s output. Optional
marker Use this parameter only when paginating results and only after you receive a response indicating that the results are truncated. Set it to the value of the Marker element in the response that you received to indicate where the next call should start. Optional

Context Output

Path Type Description
AWS.IAM.Roles.AttachedPolicies.Policies.PolicyName string The policy name.
AWS.IAM.Roles.AttachedPolicies.Policies.PolicyArn string The policy ARN.
AWS.IAM.Roles.AttachedPolicies.Policies.RoleName string The queried role name.
AWS.IAM.Roles.AttachedPolicies.Query.IsTruncated Boolean Whether there are more items to return. If the results were truncated, make a subsequent pagination request using the Marker request parameter to retrieve more items. Note that IAM might return fewer than the MaxItems number of results even when there are more results available. AWS recommends checking IsTruncated after every call to ensure that all results are received.
AWS.IAM.Roles.AttachedPolicies.Query.Marker string When IsTruncated is true, this element is present and contains the value to use for the Marker parameter in a subsequent pagination request.

Command example

!aws-iam-list-attached-role-policies roleName=myRoleName

Context Example

{
    "AWS": {
        "IAM": {
            "Roles": {
                "AttachedPolicies": {
                    "Policies": [
                        {
                            "PolicyArn": "arn:aws:iam::000000000000:policy/my-policy",
                            "PolicyName": "my-policy-name",
                            "RoleName": "myRoleName"
                        },
                        {
                            "PolicyArn": "arn:aws:iam::000000000001:policy/my-other-policy",
                            "PolicyName": "my-other-policy-name",
                            "RoleName": "myRoleName"
                        }
                    ],
                    "Query": {
                        "IsTruncated": false
                    }
                }
            }
        }
    }
}

Human Readable Output

Results

Attached Policies for Role myRoleName

PolicyArn PolicyName RoleName
arn:aws:iam::000000000000:policy/my-policy my-policy-name myRoleName
arn:aws:iam::000000000001:policy/my-other-policy my-other-policy-name myRoleName

Listed 2 attached policies for role test-role

aws-iam-list-mfa-devices


Lists the MFA devices for an IAM user.

Base Command

aws-iam-list-mfa-devices

Input

Argument Name Description Required
userName The name of the user whose MFA devices you want to 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
marker Use this parameter only when paginating results and only after you receive a response indicating that the results are truncated. Set it to the value of the Marker element in the response that you received to indicate where the next call should start. Optional

Context Output

Path Type Description
AWS.IAM.MFADevices.Devices.UserName string The user with whom the MFA device is associated.
AWS.IAM.MFADevices.Devices.SerialNumber string The serial number that uniquely identifies the MFA device. For virtual MFA devices, the serial number is the device ARN.
AWS.IAM.MFADevices.Devices.EnableDate date The date when the MFA device was enabled for the user.
MFADevices.Devices.Marker string First element of next page of items.

aws-iam-delete-mfa-devices


Deletes a virtual MFA device.

Base Command

aws-iam-delete-mfa-devices

Input

Argument Name Description Required
serialNumber The serial number that uniquely identifies the MFA device. For virtual MFA devices, the serial number is the same as the ARN. 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.

aws-iam-deactivate-mfa-devices


Deactivates the specified MFA device and removes it from association with the user name for which it was originally enabled.

Base Command

aws-iam-deactivate-mfa-devices

Input

Argument Name Description Required
userName The name of the user whose MFA devices you want to list. Required
serialNumber The serial number that uniquely identifies the MFA device. For virtual MFA devices, the serial number is the same as the ARN. 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.

Configuration parameters

  • roleArn — Role Arn
  • roleSessionName — Role Session Name
  • defaultRegion — AWS Default Region (required)
  • sessionDuration — Role Session Duration
  • credentials — Access Key
  • access_key — Access Key
  • secret_key — Secret Key
  • timeout — Timeout
  • retries — Retries
  • sts_regional_endpoint — AWS STS Regional Endpoints
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings

Commands (66)

  • aws-iam-access-key-update-quick-action

    Immediately disables a specific IAM access key. This stops all CLI, SDK, and API-based communication for this key ID without deleting it, enabling forensic recovery or re-enabling if the key is found to be safe.

  • aws-iam-account-password-policy-update-quick-action

    Updates the password policy to require a minimum length of 14 characters, at least one lowercase letter, one uppercase letter, one symbol. Allows users to reset password, disallow reuse of the last 24 passwords and set password expiration to 90 days. It runs the aws-iam-update-account-password-policy CLI command in your AWS environment and requires the 'iam:UpdateAccountPasswordPolicy' permission.

  • aws-iam-add-role-to-instance-profile

    Adds the specified IAM role to the specified instance profile. An instance profile can contain only one role, and this limit cannot be increased. You can remove the existing role and then add a different role to an instance profile.

  • aws-iam-add-user-to-group

    Adds the specified user to the specified group.

  • aws-iam-attach-policy

    Attaches the specified managed policy to the specified IAM Entity.

  • aws-iam-create-access-key

    Creates a new AWS secret access key and corresponding AWS access key ID for the specified user. The default status for new keys is Active .

  • aws-iam-create-account-alias

    Creates an alias for your AWS account.

  • aws-iam-create-group

    Creates a new iam group.

  • aws-iam-create-instance-profile

    Creates a new instance profile.

  • aws-iam-create-login-profile

    Creates a password for the specified user, giving the user the ability to access AWS services through the AWS Management Console.

  • aws-iam-create-policy

    Creates a new managed policy for your AWS account. This operation creates a policy version with a version identifier of v1 and sets v1 as the policy's default version.

  • aws-iam-create-policy-version

    Creates a new version of the specified managed policy. To update a managed policy, you create a new policy version. A managed policy can have up to five versions. If the policy has five versions, you must delete an existing version using DeletePolicyVersion before you create a new version. Optionally, you can set the new version as the policy's default version. The default version is the version that is in effect for the IAM users, groups, and roles to which the policy is attached.

  • aws-iam-create-role

    Creates a new role for your AWS account.

  • aws-iam-create-user

    Creates a new IAM user for your AWS account.

  • aws-iam-deactivate-mfa-devices

    Deactivates the specified MFA device and removes it from association with the user name for which it was originally enabled.

  • aws-iam-delete-access-key

    Deletes the access key pair associated with the specified IAM user.

  • aws-iam-delete-account-alias

    Deletes the specified AWS account alias.

  • aws-iam-delete-group

    Deletes the specified IAM group. The group must not contain any users or have any attached policies.

  • aws-iam-delete-instance-profile

    Deletes the specified instance profile. The instance profile must not have an associated role.

  • aws-iam-delete-login-profile

    Deletes the password for the specified IAM user, which terminates the user's ability to access AWS services through the AWS Management Console.

  • aws-iam-delete-mfa-devices

    Deletes a virtual MFA device.

  • aws-iam-delete-policy

    Deletes the specified managed policy. Before you can delete a managed policy, you must first detach the policy from all users, groups, and roles that it is attached to. In addition you must delete all the policy's versions.

  • aws-iam-delete-policy-version

    Deletes the specified version from the specified managed policy. You cannot delete the default version from a policy using this API. To delete the default version from a policy, use DeletePolicy . To find out which version of a policy is marked as the default version, use ListPolicyVersions .

  • aws-iam-delete-role

    Deletes the specified role. The role must not have any policies attached.

  • aws-iam-delete-user

    Deletes the specified IAM user. The user must not belong to any groups or have any access keys, signing certificates, or attached policies.

  • aws-iam-detach-policy

    Removes the specified managed policy from the specified IAM Entity.

  • aws-iam-get-access-key-last-used

    Retrieves information about when the specified access key was last used. The information includes the date and time of last use, along with the AWS service and region that were specified in the last request made with that key.

  • aws-iam-get-account-password-policy

    Get AWS account's password policy.

  • aws-iam-get-instance-profile

    Retrieves information about the specified instance profile.

  • aws-iam-get-policy

    Retrieves information about the specified managed policy, including the policy's default version and the total number of IAM users, groups, and roles to which the policy is attached.

  • aws-iam-get-policy-version

    Retrieves information about the specified version of the specified managed policy, including the policy document.

  • aws-iam-get-role

    Retrieves information about the specified role.

  • aws-iam-get-role-policy

    Retrieves the specified inline policy document that is embedded with the specified IAM role.

  • aws-iam-get-user

    Retrieves information about the specified IAM user, including the user's creation date, path, unique ID, and ARN.

  • aws-iam-get-user-login-profile

    Retrieves the user login profile information for AWS management consle.

  • aws-iam-list-access-keys-for-user

    Returns information about the access key IDs associated with the specified IAM user.

  • aws-iam-list-attached-group-policies

    Lists all managed policies that are attached to the specified IAM group.

  • aws-iam-list-attached-role-policies

    List all managed policies that are attached to the specified IAM role.

  • aws-iam-list-attached-user-policies

    Lists all managed policies that are attached to the specified IAM user.

  • aws-iam-list-groups

    Lists all the IAM groups in the AWS account.

  • aws-iam-list-groups-for-user

    Lists the IAM groups that the specified IAM user belongs to.

  • aws-iam-list-instance-profiles

    Lists all the instance profiles tin your AWS account.

  • aws-iam-list-instance-profiles-for-role

    Lists the instance profiles that have the specified associated IAM role.

  • aws-iam-list-mfa-devices

    Lists the MFA devices for an IAM user.

  • aws-iam-list-policies

    Lists all the managed policies that are available in your AWS account, including your own customer-defined managed policies and all AWS managed policies.

  • aws-iam-list-policy-versions

    Lists information about the versions of the specified managed policy, including the version that is currently set as the policy's default version.

  • aws-iam-list-role-policies

    Lists the names of the inline policies that are embedded in the specified IAM role.

  • aws-iam-list-roles

    Lists all IAM roles.

  • aws-iam-list-user-policies

    Lists the names of the inline policies embedded in the specified IAM user.

  • aws-iam-list-users

    Lists the IAM users, returns all users in the AWS account.

  • aws-iam-login-profile-delete-quick-action

    Permanently deletes the IAM user's password (login profile). This prevents the user from signing into the AWS Management Console but does not deactivate their programmatic access keys or delete the IAM user itself.

  • aws-iam-put-group-policy

    Adds or updates an inline policy document that is embedded in the specified IAM group.

  • aws-iam-put-role-policy

    Adds or updates an inline policy document that is embedded in the specified IAM role.

  • aws-iam-put-user-policy

    Adds or updates an inline policy document that is embedded in the specified IAM user.

  • aws-iam-remove-role-from-instance-profile

    Removes the specified IAM role from the specified EC2 instance profile.

  • aws-iam-remove-user-from-group

    Removes the specified user from the specified group.

  • aws-iam-set-default-policy-version

    Sets the specified version of the specified policy as the policy's default (operative) version. This operation affects all users, groups, and roles that the policy is attached to.

  • aws-iam-tag-role

    Adds one or more tags to an IAM role. The role can be a regular role or a service-linked role. If a tag with the same key name already exists, then that tag is overwritten with the new value.

  • aws-iam-tag-user

    Adds one or more tags to an IAM user. If a tag with the same key name already exists, then that tag is overwritten with the new value.

  • aws-iam-untag-role

    Removes the specified tags from the role.

  • aws-iam-untag-user

    Removes the specified tags from the user.

  • aws-iam-update-access-key

    Changes the status of the specified access key from Active to Inactive, or vice versa. This operation can be used to disable a user's key as part of a key rotation workflow.

  • aws-iam-update-account-password-policy

    Create/update password policy.

  • aws-iam-update-login-profile

    Changes the password for the specified IAM user.

  • aws-iam-update-user

    Updates the name and/or the path of the specified IAM user.

  • aws-iam-user-policy-put-quick-action

    Attaches an inline "Deny All" policy for the specified IAM user, effectively blocking the user from performing any actions on all AWS resources.

from datetime import date, datetime

import botocore.exceptions
import demistomock as demisto  # noqa: F401
from CommonServerPython import *  # noqa: F401

SERVICE = "iam"


class DatetimeEncoder(json.JSONEncoder):
    # pylint: disable=method-hidden
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%dT%H:%M:%S")
        elif isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)


def get_limit(args):
    """
    Args:
        args: Args input for command, this function uses limit, page and page_size

    Returns:
        - limit - how many items to request from AWS - IAM API.
        - is_manual - whether manual pagination is active (using page and page_size)
        - page_size - used when manual pagination is active, to bring the relevant number of results from the data.

    """
    limit = arg_to_number(str(args.get("limit"))) if "limit" in args else None
    page = arg_to_number(str(args.get("page"))) if "page" in args else None
    page_size = arg_to_number(str(args.get("page_size"))) if "page_size" in args else None

    if limit is None:
        if page is not None and page_size is not None:
            if page <= 0:
                raise Exception("Chosen page number must be greater than 0")
            limit = page_size * page
            return limit, True, page_size
        else:
            limit = 50
    return limit, False, page_size


def create_user(args, client):  # pragma: no cover
    kwargs = {"UserName": args.get("userName")}
    if args.get("path"):
        kwargs.update({"Path": args.get("path")})

    response = client.create_user(**kwargs)
    user = response["User"]
    data = {
        "UserName": user["UserName"],
        "UserId": user["UserId"],
        "Arn": user["Arn"],
        "CreateDate": datetime.strftime(user["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
        "Path": user["Path"],
    }
    ec = {"AWS.IAM.Users": data}
    human_readable = tableToMarkdown("AWS IAM Users", data)
    return_outputs(human_readable, ec)


def create_login_profile(args, client):  # pragma: no cover
    kwargs = {"UserName": args.get("userName"), "Password": args.get("password")}
    if args.get("passwordResetRequired"):
        kwargs.update({"PasswordResetRequired": args.get("passwordResetRequired") == "True"})

    response = client.create_login_profile(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("Login Profile Was Created For user {} ".format(args.get("userName")))


def get_user(args, client):  # pragma: no cover
    try:
        response = client.get_user(UserName=args.get("userName"))
    except Exception as e:
        if "NoSuchEntity" in str(e):
            return_outputs(f'User {args.get("userName")} was not found.')
            return
        else:
            raise e

    user = response["User"]
    data = {
        "UserName": user["UserName"],
        "UserId": user["UserId"],
        "Arn": user["Arn"],
        "CreateDate": datetime.strftime(user["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
        "Path": user["Path"],
    }
    ec = {"AWS.IAM.Users": data}
    human_readable = tableToMarkdown("AWS IAM Users", data)
    return_outputs(human_readable, ec)


def list_users(args, client):  # pragma: no cover
    data = []
    paginator = client.get_paginator("list_users")
    for response in paginator.paginate():
        for user in response["Users"]:
            user_details = {
                "UserName": user["UserName"],
                "UserId": user["UserId"],
                "Arn": user["Arn"],
                "CreateDate": datetime.strftime(user["CreateDate"], "%Y-%m-%d %H:%M:%S"),
                "Path": user["Path"],
            }
            if user.get("PasswordLastUsed"):
                user_details["PasswordLastUsed"] = datetime.strftime(user["PasswordLastUsed"], "%Y-%m-%d %H:%M:%S")
            data.append(user_details)
    ec = {"AWS.IAM.Users": data}
    human_readable = tableToMarkdown("AWS IAM Users", data, removeNull=True)
    return_outputs(human_readable, ec)


def update_user(args, client):  # pragma: no cover
    kwargs = {"UserName": args.get("oldUserName")}
    if args.get("newUserName"):
        kwargs.update({"NewUserName": args.get("newUserName")})
    if args.get("newPath"):
        kwargs.update({"NewPath": args.get("newPath")})

    response = client.update_user(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("Changed UserName {} To: {}".format(args.get("oldUserName"), args.get("newUserName")))


def delete_user(args, client):  # pragma: no cover
    response = client.delete_user(UserName=args.get("userName"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The User {} has been deleted".format(args.get("userName")))


def update_login_profile(args, client):  # pragma: no cover
    user = args.get("userName")
    password = args.get("newPassword")
    reset_required = args.get("passwordResetRequired") == "True"

    request_params = {
        "UserName": user,
        "PasswordResetRequired": reset_required,
    }
    # Verify if a new password was given
    if password:
        request_params["Password"] = password

    response = client.update_login_profile(**request_params)

    # Determine success message
    if password:
        success_message = f"The user {user} password was changed"
    else:
        success_message = f"The user {user} will be required to change his password."

    if response.get("ResponseMetadata", {}).get("HTTPStatusCode") == 200:
        demisto.results(success_message)


def create_group(args, client):  # pragma: no cover
    kwargs = {"GroupName": args.get("groupName")}
    if args.get("path") is not None:
        kwargs.update({"Path": args.get("path")})

    response = client.create_group(**kwargs)
    group = response["Group"]
    data = {
        "GroupName": group["GroupName"],
        "GroupId": group["GroupId"],
        "Arn": group["Arn"],
        "CreateDate": datetime.strftime(group["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
        "Path": group["Path"],
    }
    ec = {"AWS.IAM.Groups": data}
    human_readable = tableToMarkdown("AWS IAM Groups", data)
    return_outputs(human_readable, ec)


def list_groups(args, client):  # pragma: no cover
    data = []
    paginator = client.get_paginator("list_groups")
    for response in paginator.paginate():
        for group in response["Groups"]:
            data.append(
                {
                    "GroupName": group["GroupName"],
                    "GroupId": group["GroupId"],
                    "Arn": group["Arn"],
                    "CreateDate": datetime.strftime(group["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
                    "Path": group["Path"],
                }
            )
    ec = {"AWS.IAM.Groups": data}
    human_readable = tableToMarkdown("AWS IAM Groups", data)
    return_outputs(human_readable, ec)


def list_groups_for_user(args, client):  # pragma: no cover
    data = []
    response = client.list_groups_for_user(UserName=args.get("userName"))
    for group in response["Groups"]:
        data.append(
            {
                "UserName": args.get("userName"),
                "GroupName": group["GroupName"],
                "GroupId": group["GroupId"],
                "Arn": group["Arn"],
                "CreateDate": datetime.strftime(group["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
                "Path": group["Path"],
            }
        )

    ec = {"AWS.IAM.Users(val.UserName === obj.UserName).Groups": data}
    human_readable = tableToMarkdown("AWS IAM User Groups", data)
    return_outputs(human_readable, ec)


def add_user_to_group(args, client):  # pragma: no cover
    response = client.add_user_to_group(GroupName=args.get("groupName"), UserName=args.get("userName"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The user {} was added to the IAM group: {}".format(args.get("userName"), args.get("groupName")))


def create_access_key(args, client):  # pragma: no cover
    kwargs = {}
    if user_name := args.get("userName"):
        kwargs["UserName"] = user_name
    response = client.create_access_key(**kwargs)
    AccessKey = response["AccessKey"]
    data = {
        "UserName": AccessKey["UserName"],
        "AccessKeyId": AccessKey["AccessKeyId"],
        "SecretAccessKey": AccessKey["SecretAccessKey"],
        "Status": AccessKey["Status"],
        "CreateDate": datetime.strftime(AccessKey["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
    }
    ec = {"AWS.IAM.Users(val.UserName === obj.UserName).AccessKeys": data}
    human_readable = tableToMarkdown("AWS IAM Users", data)
    return_outputs(human_readable, ec)


def update_access_key(args, client):  # pragma: no cover
    kwargs = {"AccessKeyId": args.get("accessKeyId"), "Status": args.get("status")}
    if user_name := args.get("userName"):
        kwargs["UserName"] = user_name

    response = client.update_access_key(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("Access Key with ID {} was set to status: {}".format(args.get("accessKeyId"), args.get("status")))


def list_access_key_for_user(args, client):  # pragma: no cover
    data = []
    response = client.list_access_keys(UserName=args.get("userName"))
    for accesskey in response["AccessKeyMetadata"]:
        data.append(
            {
                "UserName": accesskey["UserName"],
                "AccessKeyId": accesskey["AccessKeyId"],
                "Status": accesskey["Status"],
                "CreateDate": datetime.strftime(accesskey["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
            }
        )

    ec = {"AWS.IAM.Users(val.UserName === obj.UserName).AccessKeys": data}
    human_readable = tableToMarkdown("AWS IAM Users Access Keys", data)
    return_outputs(human_readable, ec)


def list_policies(args, client):  # pragma: no cover
    data = []
    response = client.list_policies(Scope=args.get("scope"), OnlyAttached=args.get("onlyAttached") == "True")
    for policy in response["Policies"]:
        data.append(
            {
                "PolicyName": policy["PolicyName"],
                "PolicyId": policy["PolicyId"],
                "Arn": policy["Arn"],
                "Path": policy["Path"],
                "DefaultVersionId": policy["DefaultVersionId"],
                "IsAttachable": policy["IsAttachable"],
                "AttachmentCount": policy["AttachmentCount"],
                "CreateDate": datetime.strftime(policy["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
                "UpdateDate": datetime.strftime(policy["UpdateDate"], "%Y-%m-%dT%H:%M:%S"),
            }
        )
    ec = {"AWS.IAM.Policies": data}
    human_readable = tableToMarkdown("AWS IAM Policies", data)
    return_outputs(human_readable, ec)


def list_roles(args, client):  # pragma: no cover
    data = []
    output = []
    paginator = client.get_paginator("list_roles")
    for response in paginator.paginate():
        for role in response["Roles"]:
            data.append(
                {
                    "RoleName": role["RoleName"],
                    "RoleId": role["RoleId"],
                    "Arn": role["Arn"],
                    "CreateDate": datetime.strftime(role["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
                    "Path": role["Path"],
                }
            )
            output.append(role)

    raw = json.loads(json.dumps(output, cls=DatetimeEncoder))
    ec = {"AWS.IAM.Roles": raw}
    human_readable = tableToMarkdown("AWS IAM Roles", data)
    return_outputs(human_readable, ec)


def attach_policy(args, client):  # pragma: no cover
    response = {}
    if args.get("type") == "User":
        response = client.attach_user_policy(UserName=args.get("entityName"), PolicyArn=args.get("policyArn"))
    if args.get("type") == "Group":
        response = client.attach_group_policy(GroupName=args.get("entityName"), PolicyArn=args.get("policyArn"))
    if args.get("type") == "Role":
        response = client.attach_role_policy(RoleName=args.get("entityName"), PolicyArn=args.get("policyArn"))

    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("Policy was attached to {}: {} ".format(args.get("type"), args.get("entityName")))


def detach_policy(args, client):  # pragma: no cover
    response = {}
    if args.get("type") == "User":
        response = client.detach_user_policy(UserName=args.get("entityName"), PolicyArn=args.get("policyArn"))
    if args.get("type") == "Group":
        response = client.detach_group_policy(GroupName=args.get("entityName"), PolicyArn=args.get("policyArn"))
    if args.get("type") == "Role":
        response = client.detach_role_policy(RoleName=args.get("entityName"), PolicyArn=args.get("policyArn"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("Policy was detached from {}: {} ".format(args.get("type"), args.get("entityName")))


def delete_login_profile(args, client):  # pragma: no cover
    response = client.delete_login_profile(UserName=args.get("userName"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The user {} login profile has been deleted".format(args.get("userName")))


def delete_group(args, client):  # pragma: no cover
    response = client.delete_group(GroupName=args.get("groupName"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Group {} has been deleted".format(args.get("groupName")))


def remove_user_from_group(args, client):  # pragma: no cover
    response = client.remove_user_from_group(GroupName=args.get("groupName"), UserName=args.get("userName"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The User {} has been removed from the group {}".format(args.get("userName"), args.get("groupName")))


def delete_access_key(args, client):  # pragma: no cover
    kwargs = {"AccessKeyId": args.get("AccessKeyId")}
    if user_name := args.get("userName"):
        kwargs["UserName"] = user_name

    response = client.delete_access_key(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Access Key was deleted")


def list_mfa_devices(args, client):
    user_name = args.get("userName", "")
    marker = args.get("marker", None)
    limit, is_manual, page_size = get_limit(args)

    kwargs = {"UserName": user_name, "MaxItems": limit}
    if marker:
        kwargs.update({"Marker": marker})
    response = client.list_mfa_devices(**kwargs)

    mfa_devices = response["MFADevices"]
    data = []

    for mfa_device in mfa_devices:
        data.append(
            {
                "UserName": mfa_device["UserName"],
                "SerialNumber": mfa_device["SerialNumber"],
                "EnableDate": datetime.strftime(mfa_device["EnableDate"], "%Y-%m-%d %H:%M:%S"),
            }
        )
    if is_manual and page_size and len(data) > page_size:
        data = data[-1 * page_size :]
    human_readable = tableToMarkdown("AWS IAM Users MFA Devices", data)
    return CommandResults(
        readable_output=human_readable,
        outputs_key_field="UserName",
        outputs_prefix="AWS.IAM.MFADevices",
        outputs={"Devices": data, "Marker": response["Marker"]},
    )


def deactivate_mfa_device(args, client):
    response = client.deactivate_mfa_device(UserName=args["userName"], SerialNumber=args["serialNumber"])
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The User {} mfa device has been deactivated".format(args.get("userName")))


def delete_virtual_mfa_device(args, client):
    response = client.delete_virtual_mfa_device(SerialNumber=args["serialNumber"])
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The User {} mfa device has been deleted".format(args.get("serialNumber")))


def create_instance_profile(args, client):  # pragma: no cover
    kwargs = {"InstanceProfileName": args.get("instanceProfileName")}
    if args.get("path") is not None:
        kwargs.update({"Path": args.get("path")})

    response = client.create_instance_profile(**kwargs)
    instanceProfile = response["InstanceProfile"]
    data = {
        "Path": instanceProfile["Path"],
        "InstanceProfileName": instanceProfile["InstanceProfileName"],
        "InstanceProfileId": instanceProfile["Path"],
        "Arn": instanceProfile["Arn"],
        "CreateDate": datetime.strftime(instanceProfile["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
    }

    ec = {"AWS.IAM.InstanceProfiles": data}
    human_readable = tableToMarkdown("AWS IAM InstanceProfile", data)
    return_outputs(human_readable, ec)


def delete_instance_profile(args, client):  # pragma: no cover
    response = client.delete_instance_profile(InstanceProfileName=args.get("instanceProfileName"))
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The InstanceProfile: {} was deleted".format(args.get("instanceProfileName")))


def list_instance_profiles(args, client):  # pragma: no cover
    output = []
    data = []
    paginator = client.get_paginator("list_instance_profiles")
    for response in paginator.paginate():
        for instanceProfile in response["InstanceProfiles"]:
            data.append(
                {
                    "Path": instanceProfile["Path"],
                    "InstanceProfileName": instanceProfile["InstanceProfileName"],
                    "InstanceProfileId": instanceProfile["InstanceProfileId"],
                    "CreateDate": datetime.strftime(instanceProfile["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
                }
            )
            output.append(instanceProfile)

    raw = json.loads(json.dumps(output, cls=DatetimeEncoder))
    ec = {"AWS.IAM.InstanceProfiles": raw}
    human_readable = tableToMarkdown("AWS IAM Instance Profiles", data)
    return_outputs(human_readable, ec)


def add_role_to_instance_profile(args, client):  # pragma: no cover
    kwargs = {"InstanceProfileName": args.get("instanceProfileName"), "RoleName": args.get("roleName")}

    response = client.add_role_to_instance_profile(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results(
            "The Role: {} was added to the Instance Profile: {}".format(args.get("roleName"), args.get("instanceProfileName"))
        )


def remove_role_from_instance_profile(args, client):  # pragma: no cover
    kwargs = {"InstanceProfileName": args.get("instanceProfileName"), "RoleName": args.get("roleName")}

    response = client.remove_role_from_instance_profile(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results(
            "The Role: {} was removed from the Instance Profile: {}".format(args.get("roleName"), args.get("instanceProfileName"))
        )


def list_instance_profiles_for_role(args, client):  # pragma: no cover
    output = []
    data = []
    paginator = client.get_paginator("list_instance_profiles_for_role")
    for response in paginator.paginate(RoleName=args.get("roleName")):
        for instanceProfile in response["InstanceProfiles"]:
            data.append(
                {
                    "Path": instanceProfile["Path"],
                    "InstanceProfileName": instanceProfile["InstanceProfileName"],
                    "InstanceProfileId": instanceProfile["InstanceProfileId"],
                    "CreateDate": datetime.strftime(instanceProfile["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
                    "Arn": instanceProfile["Arn"],
                }
            )
            output.append(instanceProfile)

    raw = json.loads(json.dumps(instanceProfile, cls=DatetimeEncoder))
    ec = {"AWS.IAM.InstanceProfiles": raw}
    human_readable = tableToMarkdown("AWS IAM Instance Profiles", data)
    return_outputs(human_readable, ec)


def get_instance_profile(args, client):  # pragma: no cover
    response = client.get_instance_profile(InstanceProfileName=args.get("instanceProfileName"))
    instanceProfile = response["InstanceProfile"]
    data = {
        "Path": instanceProfile["Path"],
        "InstanceProfileName": instanceProfile["InstanceProfileName"],
        "InstanceProfileId": instanceProfile["InstanceProfileId"],
        "CreateDate": datetime.strftime(instanceProfile["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
    }

    raw = json.loads(json.dumps(instanceProfile, cls=DatetimeEncoder))
    ec = {"AWS.IAM.InstanceProfiles": raw}
    human_readable = tableToMarkdown("AWS IAM Instance Profiles", data)
    return_outputs(human_readable, ec)


def get_role(args, client):  # pragma: no cover
    response = client.get_role(RoleName=args.get("roleName"))
    role = response["Role"]
    data = {
        "RoleName": role["RoleName"],
        "RoleId": role["RoleId"],
        "Arn": role["Arn"],
        "CreateDate": datetime.strftime(role["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
        "Path": role["Path"],
    }

    raw = json.loads(json.dumps(response["Role"], cls=DatetimeEncoder))
    raw["Tags"] = raw.get("Tags", [])
    human_readable = tableToMarkdown("AWS IAM Roles", data)
    return CommandResults(
        outputs=createContext(raw), outputs_prefix="AWS.IAM.Roles", outputs_key_field="RoleName", readable_output=human_readable
    )


def delete_role(args, client):  # pragma: no cover
    response = client.delete_role(RoleName=args.get("roleName"))

    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Role: {} was deleted".format(args.get("roleName")))


def create_role(args, client):  # pragma: no cover
    kwargs = {
        "RoleName": args.get("roleName"),
        "AssumeRolePolicyDocument": json.dumps(json.loads(args.get("assumeRolePolicyDocument"))),
    }
    if args.get("path") is not None:
        kwargs.update({"Path": args.get("path")})
    if args.get("description") is not None:
        kwargs.update({"Description": args.get("description")})
    if args.get("maxSessionDuration") is not None:
        kwargs.update({"MaxSessionDuration": int(args.get("maxSessionDuration"))})
    # return kwargs
    response = client.create_role(**kwargs)
    role = response["Role"]
    data = {
        "RoleName": role["RoleName"],
        "RoleId": role["RoleId"],
        "Arn": role["Arn"],
        "Path": role["Path"],
    }

    raw = json.loads(json.dumps(response["Role"], cls=DatetimeEncoder))
    ec = {"AWS.IAM.Roles": raw}
    human_readable = tableToMarkdown("AWS IAM Roles", data)
    return_outputs(human_readable, ec)


def create_policy(args, client):  # pragma: no cover
    kwargs = {"PolicyName": args.get("policyName"), "PolicyDocument": json.dumps(json.loads(args.get("policyDocument")))}
    if args.get("path") is not None:
        kwargs.update({"Path": args.get("path")})
    if args.get("description") is not None:
        kwargs.update({"Description": args.get("description")})

    response = client.create_policy(**kwargs)
    policy = response["Policy"]
    data = {
        "PolicyName": policy["PolicyName"],
        "PolicyId": policy["PolicyId"],
        "Arn": policy["Arn"],
        "Path": policy["Path"],
        "CreateDate": datetime.strftime(policy["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
    }

    raw = json.loads(json.dumps(response["Policy"], cls=DatetimeEncoder))
    ec = {"AWS.IAM.Policies": raw}
    human_readable = tableToMarkdown("AWS IAM Policies", data)
    return_outputs(human_readable, ec)


def delete_policy(args, client):  # pragma: no cover
    response = client.delete_policy(PolicyArn=args.get("policyArn"))

    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Policy: {} was deleted".format(args.get("policyArn")))


def create_policy_version(args, client):  # pragma: no cover
    kwargs = {"PolicyArn": args.get("policyArn"), "PolicyDocument": json.dumps(json.loads(args.get("policyDocument")))}
    if args.get("setAsDefault") is not None:
        kwargs.update({"SetAsDefault": args.get("setAsDefault") == "True"})

    response = client.create_policy_version(**kwargs)
    policy = response["PolicyVersion"]
    data = {
        "PolicyArn": args.get("policyArn"),
        "VersionId": policy["VersionId"],
        "IsDefaultVersion": policy["IsDefaultVersion"],
        "CreateDate": datetime.strftime(policy["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
    }

    ec = {"AWS.IAM.Policies(val.PolicyArn === obj.PolicyArn).Versions": data}
    human_readable = tableToMarkdown("New AWS IAM Policy Version", data)
    return_outputs(human_readable, ec)


def delete_policy_version(args, client):  # pragma: no cover
    kwargs = {"PolicyArn": args.get("policyArn"), "VersionId": args.get("versionId")}
    response = client.delete_policy_version(**kwargs)

    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Policy Version was deleted")


def list_policy_versions(args, client):  # pragma: no cover
    data = []
    response = client.list_policy_versions(PolicyArn=args.get("policyArn"))
    for version in response["Versions"]:
        data.append(
            {
                "PolicyArn": args.get("policyArn"),
                "VersionId": version["VersionId"],
                "IsDefaultVersion": version["IsDefaultVersion"],
                "CreateDate": datetime.strftime(version["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
            }
        )
    ec = {"AWS.IAM.Policies(val.PolicyArn === obj.PolicyArn).Versions": data}
    human_readable = tableToMarkdown("AWS IAM Policy Versions", data)
    return_outputs(human_readable, ec)


def get_policy_version(args, client):  # pragma: no cover
    data = []
    kwargs = {"PolicyArn": args.get("policyArn"), "VersionId": args.get("versionId")}
    response = client.get_policy_version(**kwargs)
    version = response["PolicyVersion"]
    data.append(
        {
            "PolicyArn": args.get("policyArn"),
            "Document": version["Document"],
            "VersionId": version["VersionId"],
            "IsDefaultVersion": version["IsDefaultVersion"],
            "CreateDate": datetime.strftime(version["CreateDate"], "%Y-%m-%dT%H:%M:%S"),
        }
    )
    ec = {"AWS.IAM.Policies(val.PolicyArn === obj.PolicyArn).Versions": data}
    human_readable = tableToMarkdown("AWS IAM Policy Version", data)
    return_outputs(human_readable, ec)


def set_default_policy_version(args, client):  # pragma: no cover
    kwargs = {"PolicyArn": args.get("policyArn"), "VersionId": args.get("versionId")}
    response = client.set_default_policy_version(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Default Policy Version was set to {}".format(args.get("versionId")))


def create_account_alias(args, client):  # pragma: no cover
    kwargs = {"AccountAlias": args.get("accountAlias")}
    response = client.create_account_alias(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Account Alias was created")


def delete_account_alias(args, client):  # pragma: no cover
    kwargs = {"AccountAlias": args.get("accountAlias")}
    response = client.delete_account_alias(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Account Alias was deleted")


def get_account_password_policy(args, client):  # pragma: no cover
    response = client.get_account_password_policy()
    data = response["PasswordPolicy"]
    raw = json.loads(json.dumps(response["PasswordPolicy"], cls=DatetimeEncoder))
    ec = {"AWS.IAM.PasswordPolicy": raw}
    human_readable = tableToMarkdown("AWS IAM Account Password Policy", data)
    return_outputs(human_readable, ec)


def update_account_password_policy(args, client):  # pragma: no cover
    try:
        response = client.get_account_password_policy()
        kwargs = response["PasswordPolicy"]
    except client.exceptions.NoSuchEntityException:
        kwargs = {}
    # ExpirePasswords is part of the response but cannot be included
    # in the request
    if "ExpirePasswords" in kwargs:
        kwargs.pop("ExpirePasswords")
    if args.get("minimumPasswordLength"):
        kwargs.update({"MinimumPasswordLength": int(args.get("minimumPasswordLength"))})
    if args.get("requireSymbols"):
        kwargs.update({"RequireSymbols": args.get("requireSymbols") == "True"})
    if args.get("requireNumbers"):
        kwargs.update({"RequireNumbers": args.get("requireNumbers") == "True"})
    if args.get("requireUppercaseCharacters"):
        kwargs.update({"RequireUppercaseCharacters": args.get("requireUppercaseCharacters") == "True"})
    if args.get("requireLowercaseCharacters"):
        kwargs.update({"RequireLowercaseCharacters": args.get("requireLowercaseCharacters") == "True"})
    if args.get("allowUsersToChangePassword"):
        kwargs.update({"AllowUsersToChangePassword": args.get("allowUsersToChangePassword") == "True"})
    if args.get("maxPasswordAge"):
        kwargs.update({"MaxPasswordAge": int(args.get("maxPasswordAge"))})
    if args.get("passwordReusePrevention"):
        kwargs.update({"PasswordReusePrevention": int(args.get("passwordReusePrevention"))})
    if args.get("hardExpiry"):
        kwargs.update({"HardExpiry": args.get("hardExpiry") == "True"})
    response = client.update_account_password_policy(**kwargs)
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("The Account Password Policy was updated")


def list_role_policies(args, client):  # pragma: no cover
    kwargs = {"RoleName": args.get("roleName")}
    response = client.list_role_policies(**kwargs)
    response = json.dumps(response, default=datetime_to_string)
    response = json.loads(response)
    outputs = {"AWS.IAM.Roles(val.RoleName && val.RoleName === obj.RoleName).Policies": response.get("PolicyNames")}
    del response["ResponseMetadata"]
    table_header = "AWS IAM Role Policies for {}".format(args.get("roleName"))
    human_readable = aws_table_to_markdown(response, table_header)
    return_outputs(human_readable, outputs, response)


def get_role_policy(args, client):  # pragma: no cover
    kwargs = {"RoleName": args.get("roleName"), "PolicyName": args.get("policyName")}
    response = client.get_role_policy(**kwargs)
    response = json.dumps(response, default=datetime_to_string)
    response = json.loads(response)
    outputs = {"AWS.IAM.Roles(val.RoleName && val.RoleName === obj.RoleName)": response}
    del response["ResponseMetadata"]
    table_header = "AWS IAM Role Policy for {}".format(args.get("roleName"))
    human_readable = aws_table_to_markdown(response, table_header)
    return_outputs(human_readable, outputs, response)


def get_policy(args, client):  # pragma: no cover
    kwargs = {"PolicyArn": args.get("policyArn")}
    response = client.get_policy(**kwargs)
    response = json.dumps(response, default=datetime_to_string)
    response = json.loads(response)
    outputs = {"AWS.IAM.Policy(val.PolicyName && val.PolicyName === obj.PolicyName)": response.get("Policy")}
    del response["ResponseMetadata"]
    table_header = "AWS IAM Policy for {}".format(args.get("policyArn"))
    human_readable = aws_table_to_markdown(response, table_header)
    return_outputs(human_readable, outputs, response)


def list_user_policies(args, client):
    user_name = args.get("userName", "")
    marker = args.get("marker", None)
    limit, is_manual, page_size = get_limit(args)

    kwargs = {"UserName": user_name, "MaxItems": limit}
    if marker:
        kwargs.update({"Marker": marker})

    response = client.list_user_policies(**kwargs)
    data = response.get("PolicyNames", [])
    marker = response.get("Marker", None)

    if is_manual and page_size and len(data) > page_size:
        data = data[-1 * page_size :]

    policy_data = [
        {
            "UserName": user_name,
            "PolicyName": policy,
        }
        for policy in data
    ]

    ec = {}
    if policy_data:
        ec = {
            "AWS.IAM.UserPolicies(val.PolicyName && val.UserName && val.PolicyName === obj.PolicyName && "
            "val.UserName === obj.UserName)": policy_data,
            f"AWS.IAM.Users(val.UserName === '{user_name}').InlinePoliciesMarker": marker,
        }

    human_readable = tableToMarkdown(
        f"AWS IAM Policies for user {user_name}", headers=["PolicyNames"], headerTransform=pascalToSpace, t=data
    )
    return_outputs(human_readable, ec, response)


def list_attached_user_policies(args, client):
    user_name = args.get("userName")
    marker = args.get("marker")
    limit, is_manual, page_size = get_limit(args)

    kwargs = {"UserName": user_name, "MaxItems": limit}
    if marker:
        kwargs.update({"Marker": marker})

    response = client.list_attached_user_policies(**kwargs)
    data = response.get("AttachedPolicies", [])
    marker = response.get("Marker", None)

    if is_manual and page_size is not None and len(data) > page_size:
        data = data[-1 * page_size :]

    policy_data = [
        {"UserName": user_name, "PolicyArn": policy.get("PolicyArn"), "PolicyName": policy.get("PolicyName")} for policy in data
    ]

    ec = {}
    if policy_data:
        ec = {
            "AWS.IAM.AttachedUserPolicies(val.PolicyArn && val.UserName && val.PolicyArn === obj.PolicyArn && "
            "val.UserName === obj.UserName)": policy_data,
            f"AWS.IAM.Users(val.UserName === '{user_name}').AttachedPoliciesMarker": marker,
        }

    human_readable = tableToMarkdown(
        f"AWS IAM Attached Policies for user {user_name}",
        headers=["PolicyName", "PolicyArn"],
        headerTransform=pascalToSpace,
        t=data,
    )

    return_outputs(human_readable, ec, response)


def list_attached_group_policies(args, client):
    group_name = args.get("groupName")
    marker = args.get("marker")
    limit, is_manual, page_size = get_limit(args)

    kwargs = {"GroupName": group_name, "MaxItems": limit}
    if marker:
        kwargs.update({"Marker": marker})

    response = client.list_attached_group_policies(**kwargs)
    data = response.get("AttachedPolicies", [])
    marker = response.get("Marker")

    if is_manual and page_size and len(data) > page_size:
        data = data[-1 * args.get("page_size") :]

    policy_data = [
        {"GroupName": group_name, "PolicyArn": policy.get("PolicyArn"), "PolicyName": policy.get("PolicyName")} for policy in data
    ]

    ec = {}
    if policy_data:
        ec = {
            "AWS.IAM.AttachedGroupPolicies(val.PolicyArn && val.GroupName && val.PolicyArn === obj.PolicyArn && "
            "val.GroupName === obj.GroupName)": policy_data,
            f"AWS.IAM.Groups(val.GroupName === '{group_name}').AttachedPoliciesMarker": marker,
        }

    human_readable = tableToMarkdown(
        f"AWS IAM Attached Policies for group {group_name}",
        headers=["PolicyName", "PolicyArn"],
        headerTransform=pascalToSpace,
        t=data,
    )

    return_outputs(human_readable, ec, response)


def get_user_login_profile(args, client):
    user_name = args.get("userName")
    kwargs = {"UserName": user_name}

    try:
        response = client.get_login_profile(**kwargs)
        user_profile = response["LoginProfile"]
        create_date = datetime_to_string(user_profile.get("CreateDate")) or user_profile.get("CreateDate")
        data = {
            "UserName": user_profile.get("UserName"),
            "LoginProfile": {"CreateDate": create_date, "PasswordResetRequired": user_profile.get("PasswordResetRequired")},
        }

        ec = {"AWS.IAM.Users(val.UserName && val.UserName === obj.UserName)": data}

        human_readable = tableToMarkdown(
            f"AWS IAM Login Profile for user {user_name}",
            t=data.get("LoginProfile"),
            headers=["CreateDate", "PasswordResetRequired"],
            removeNull=True,
            headerTransform=pascalToSpace,
        )

        response["LoginProfile"].update({"CreateDate": create_date})
        return_outputs(human_readable, ec, response)
    except botocore.exceptions.ClientError as error:
        if error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") == 404:
            return_outputs(tableToMarkdown(f"AWS IAM Login Profile for user {user_name}", t={}))
        else:
            raise error


def put_role_policy_command(args, client):
    """
    Add or change a policy entry for a given role.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    policy_document = args.get("policyDocument")
    policy_name = args.get("policyName")
    role_name = args.get("roleName")

    kwargs = {"PolicyDocument": policy_document, "PolicyName": policy_name, "RoleName": role_name}

    try:
        response = client.put_role_policy(**kwargs)
        human_readable = f"Policy {policy_name} was added to role {role_name}"
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't add policy {policy_name} to role {role_name}\nencountered the following exception: {e!s}"
        )


def put_user_policy_command(args, client):
    """
    Add or change a policy entry for a given user.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    policy_document = args.get("policyDocument")
    policy_name = args.get("policyName")
    user_name = args.get("userName")

    kwargs = {"PolicyDocument": policy_document, "PolicyName": policy_name, "UserName": user_name}

    try:
        response = client.put_user_policy(**kwargs)
        human_readable = f"Policy {policy_name} was added to user {user_name}"
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't add policy {policy_name} to user {user_name}\nencountered the following exception: {e!s}"
        )


def put_group_policy_command(args, client):
    """
    Add or change a policy entry for a given group.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    policy_document = args.get("policyDocument")
    policy_name = args.get("policyName")
    group_name = args.get("groupName")

    kwargs = {"PolicyDocument": policy_document, "PolicyName": policy_name, "GroupName": group_name}

    try:
        response = client.put_group_policy(**kwargs)
        human_readable = f"Policy {policy_name} was added to group {group_name}"
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't add policy {policy_name} to group {group_name}\nencountered the following exception: {e!s}"
        )


def tag_role_command(args, client):
    """
    Add the given tags to the given role.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    tags = create_tag_dicts_list(argToList(args.get("tags")))
    role_name = args.get("roleName")

    kwargs = {"RoleName": role_name, "Tags": tags}

    try:
        response = client.tag_role(**kwargs)
        human_readable = tableToMarkdown(f"Added the following tags to role {role_name}", tags)
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't add the following tags {tags} to role {role_name}\nencountered the following exception: {e!s}"
        )


def list_attached_role_policies_command(args: dict, client) -> list[CommandResults]:
    aws_args = {"RoleName": (role_name := args["roleName"])}

    for demisto_key, aws_key in (
        ("pathPrefix", "PathPrefix"),
        ("marker", "Marker"),
        ("maxItems", "MaxItems"),
    ):  # optional keys, renaming to match AWS API
        if (value := args.get(demisto_key)) is not None:
            aws_args[aws_key] = value

    if (max_itmes := aws_args.get("MaxItems")) is not None:
        aws_args["MaxItems"] = int(max_itmes)
    try:
        raw_response = client.list_attached_role_policies(**aws_args)
    except Exception as e:
        raise DemistoException(f"Couldn't list role policies with {args}\nencountered the following exception: {e!s}") from e

    policies = [policy | {"RoleName": role_name} for policy in raw_response["AttachedPolicies"]]

    query_outputs = {k: v for k, v in raw_response.items() if k in ("IsTruncated", "Marker")}
    return [
        CommandResults(
            # Main result - here be policies
            raw_response=raw_response,
            outputs=policies,
            outputs_prefix="AWS.IAM.Roles.AttachedPolicies.Policies",
            readable_output=tableToMarkdown(
                name=f"Attached Policies for Role {role_name}",
                t=policies,
            ),
        ),
        CommandResults(
            # Secondary result object, for querying the next ones (if necessary)
            raw_response=raw_response,
            outputs=query_outputs,
            outputs_prefix="AWS.IAM.Roles.AttachedPolicies.Query",
            readable_output=f"Listed {len(policies)} attached policies for role {role_name}"
            if not raw_response.get("IsTruncated")
            else (
                f"Listed {len(policies)} role policies but more are available. "
                "Either increase the `maxItems` argument, or use `marker` argument with the value from context."
            ),
        ),
    ]


def tag_user_command(args, client):
    """
    Add the given tags to the given user.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    tags = create_tag_dicts_list(argToList(args.get("tags")))
    user_name = args.get("userName")

    kwargs = {"UserName": user_name, "Tags": tags}

    try:
        response = client.tag_user(**kwargs)
        human_readable = tableToMarkdown(f"Added the following tags to user {user_name}", tags)
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't add the following tags {tags} to role {user_name}\nencountered the following exception: {e!s}"
        )


def untag_user_command(args, client):
    """
    Remove the given tags from the given user.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    tags = argToList(args.get("tagKeys"))
    user_name = args.get("userName")

    kwargs = {"UserName": user_name, "TagKeys": tags}

    try:
        response = client.untag_user(**kwargs)
        human_readable = tableToMarkdown(f"Untagged the following tags from user {user_name}", tags, headers=["Removed keys"])
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't untag the following tags {', '.join(tags)} from user {user_name}"
            f"\nencountered the following exception: {e!s}"
        )


def untag_role_command(args, client):
    """
    Remove the given tags from the given role.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, and the human readable section.
    """
    tags = argToList(args.get("tagKeys"))
    role_name = args.get("roleName")

    kwargs = {"RoleName": role_name, "TagKeys": tags}

    try:
        response = client.untag_role(**kwargs)
        human_readable = tableToMarkdown(f"Untagged the following tags from role {role_name}", tags, headers=["Removed keys"])
        return CommandResults(raw_response=response, readable_output=human_readable)
    except Exception as e:
        raise DemistoException(
            f"Couldn't untag the following tags {', '.join(tags)} from role {role_name}"
            f"\nencountered the following exception: {e!s}"
        )


def create_tag_dicts_list(tags):
    """
    Transform the given tags list to a list of dicts.
    Args:
        tags (list): The tags list where each entry is in the form of Key:value
    Returns:
        list: The transformed list.
    """
    try:
        dict_tags = []
        for tag in tags:
            temp = tag.split(":")
            dict_tags.append({"Key": temp[0], "Value": temp[1]})
        return dict_tags
    except Exception as e:
        demisto.debug(f"encountered the following error in create_tag_dicts_list: {e!s}")
        raise DemistoException("Please make sure the tags argument is in the form of Key1:Value1,Key2:Value2.")


def get_access_key_last_used_command(args, client):
    """
    Retrieve information about the last used occasion of the given access key.
    Args:
        client (boto3.client): The boto3.client client object.
        args (Dict): demisto.args() object.
    Returns:
        CommandResults: command results object with the response, the ec, and the human readable section.
    """
    access_key_id = args.get("accessKeyId")
    kwargs = {"AccessKeyId": access_key_id}

    try:
        response = client.get_access_key_last_used(**kwargs)
        access_key_last_used = response.get("AccessKeyLastUsed", {})
        last_used = ""
        if last_used := access_key_last_used.get("LastUsedDate", ""):
            last_used = datetime.strftime(last_used, "%Y-%m-%dT%H:%M:%S")
            response["AccessKeyLastUsed"]["LastUsedDate"] = last_used
        data = {
            "ID": access_key_id,
            "UserName": response.get("UserName", ""),
            "LastUsedServiceName": access_key_last_used.get("ServiceName", ""),
            "LastUsedRegion": access_key_last_used.get("Region", ""),
            "LastUsedDate": last_used,
        }
        headers = ["ID", "UserName", "LastUsedDate", "LastUsedServiceName", "LastUsedRegion"]
        human_readable = tableToMarkdown(
            f"Found the following information about access key {access_key_id}", data, headers, removeNull=True
        )
        return CommandResults(
            outputs=createContext(data, removeNull=True),
            outputs_prefix="AWS.IAM.AccessKey",
            raw_response=response,
            outputs_key_field="ID",
            readable_output=human_readable,
        )
    except Exception as e:
        raise DemistoException(
            f"Couldn't get information about access key {access_key_id}\nencountered the following exception: {e!s}"
        )


def test_function(client):
    response = client.list_users()
    if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        demisto.results("ok")


def main():  # pragma: no cover
    params = demisto.params()
    aws_default_region = params.get("defaultRegion")
    aws_role_arn = params.get("roleArn")
    aws_role_session_name = params.get("roleSessionName")
    aws_role_session_duration = params.get("sessionDuration")
    aws_role_policy = None
    aws_access_key_id = params.get("credentials", {}).get("identifier") or params.get("access_key")
    aws_secret_access_key = params.get("credentials", {}).get("password") or params.get("secret_key")
    verify_certificate = not params.get("insecure", True)
    timeout = params.get("timeout")
    retries = params.get("retries") or 5

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

    aws_client = 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,
        verify_certificate,
        timeout,
        retries,
    )
    command = demisto.command()
    args = demisto.args()
    client = aws_client.aws_session(
        service=SERVICE,
        role_arn=args.get("roleArn"),
        role_session_name=args.get("roleSessionName"),
        role_session_duration=args.get("roleSessionDuration"),
    )

    try:
        LOG(f"Command being called is {command}")
        if command == "test-module":
            test_function(client)
        elif command == "aws-iam-create-user":
            create_user(args, client)
        elif command == "aws-iam-create-login-profile":
            create_login_profile(args, client)
        elif command == "aws-iam-get-user":
            get_user(args, client)
        elif command == "aws-iam-list-users":
            list_users(args, client)
        elif command == "aws-iam-update-user":
            update_user(args, client)
        elif command == "aws-iam-delete-user":
            delete_user(args, client)
        elif command == "aws-iam-update-login-profile":
            update_login_profile(args, client)
        elif command == "aws-iam-create-group":
            create_group(args, client)
        elif command == "aws-iam-list-groups":
            list_groups(args, client)
        elif command == "aws-iam-list-groups-for-user":
            list_groups_for_user(args, client)
        elif command == "aws-iam-create-access-key":
            create_access_key(args, client)
        elif command == "aws-iam-update-access-key" or command == "aws-iam-access-key-update-quick-action":
            update_access_key(args, client)
        elif command == "aws-iam-list-access-keys-for-user":
            list_access_key_for_user(args, client)
        elif command == "aws-iam-list-policies":
            list_policies(args, client)
        elif command == "aws-iam-list-roles":
            list_roles(args, client)
        elif command == "aws-iam-attach-policy":
            attach_policy(args, client)
        elif command == "aws-iam-detach-policy":
            detach_policy(args, client)
        elif command == "aws-iam-delete-login-profile" or command == "aws-iam-login-profile-delete-quick-action":
            delete_login_profile(args, client)
        elif command == "aws-iam-add-user-to-group":
            add_user_to_group(args, client)
        elif command == "aws-iam-delete-group":
            delete_group(args, client)
        elif command == "aws-iam-remove-user-from-group":
            remove_user_from_group(args, client)
        elif command == "aws-iam-delete-access-key":
            delete_access_key(args, client)
        elif command == "aws-iam-list-mfa-devices":
            list_mfa_devices(args, client)
        elif command == "aws-iam-deactivate-mfa-devices":
            deactivate_mfa_device(args, client)
        elif command == "aws-iam-delete-mfa-devices":
            delete_virtual_mfa_device(args, client)
        elif command == "aws-iam-create-instance-profile":
            create_instance_profile(args, client)
        elif command == "aws-iam-delete-instance-profile":
            delete_instance_profile(args, client)
        elif command == "aws-iam-list-instance-profiles":
            list_instance_profiles(args, client)
        elif command == "aws-iam-add-role-to-instance-profile":
            add_role_to_instance_profile(args, client)
        elif command == "aws-iam-remove-role-from-instance-profile":
            remove_role_from_instance_profile(args, client)
        elif command == "aws-iam-list-instance-profiles-for-role":
            list_instance_profiles_for_role(args, client)
        elif command == "aws-iam-get-instance-profile":
            get_instance_profile(args, client)
        elif command == "aws-iam-get-role":
            return_results(get_role(args, client))
        elif command == "aws-iam-delete-role":
            delete_role(args, client)
        elif command == "aws-iam-create-role":
            create_role(args, client)
        elif command == "aws-iam-create-policy":
            create_policy(args, client)
        elif command == "aws-iam-delete-policy":
            delete_policy(args, client)
        elif command == "aws-iam-create-policy-version":
            create_policy_version(args, client)
        elif command == "aws-iam-delete-policy-version":
            delete_policy_version(args, client)
        elif command == "aws-iam-list-policy-versions":
            list_policy_versions(args, client)
        elif command == "aws-iam-get-policy-version":
            get_policy_version(args, client)
        elif command == "aws-iam-set-default-policy-version":
            set_default_policy_version(args, client)
        elif command == "aws-iam-create-account-alias":
            create_account_alias(args, client)
        elif command == "aws-iam-delete-account-alias":
            delete_account_alias(args, client)
        elif command == "aws-iam-get-account-password-policy":
            get_account_password_policy(args, client)
        elif (
            command == "aws-iam-update-account-password-policy"
            or command == "aws-iam-account-password-policy-update-quick-action"
        ):
            update_account_password_policy(args, client)
        elif command == "aws-iam-list-role-policies":
            list_role_policies(args, client)
        elif command == "aws-iam-get-role-policy":
            get_role_policy(args, client)
        elif command == "aws-iam-get-policy":
            get_policy(args, client)
        elif command == "aws-iam-list-user-policies":
            list_user_policies(args, client)
        elif command == "aws-iam-list-attached-user-policies":
            list_attached_user_policies(args, client)
        elif command == "aws-iam-list-attached-group-policies":
            list_attached_group_policies(args, client)
        elif command == "aws-iam-get-user-login-profile":
            get_user_login_profile(args, client)
        elif command == "aws-iam-put-role-policy":
            return_results(put_role_policy_command(args, client))
        elif command == "aws-iam-put-user-policy" or command == "aws-iam-user-policy-put-quick-action":
            return_results(put_user_policy_command(args, client))
        elif command == "aws-iam-put-group-policy":
            return_results(put_group_policy_command(args, client))
        elif command == "aws-iam-tag-role":
            return_results(tag_role_command(args, client))
        elif command == "aws-iam-tag-user":
            return_results(tag_user_command(args, client))
        elif command == "aws-iam-untag-user":
            return_results(untag_user_command(args, client))
        elif command == "aws-iam-untag-role":
            return_results(untag_role_command(args, client))
        elif command == "aws-iam-get-access-key-last-used":
            return_results(get_access_key_last_used_command(args, client))
        elif command == "aws-iam-list-attached-role-policies":
            return_results(list_attached_role_policies_command(args, client))
    except Exception as e:
        LOG(str(e))
        return_error(f"Error has occurred in the AWS IAM Integration: {type(e)}\n {e!s}")


from AWSApiModule import *  # noqa: E402

if __name__ in ("__builtin__", "builtins", "__main__"):
    main()