

# IAM JSON policy element reference
JSON element reference

JSON policy documents are made up of elements. The elements are listed here in the general order you use them in a policy. The order of the elements doesn't matter—for example, the `Resource` element can come before the `Action` element. You're not required to specify any `Condition` elements in the policy. To learn more about the general structure and purpose of a JSON policy document, see [Overview of JSON policies](access_policies.md#access_policies-json).

Some JSON policy elements are mutually exclusive. This means that you cannot create a policy that uses both. For example, you cannot use both `Action` and `NotAction` in the same policy statement. Other pairs that are mutually exclusive include `Principal`/`NotPrincipal` and `Resource`/`NotResource`. 

The details of what goes into a policy vary for each service, depending on what actions the service makes available, what types of resources it contains, and so on. When you're writing policies for a specific service, it's helpful to see examples of policies for that service. For a list of all the services that support IAM, and for links to the documentation in those services that discusses IAM and policies, see [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md).

 When you create or edit a JSON policy, IAM can perform policy validation to help you create an effective policy. IAM identifies JSON syntax errors, while IAM Access Analyzer provides additional policy checks with recommendations to help you further refine your policies. To learn more about policy validation, see [IAM policy validation](access_policies_policy-validator.md). To learn more about IAM Access Analyzer policy checks and actionable recommendations, see [ IAM Access Analyzer policy validation](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-validation.html). 

**Topics**
+ [Version](reference_policies_elements_version.md)
+ [Id](reference_policies_elements_id.md)
+ [Statement](reference_policies_elements_statement.md)
+ [Sid](reference_policies_elements_sid.md)
+ [Effect](reference_policies_elements_effect.md)
+ [Principal](reference_policies_elements_principal.md)
+ [NotPrincipal](reference_policies_elements_notprincipal.md)
+ [Action](reference_policies_elements_action.md)
+ [NotAction](reference_policies_elements_notaction.md)
+ [Resource](reference_policies_elements_resource.md)
+ [NotResource](reference_policies_elements_notresource.md)
+ [Condition](reference_policies_elements_condition.md)
+ [Variables and tags](reference_policies_variables.md)
+ [Supported data types](reference_policies_elements_datatypes.md)

# IAM JSON policy elements: Version
Version

**Disambiguation note**  
This `Version` JSON policy element is different from a *policy version*. The `Version` policy element is used within a policy and defines the version of the policy language. A policy version, on the other hand, is created when you make changes to a customer managed policy in IAM. The changed policy doesn't overwrite the existing policy. Instead, IAM creates a new version of the managed policy. If you were searching for information about the multiple version support available for managed policies, see [Versioning IAM policies](access_policies_managed-versioning.md).

The `Version` policy element specifies the language syntax rules that are to be used to process a policy. To use all of the available policy features, include the following `Version` element **outside** the `Statement` element in all of your policies.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*"
    }
  ]
}
```

------

IAM supports the following `Version` element values:
+ `2012-10-17`. This is the current version of the policy language, and you should always include a `Version` element and set it to `2012-10-17`. Otherwise, you cannot use features such as [policy variables](reference_policies_variables.md) that were introduced with this version.
+ `2008-10-17`. This was an earlier version of the policy language. You might see this version on older existing policies. Do not use this version for any new policies or when you update any existing policies. Newer features, such as policy variables, will not work with your policy. For example, variables such as `${aws:username}` aren't recognized as variables and are instead treated as literal strings in the policy.

# IAM JSON policy elements: Id
Id

The `Id` element specifies an optional identifier for the policy. The ID is used differently in different services. ID is allowed in resource-based policies, but not in identity-based policies.

For services that let you set an `ID` element, we recommend you use a UUID (GUID) for the value, or incorporate a UUID as part of the ID to ensure uniqueness. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Id": "cd3ad3d9-2776-4ef1-a904-4c229d1642ee",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*"
    }
  ]
}
```

------

**Note**  
Some AWS services (for example, Amazon SQS or Amazon SNS) might require this element and have uniqueness requirements for it. For service-specific information about writing policies, refer to the documentation for the service you're working with.

# IAM JSON policy elements: Statement
Statement

The `Statement` element is the main element for a policy. This element is required. The `Statement` element can contain a single statement or an array of individual statements. Each individual statement block must be enclosed in curly braces \$1 \$1. For multiple statements, the array must be enclosed in square brackets [ ].

```
"Statement": [{...},{...},{...}]
```

The following example shows a policy that contains an array of three statements inside a single `Statement` element. (The policy allows you to access your own "home folder" in the Amazon S3 console.) The policy includes the `aws:username` variable, which is replaced during policy evaluation with the user name from the request. For more information, see [Introduction](reference_policies_variables.md#policy-vars-intro). 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListAllMyBuckets",
        "s3:GetBucketLocation"
      ],
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
      "Condition": {"StringLike": {"s3:prefix": [
        "",
        "home/",
        "home/${aws:username}/"
      ]}}
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/home/${aws:username}",
        "arn:aws:s3:::amzn-s3-demo-bucket/home/${aws:username}/*"
      ]
    }
  ]
}
```

------

# IAM JSON policy elements: Sid
Sid

You can provide a `Sid` (statement ID) as an optional identifier for the policy statement. You can assign a `Sid` value to each statement in a statement array. You can use the `Sid` value as a description for the policy statement. In services that let you specify an `ID` element, such as SQS and SNS, the `Sid` value is just a sub-ID of the policy document ID. In IAM, the `Sid` value must be unique within a JSON policy.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "ExampleStatementID",
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*"
    }
  ]
}
```

------

The `Sid` element supports ASCII uppercase letters (A-Z), lowercase letters (a-z), and numbers (0-9). 

IAM does not expose the `Sid` in the IAM API. You can't retrieve a particular statement based on this ID.

**Note**  
Some AWS services (for example, Amazon SQS or Amazon SNS) might require this element and have uniqueness requirements for it. For service-specific information about writing policies, refer to the documentation for the service you work with.

# IAM JSON policy elements: Effect
Effect

The `Effect` element is required and specifies whether the statement results in an allow or an explicit deny. Valid values for `Effect` are `Allow` and `Deny`. The `Effect` value is case sensitive. 

```
"Effect":"Allow"
```

By default, access to resources is denied. To allow access to a resource, you must set the `Effect` element to `Allow`. To override an allow (for example, to override an allow that is otherwise in force), you set the `Effect` element to `Deny`. For more information, see [Policy evaluation logic](reference_policies_evaluation-logic.md).

# AWS JSON policy elements: Principal
Principal

Use the `Principal` element in a resource-based JSON policy to specify the principal that is allowed or denied access to a resource. 

You must use the `Principal` element in [resource-based policies](access_policies_identity-vs-resource.md). Several services support resource-based policies, including IAM. The IAM resource-based policy type is a role trust policy. In IAM roles, use the `Principal` element in the role trust policy to specify who can assume the role. For cross-account access, you must specify the 12-digit identifier of the trusted account. To learn whether principals in accounts outside of your zone of trust (trusted organization or account) have access to assume your roles, see [What is IAM Access Analyzer?](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html).

**Note**  
After you create the role, you can change the account to "\$1" to allow everyone to assume the role. If you do this, we strongly recommend that you limit who can access the role through other means, such as a `Condition` element that limits access to only certain IP addresses. Do not leave your role accessible to everyone\$1

Other examples of resources that support resource-based policies include an Amazon S3 bucket or an AWS KMS key.

You cannot use the `Principal` element in an identity-based policy. Identity-based policies are permissions policies that you attach to IAM identities (users, groups, or roles). In those cases, the principal is implicitly the identity where the policy is attached.

**Topics**
+ [

## How to specify a principal
](#Principal_specifying)
+ [

## AWS account principals
](#principal-accounts)
+ [

## IAM role principals
](#principal-roles)
+ [

## Role session principals
](#principal-role-session)
+ [

## OIDC federated principals
](#principal-federated-web-identity)
+ [

## SAML federated principals
](#principal-saml)
+ [

## IAM user principals
](#principal-users)
+ [

## IAM Identity Center principals
](#principal-identity-users)
+ [

## AWS STS federated user principals
](#sts-session-principals)
+ [

## AWS service principals
](#principal-services)
+ [

## AWS service principals in opt-in Regions
](#principal-services-in-opt-in-regions)
+ [

## All principals
](#principal-anonymous)
+ [

## More information
](#Principal_more-info)

## How to specify a principal


You specify a principal in the `Principal` element of a resource-based policy or in condition keys that support principals.

You can specify any of the following principals in a policy:
+ AWS account and root user
+ IAM roles
+ Role sessions 
+ IAM users
+ Federated user principals
+ AWS services
+ All principals

You cannot identify a user group as a principal in a policy (such as a resource-based policy) because groups relate to permissions, not authentication, and principals are authenticated IAM entities.

You can specify more than one principal for each of the principal types in following sections using an array. Arrays can take one or more values. When you specify more than one principal in an element, you grant permissions to each principal. This is a logical `OR` and not a logical `AND`, because you authenticate as one principal at a time. If you include more than one value, use square brackets (`[` and `]`) and comma-delimit each entry for the array. The following example policy defines permissions for the 123456789012 account or the 555555555555 account.

```
"Principal" : { 
"AWS": [ 
  "123456789012",
  "555555555555" 
  ]
}
```

**Note**  
You cannot use a wildcard to match part of a principal name or ARN. 

## AWS account principals


You can specify AWS account identifiers in the `Principal` element of a resource-based policy or in condition keys that support principals. This delegates authority to the account. When you allow access to a different account, an administrator in that account must then grant access to an identity (IAM user or role) in that account. When you specify an AWS account, you can use the account ARN (arn:aws:iam::*account-ID*:root), or a shortened form that consists of the `"AWS":` prefix followed by the account ID.

For example, given an account ID of `123456789012`, you can use either of the following methods to specify that account in the `Principal` element:

```
"Principal": { "AWS": "arn:aws:iam::123456789012:root" }
```

```
"Principal": { "AWS": "123456789012" }
```

The account ARN and the shortened account ID behave the same way. Both delegate permissions to the account. Using the account ARN in the `Principal` element does not limit permissions to only the root user of the account. 

**Note**  
When you save a resource-based policy that includes the shortened account ID, the service might convert it to the principal ARN. This does not change the functionality of the policy.

Some AWS services support additional options for specifying an account principal. For example, Amazon S3 lets you specify a [canonical user ID](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html#FindingCanonicalId) using the following format:

```
"Principal": { "CanonicalUser": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be" }
```

You can also specify more than one AWS account, (or canonical user ID) as a principal using an array. For example, you can specify a principal in a bucket policy using all three methods.

```
"Principal": { 
  "AWS": [
    "arn:aws:iam::123456789012:root",
    "999999999999"
  ],
  "CanonicalUser": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be"
}
```

## IAM role principals


You can specify IAM role principal ARNs in the `Principal` element of a resource-based policy or in condition keys that support principals. IAM roles are identities. In IAM, identities are resources to which you can assign permissions. Roles trust another authenticated identity to assume that role. This includes a principal in AWS or a user from an external identity provider (IdP). When a principal or identity assumes a role, they receive temporary security credentials with the assumed role’s permissions. When they use those session credentials to perform operations in AWS, they become a *role session principal*.

When you specify a role principal in a resource-based policy, the effective permissions for the principal are limited by any policy types that limit permissions for the role. This includes session policies and permissions boundaries. For more information about how the effective permissions for a role session are evaluated, see [Policy evaluation logic](reference_policies_evaluation-logic.md).

To specify the role ARN in the `Principal` element, use the following format:

```
"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:role/role-name" }
```

**Important**  
If your `Principal` element in a role trust policy contains an ARN that points to a specific IAM role, then that ARN transforms to the role's unique principal ID when you save the policy. This helps mitigate the risk of someone escalating their privileges by removing and recreating the role. You don't normally see this ID in the console, because IAM uses a reverse transformation back to the role ARN when the trust policy is displayed. However, if you delete the role, then you break the relationship. The policy no longer applies, even if you recreate the role because the new role has a new principal ID that does not match the ID stored in the trust policy. When this happens, the principal ID appears in resource-based policies because AWS can no longer map it back to a valid ARN. The end result is that if you delete and recreate a role referenced in a trust policy's `Principal` element, you must edit the role in the policy to replace the principal ID with the correct ARN. The ARN once again transforms into the role's new principal ID when you save the policy. For more information, see [Understanding AWS's Handling of Deleted IAM roles in Policies](https://repost.aws/articles/ARSqFcxvd7R9u-gcFD9nmA5g/understanding-aws-s-handling-of-deleted-iam-roles-in-policies).

Alternatively, you can specify the role principal as the principal in a resource-based policy or [create a broad-permission policy](#principal-anonymous) that uses the `aws:PrincipalArn` condition key. When you use this key, the role session principal is granted the permissions based on the ARN of role that was assumed, and not the ARN of the resulting session. Because AWS does not convert condition key ARNs to IDs, permissions granted to the role ARN persist if you delete the role and then create a new role with the same name. Identity-based policy types, such as permissions boundaries or session policies, do not limit permissions granted using the `aws:PrincipalArn` condition key with a wildcard(\$1) in the `Principal` element, unless the identity-based policies contain an explicit deny.

## Role session principals


You can specify role sessions in the `Principal` element of a resource-based policy or in condition keys that support principals. When a principal or identity assumes a role, they receive temporary security credentials with the assumed role’s permissions. When they use those session credentials to perform operations in AWS, they become a *role session principal*.

The format that you use for a role session principal depends on the AWS STS operation that was used to assume the role.

**Important**  
AWS recommends using [IAM role principals](#principal-roles) in your policies instead of role session principals wherever possible. Use `Condition` statements and condition keys to further scope down access when required.

To specify the role session principal ARN in the `Principal` element, use the following format:

```
"Principal": { "AWS": "arn:aws:sts::AWS-account-ID:assumed-role/role-name/role-session-name" }
```

Additionally, administrators can design a process to control how role sessions are issued. For example, they can provide a one-click solution for their users that creates a predictable session name. If your administrator does this, you can use role session principals in your policies or condition keys. Otherwise, you can specify the role ARN as a principal in the `aws:PrincipalArn` condition key. How you specify the role as a principal can change the effective permissions for the resulting session. For more information, see [IAM role principals](#principal-roles). 

## OIDC federated principals


An OIDC federated principal is the principal used when calling AWS STS `AssumeRoleWithWebIdentity` API with a JSON web token (JWT) from an OIDC compliant IDP, also known as OpenID Provider (OP), to request temporary AWS credentials. An OIDC federated principal can represent an OIDC IDP in your AWS account, or the 4 built in identity providers: Login with Amazon, Google, Facebook, and [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html).

Users, workloads, or systems who’ve been issued a JWT from their OIDC IDP can call `AssumeRoleWithWebIdentity` using the JWT to request temporary AWS security credentials for an IAM role that is configured to trust the OIDC IDP that issued the JWT. The JWT can be an id token, access token, or a JWT token delivered by any other method as long as it meets the [requirements listed by AWS STS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html#manage-oidc-provider-prerequisites). For more information, see [Common scenarios](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_federation_common_scenarios.html) and [Requesting credentials through an OIDC provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity).

Use this principal type in your role trust policy to allow or deny permissions to call `AssumeRoleWIthWebIdentity` using an OIDC IDP that exists in your AWS account, or one of the four built in IDPs. To specify the OIDC federated principal ARN in the `Principal` element of a role trust policy, use one of the following four formats for the built in OIDC IDPs:

```
"Principal": { "Federated": "cognito-identity.amazonaws.com" }
```

```
"Principal": { "Federated": "www.amazon.com" }
```

```
"Principal": { "Federated": "graph.facebook.com" }
```

```
"Principal": { "Federated": "accounts.google.com" }
```

When using a OIDC provider you add to your account, such as GitHub, you specify the provider's ARN in your role's trust policy. This configuration allows you to write IAM policies that control access specifically for users authenticated through your custom identity provider.

```
"Principal": { "Federated": "arn:aws:iam::AWS-account-ID:oidc-provider/full-OIDC-identity-provider-URL" }
```

For example, if GitHub was the trusted web identity provider, the OIDC role session ARN in the `Principal` element of a role trust policy uses the following format:

```
"Principal": { "Federated": "arn:aws:iam::AWS-account-ID:oidc-provider/tokens.actions.githubusercontent.com" }
```

See [Configuring OpenID Connect in Amazon Web Services](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services) for more information.

OIDC federated principals are not supported in policy types other than role trust policies.

## SAML federated principals


A *SAML federated principal* is a principal that is used when calling AWS STS `AssumeRoleWithSAML` API to request temporary AWS credentials using a SAML assertion. You can use your SAML identity provider (IDP) to sign in, and then assume an IAM role using this operation. Similar to `AssumeRoleWithWebIdentity`, `AssumeRoleWithSAML` doesn't require AWS credentials for authentication. Instead, users first authenticate with their SAML identity provider, then make the `AssumeRoleWithSAML` API call using their SAML assertion, or are redirected to the AWS Sign-In/SAML page to sign into the AWS Management Console. For more information about which principals can assume a role using this operation, see [Compare AWS STS credentials](id_credentials_sts-comparison.md).

Use this principal type in your role trust policy to allow or deny permissions based on the trusted SAML identity provider. To specify the SAML identity role session ARN in the `Principal` element of a role trust policy, use the following format:

```
"Principal": { "Federated": "arn:aws:iam::AWS-account-ID:saml-provider/provider-name" }
```

## IAM user principals


You can specify IAM users in the `Principal` element of a resource-based policy or in condition keys that support principals.

**Note**  
In a `Principal` element, the user name part of the [*Amazon Resource Name* (ARN)](reference_identifiers.md#identifiers-arns) is case sensitive.

```
"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:user/user-name" }
```

```
"Principal": {
  "AWS": [
    "arn:aws:iam::AWS-account-ID:user/user-name-1", 
    "arn:aws:iam::AWS-account-ID:user/user-name-2"
  ]
}
```

When you specify users in a `Principal` element, you cannot use a wildcard (`*`) to mean "all users". Principals must always name specific users. 

**Important**  
If your `Principal` element in a role trust policy contains an ARN that points to a specific IAM user, then IAM transforms the ARN to the user's unique principal ID when you save the policy. This helps mitigate the risk of someone escalating their privileges by removing and recreating the user. You don't normally see this ID in the console, because there is also a reverse transformation back to the user's ARN when the trust policy is displayed. However, if you delete the user, then you break the relationship. The policy no longer applies, even if you recreate the user. That's because the new user has a new principal ID that does not match the ID stored in the trust policy. When this happens, the principal ID appears in resource-based policies because AWS can no longer map it back to a valid ARN. The result is that if you delete and recreate a user referenced in a trust policy `Principal` element, you must edit the role to replace the now incorrect principal ID with the correct ARN. IAM once again transforms ARN into the user's new principal ID when you save the policy.

## IAM Identity Center principals
Identity Center principals

In IAM Identity Center, the principal in a resource-based policy must be defined as the AWS account principal. To specify access, reference the role ARN of the permission set in the condition block. For details, see [Referencing permission sets in resource policies, Amazon EKS, and AWS KMS](https://docs.aws.amazon.com/singlesignon/latest/userguide/referencingpermissionsets.html) in the *IAM Identity Center User Guide*.

## AWS STS federated user principals
Federated user principals

You can specify *federated user sessions* in the `Principal` element of a resource-based policy or in condition keys that support principals.

**Important**  
AWS recommends that you limit the use of AWS STS federated user sessions. Instead, use [IAM roles](IAM/latest/UserGuide/tutorial_cross-account-with-roles.html).

An AWS STS federated user principal is created through the `GetFederationToken` operation called with long-lived IAM credentials. Federated user permissions are the intersection of the principal that called `GetFederationToken` and the session policies passed as parameters to the `GetFederationToken` API.

In AWS, IAM users or an AWS account root user can authenticate using long-term access keys. For more information about which principals can federate using this operation, see [Compare AWS STS credentials](id_credentials_sts-comparison.md).
+ **IAM federated user** – An IAM user federates using the `GetFederationToken` operation that results in a federated user session for that IAM user.
+ **Federated root user** – A root user federates using the `GetFederationToken` operation that results in a federated user session for that root user.

When an IAM user or root user requests temporary credentials from AWS STS using this operation, they begin a temporary federated user session. This session’s ARN is based on the original identity that was federated.

To specify the federated user session ARN in the `Principal` element, use the following format:

```
"Principal": { "AWS": "arn:aws:sts::AWS-account-ID:federated-user/user-name" }
```

## AWS service principals


You can specify AWS services in the `Principal` element of a resource-based policy or in condition keys that support principals. A *service principal* is an identifier for a service. 

IAM roles that can be assumed by an AWS service are called *[service roles](id_roles.md#iam-term-service-role)*. Service roles must include a trust policy. *Trust policies* are resource-based policies attached to a role that defines which principals can assume the role. Some service roles have predefined trust policies. However, in some cases, you must specify the service principal in the trust policy. The service principal in an IAM policy can't be `"Service": "*"`.

**Important**  
The identifier for a service principal includes the service name, and is usually in the following format:  
`service-name.amazonaws.com`

The service principal is defined by the service. You can find the service principal for some services by opening [AWS services that work with IAM](reference_aws-services-that-work-with-iam.md), checking whether the service has **Yes **in the **Service-linked role** column, and opening the **Yes** link to view the service-linked role documentation for that service. Find the **Service-Linked Role Permissions** section for that service to view the service principal.

The following example shows a policy that can be attached to a service role. The policy enables two services, Amazon ECS and Elastic Load Balancing, to assume the role. The services can then perform any tasks granted by the permissions policy assigned to the role (not shown). To specify multiple service principals, you do not specify two `Service` elements; you can have only one. Instead, you use an array of multiple service principals as the value of a single `Service` element.

```
"Principal": {
    "Service": [
        "ecs.amazonaws.com",
        "elasticloadbalancing.amazonaws.com"
   ]
}
```

## AWS service principals in opt-in Regions


You can launch resources in several AWS Regions and some of those Regions you must opt in to. For a complete list of Regions you must opt in to, see [Managing AWS Regions](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html) in the *AWS General Reference* guide.

When an AWS service in an opt-in Region makes a request within the same Region, the service principal name format is identified as the non-regionalized version of their service principal name:

`service-name.amazonaws.com`

When an AWS service in an opt-in Region makes a cross-region request to another Region, the service principal name format is identified as the regionalized version of their service principal name:

`service-name.{region}.amazonaws.com`

For example, you have an Amazon SNS topic located in Region `ap-southeast-1` and an Amazon S3 bucket located in opt-in Region `ap-east-1`. You want to configure S3 bucket notifications to publish messages to the SNS topic. To allow the S3 service to post messages to the SNS topic you must grant the S3 service principal `sns:Publish` permission via the resource-based access policy of the topic.

If you specify the non-regionalized version of the S3 service principal, `s3.amazonaws.com`, in the topic access policy, the `sns:Publish` request from the bucket to the topic will fail. The following example specifies the non-regionalized S3 service principal in the `Principal` policy element of the SNS topic access policy.

```
"Principal": { "Service": "s3.amazonaws.com" }
```

Since the bucket is located in an opt-in Region and the request is made outside of that same Region, the S3 service principal appears as the regionalized service principal name, `s3.ap-east-1.amazonaws.com`. You must use the regionalized service principal name when an AWS service in an opt-in Region makes a request to another Region. After you specify the regionalized service principal name, if the bucket makes an `sns:Publish` request to the SNS topic located in another Region, the request will be successful. The following example specifies the regionalized S3 service principal in the `Principal` policy element of the SNS topic access policy.

```
"Principal": { "Service": "s3.ap-east-1.amazonaws.com" }
```

Resource policies or service principal-based allow-lists for cross-Region requests from an opt-in Region to another Region will only be successful if you specify the regionalized service principal name.

**Note**  
For IAM role trust policies, we recommend using the non-regionalized service principal name. IAM resources are global and therefore the same role can be used in any Region.

## All principals


You can use a wildcard (\$1) to specify all principals in the `Principal` element of a resource-based policy or in condition keys that support principals. [Resource-based policies](access_policies.md#policies_resource-based) *grant* permissions and [condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) are used to limit the conditions of a policy statement.

**Important**  
We strongly recommend that you do not use a wildcard (\$1) in the `Principal` element of a resource-based policy with an `Allow` effect unless you intend to grant public or anonymous access. Otherwise, specify intended principals, services, or AWS accounts in the `Principal` element and then further restrict access in the `Condition` element. This is especially true for IAM role trust policies, because they allow other principals to become a principal in your account.

For resource-based policies, using a wildcard (\$1) with an `Allow` effect grants access to all users, including anonymous users (public access). For IAM users and role principals within your account, no other permissions are required. For principals in other accounts, they must also have identity-based permissions in their account that allow them to access your resource. This is called [cross-account access](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html).

For anonymous users, the following elements are equivalent:

```
"Principal": "*"
```

```
"Principal" : { "AWS" : "*" }
```

You cannot use a wildcard to match part of a principal name or ARN.

The following example shows a resource-based policy that can be used instead of [AWS JSON policy elements: NotPrincipal](reference_policies_elements_notprincipal.md) to explicitly deny all principals *except* for the ones specified in the `Condition` element. This policy should be [added to an Amazon S3 bucket](https://docs.aws.amazon.com//AmazonS3/latest/userguide/add-bucket-policy.html).

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "UsePrincipalArnInsteadOfNotPrincipalWithDeny",
      "Effect": "Deny",
      "Action": "s3:*",
      "Principal": "*",
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*",
        "arn:aws:s3:::amzn-s3-demo-bucket"
      ],
      "Condition": {
        "ArnNotEquals": {
          "aws:PrincipalArn": "arn:aws:iam::444455556666:user/user-name"
        }
      }
    }
  ]
}
```

------

## More information


For more information, see the following:
+ [Bucket policy examples](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html) in the *Amazon Simple Storage Service User Guide*
+ [Example policies for Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/UsingIAMwithSNS.html#ExamplePolicies_SNS) in the *Amazon Simple Notification Service Developer Guide*
+ [Amazon SQS policy examples](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSExamples.html) in the *Amazon Simple Queue Service Developer Guide*
+ [Key policies](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html) in the *AWS Key Management Service Developer Guide*
+ [Account identifiers](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html) in the *AWS General Reference*
+ [OIDC federation](id_roles_providers_oidc.md)

# AWS JSON policy elements: NotPrincipal
NotPrincipal

The `NotPrincipal` element uses `"Effect":"Deny"` to deny access to all principals ***except*** the principal specified in the `NotPrincipal` element. A principal can be an IAM user, AWS STS federated user principal, IAM role, assumed role session, AWS account, AWS service, or other principal type. For more information about principals, see [AWS JSON policy elements: Principal](reference_policies_elements_principal.md).

`NotPrincipal` must be used with `"Effect":"Deny"`. Using it with `"Effect":"Allow"` is not supported. 

**Important**  
We do not recommend the use of `NotPrincipal` for new resource-based policies as part of your security and authorization strategy. When you use `NotPrincipal`, troubleshooting the effects of multiple policy types can be difficult. We recommend using the `aws:PrincipalArn` context key with ARN condition operators instead.

## Key points

+ The `NotPrincipal` element is supported in resource-based policies for some AWS services, including VPC endpoints. Resource-based policies are policies that you embed directly in a resource. You cannot use the `NotPrincipal` element in an IAM identity-based policy nor in an IAM role trust policy.
+ Don't use resource-based policy statements that include a `NotPrincipal` policy element with a `Deny` effect for IAM users or roles that have a permissions boundary policy attached. The `NotPrincipal` element with a `Deny` effect will always deny any IAM principal that has a permissions boundary policy attached, regardless of the values specified in the `NotPrincipal` element. This causes some IAM users or roles that would otherwise have access to the resource to lose access. We recommend changing your resource-based policy statements to use the condition operator [`ArnNotEquals`](reference_policies_elements_condition_operators.md#Conditions_ARN) with the [`aws:PrincipalArn`](reference_policies_condition-keys.md#condition-keys-principalarn) context key to limit access instead of the `NotPrincipal` element. For information about permissions boundaries, see [Permissions boundaries for IAM entities](access_policies_boundaries.md).
+ When you use `NotPrincipal`, you must also specify the account ARN of the not-denied principal. Otherwise, the policy might deny access to the entire account containing the principal. Depending on the service that you include in your policy, AWS might validate the account first and then the user. If an assumed-role user (someone who is using a role) is being evaluated, AWS might validate the account first, then the role, and then the assumed-role user. The assumed-role user is identified by the role session name that is specified when they assumed the role. Therefore, we strongly recommend that you explicitly include the ARN for a user's account, or include both the ARN for a role and the ARN for the account containing that role.
+ The `NotPrincipal` element isn’t supported in Service Control Policies (SCP) and Resource Control Policies (RCP).

## Alternatives to the `NotPrincipal` element


When managing access control in AWS, there may be scenarios where you need to explicitly deny all principals access to a resource, except for one or more principals you specify. AWS recommends using a Deny statement with global condition context keys for more precise control and easier troubleshooting. The following examples show alternative approaches using condition operators like `StringNotEquals` or `ArnNotEquals` to deny access to all principals except those specified in the Condition element.

## Example scenario using an IAM role


You can use a resource-based policy with a Deny statement to prevent all IAM roles, except those specified in the Condition element, from accessing or manipulating your resources. This approach follows the AWS security principle that an explicit deny always takes precedence over any allow statements and helps maintain the principle of least privilege across your AWS infrastructure.

Instead of using `NotPrincipal`, we recommend using a Deny statement with global condition context keys and the condition operator like [`ArnNotEquals`](reference_policies_elements_condition_operators.md#Conditions_ARN) to explicitly allow an IAM role access to your resources. The following example uses [aws:PrincipalArn](reference_policies_condition-keys.md#condition-keys-principalarn) to explicitly allow the role `read-only-role` to access Amazon S3 buckets in the `Bucket_Account_Audit` folder.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyCrossAuditAccess",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::Bucket_Account_Audit",
        "arn:aws:s3:::Bucket_Account_Audit/*"
      ],
      "Condition": {
        "ArnNotEquals": {
          "aws:PrincipalArn": "arn:aws:iam::444455556666:role/read-only-role"
        }
      }
    }
  ]
}
```

------

## Example scenario using a service principal


You can use a Deny statement to prevent all service principals, except those specified in the `Condition` element, from accessing or manipulating your resources. This approach is particularly useful when you need to implement fine-grained access controls or establish security boundaries between different services and applications in your AWS environment.

Instead of using `NotPrincipal`, we recommend using a Deny statement with global condition context keys and the condition operator [`StringNotEquals`](reference_policies_elements_condition_operators.md#Conditions_String) to explicitly allow a service principal access to your resources. The following example uses `aws:PrincipalServiceName` to explicitly allow the AWS CodeBuild service principal to access Amazon S3 buckets in the `BUCKETNAME` folder.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyNotCodeBuildAccess",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::BUCKETNAME",
        "arn:aws:s3:::BUCKETNAME/*"
      ],
      "Condition": {
        "StringNotEqualsIfExists": {
          "aws:PrincipalServiceName": "codebuild.amazonaws.com"
        }
      }
    }
  ]
}
```

------

# IAM JSON policy elements: Action
Action

The `Action` element describes the specific action or actions that will be allowed or denied. Statements must include either an `Action` or `NotAction` element. Each AWS service has its own set of actions that describe tasks that you can perform with that service. For example, the list of actions for Amazon S3 can be found at [Specifying Permissions in a Policy](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-with-s3-actions.html) in the *Amazon Simple Storage Service User Guide*, the list of actions for Amazon EC2 can be found in the [Amazon EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-apis.html), and the list of actions for AWS Identity and Access Management can be found in the [IAM API Reference](https://docs.aws.amazon.com/IAM/latest/APIReference/API_Operations.html). To find the list of actions for other services, consult the API reference [documentation](http://aws.amazon.com/documentation) for the service.

AWS also provides service reference information in JSON format to streamline the automation of policy management workflows. With the service reference information, you can access available actions, resources, and condition keys across AWS services from machine-readable files. For more information, see [Simplified AWS service information for programmatic access](https://docs.aws.amazon.com/service-authorization/latest/reference/service-reference.html) in the Service Authorization Reference.

You specify a value using a service namespace as an action prefix (`iam`, `ec2`, `sqs`, `sns`, `s3`, etc.) followed by the name of the action to allow or deny. The name must match an action that is supported by the service. The prefix and the action name are case insensitive. For example, `iam:ListAccessKeys` is the same as `IAM:listaccesskeys`. The following examples show `Action` elements for different services.

**Amazon SQS action**

```
"Action": "sqs:SendMessage"
```

**Amazon EC2 action**

```
"Action": "ec2:StartInstances"
```

**IAM action**

```
"Action": "iam:ChangePassword"
```

**Amazon S3 action**

```
"Action": "s3:GetObject"
```

You can specify multiple values for the `Action` element.

```
"Action": [ "sqs:SendMessage", "sqs:ReceiveMessage", "ec2:StartInstances", "iam:ChangePassword", "s3:GetObject" ]
```

You can use multi-character match wildcards (`*`) and single-character match wildcards (`?`) to give access to all the actions the specific AWS product offers. For example, the following `Action` element applies to all S3 actions.

```
"Action": "s3:*"
```

You can also use wildcards (`*` or `?`) as part of the action name. For example, the following `Action` element applies to all IAM actions that include the string `AccessKey`, including `CreateAccessKey`, `DeleteAccessKey`, `ListAccessKeys`, and `UpdateAccessKey`.

```
"Action": "iam:*AccessKey*"
```

Some services let you limit the actions that are available. For example, Amazon SQS lets you make available just a subset of all the possible Amazon SQS actions. In that case, the `*` wildcard doesn't allow complete control of the queue; it allows only the subset of actions that you've shared. For more information, see [Understanding Permissions](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html#PermissionTypes) in the *Amazon Simple Queue Service Developer Guide*.

# IAM JSON policy elements: NotAction
NotAction

`NotAction` is an advanced policy element that explicitly matches everything *except* the specified list of actions. Using `NotAction` can result in a shorter policy by listing only a few actions that should not match, rather than including a long list of actions that will match. Actions specified in `NotAction` are not impacted by the `Allow` or `Deny` effect in a policy statement. This, in turn, means that all of the applicable actions or services that are not listed are allowed if you use the `Allow` effect. In addition, such unlisted actions or services are denied if you use the `Deny` effect. When you use `NotAction` with the `Resource` element, you provide scope for the policy. This is how AWS determines which actions or services are applicable. For more information, see the following example policy. 

**NotAction with Allow** 

You can use the `NotAction` element in a statement with `"Effect": "Allow"` to provide access to all of the actions in an AWS service, except for the actions specified in `NotAction`. You can use it with the `Resource` element to provide scope for the policy, limiting the allowed actions to the actions that can be performed on the specified resource.

The following example allows users to access all of the Amazon S3 actions that can be performed on any S3 resource *except* for deleting a bucket. This policy also does not allow actions in other services, because other service actions are not applicable to the S3 resources.

```
"Effect": "Allow",
"NotAction": "s3:DeleteBucket",
"Resource": "arn:aws:s3:::*",
```

Sometimes, you might want to allow access to a large number of actions. By using the `NotAction` element you effectively reverse the statement, resulting in a shorter list of actions. For example, because AWS has so many services, you might want to create a policy that allows the user to do everything except access IAM actions.

The following example allows users to access every action in every AWS service except for IAM.

```
"Effect": "Allow",
"NotAction": "iam:*",
"Resource": "*"
```

Be careful using the `NotAction` element and `"Effect": "Allow"` in the same statement or in a different statement within a policy. `NotAction` matches all services and actions that are not explicitly listed or applicable to the specified resource, and could result in granting users more permissions than you intended.

**NotAction with Deny**

You can use the `NotAction` element in a statement with `"Effect": "Deny"` to deny access to all of the listed resources except for the actions specified in the `NotAction` element. This combination does not allow the listed items, but instead explicitly denies the actions not listed. You must still allow actions that you want to allow.

The following conditional example denies access to non-IAM actions if the user is not signed in using MFA. If the user is signed in with MFA, then the `"Condition"` test fails and the final `"Deny"` statement has no effect. Note, however, that this would not grant the user access to any actions; it would only explicitly deny all other actions except IAM actions.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Sid": "DenyAllUsersNotUsingMFA",
        "Effect": "Deny",
        "NotAction": "iam:*",
        "Resource": "*",
        "Condition": {"BoolIfExists": {"aws:MultiFactorAuthPresent": "false"}}
    }]
}
```

------

For an example policy that denies access to actions outside of specific Regions, except for actions from specific services, see [AWS: Denies access to AWS based on the requested Region](reference_policies_examples_aws_deny-requested-region.md).

# IAM JSON policy elements: Resource
Resource

The `Resource` element in an IAM policy statement defines the object or objects that the statement applies to. Statements must include either a `Resource` or a `NotResource` element.

You specify a resource using an Amazon Resource Name (ARN). The format of the ARN depends on the AWS service and the specific resource you're referring to. Although the ARN format varies you always use an ARN to identify a resource. For more information about the format of ARNs, see [IAM ARNs](reference_identifiers.md#identifiers-arns). For information about how to specify a resource, refer to the documentation for the service you want to write a statement.

**Note**  
Some AWS services do not allow you to specify actions for individual resources. In these cases, any actions that you list in the `Action` or `NotAction` element apply to all resources in that service. When this is the case, you use the wildcard character (`*`) in the `Resource` element.

The following example refers to a specific Amazon SQS queue.

```
"Resource": "arn:aws:sqs:us-east-2:account-ID-without-hyphens:queue1"
```

The following example refers to the IAM user named `Bob` in an AWS account.

**Note**  
In the `Resource` element, the IAM user name is case sensitive.

```
"Resource": "arn:aws:iam::account-ID-without-hyphens:user/Bob"
```

## Using wildcards in resource ARNs


You can use wildcard characters (`*` and `?`) within the individual segments of an ARN (the parts separated by colons) to represent:
+ Any combination of characters (`*`)
+ Any single character (`?`)

You can use multiple `*` or `?` characters in each segment. If the `*` wildcard is the last character of a resource ARN segment, it can expand to match beyond the colon boundaries. We recommend you use wildcards (`*` and `?`) within ARN segments separated by a colon.

**Note**  
You can't use a wildcard in the service segment that identifies the AWS product. For more information about ARN segments, see [Identify AWS resources with Amazon Resource Names (ARNs)](reference-arns.md)

The following example refers to all IAM users whose path is `/accounting`. 

```
"Resource": "arn:aws:iam::account-ID-without-hyphens:user/accounting/*"
```

The following example refers to all items within a specific Amazon S3 bucket.

```
"Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
```

The asterisk (`*`) character can expand to replace everything within a segment, including characters like a forward slash (`/`) that may otherwise appear to be a delimiter within a given service namespace. For example, consider the following Amazon S3 ARN as the same wildcard expansion logic applies to all services.

```
"Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*/test/*"
```

The wildcards in the ARN apply to all of the following objects in the bucket, not only the first object listed.

```
amzn-s3-demo-bucket/1/test/object.jpg
amzn-s3-demo-bucket/1/2/test/object.jpg
amzn-s3-demo-bucket/1/2/test/3/object.jpg 
amzn-s3-demo-bucket/1/2/3/test/4/object.jpg
amzn-s3-demo-bucket/1///test///object.jpg
amzn-s3-demo-bucket/1/test/.jpg
amzn-s3-demo-bucket//test/object.jpg
amzn-s3-demo-bucket/1/test/
```

Consider the last two objects in the previous list. An Amazon S3 object name can begin or end with the conventional delimiter forward slash (`/`) character. While `/` works as a delimiter, there is no specific significance when this character is used within a resource ARN. It is treated the same as any other valid character. The ARN would not match the following objects:

```
amzn-s3-demo-bucket/1-test/object.jpg
amzn-s3-demo-bucket/test/object.jpg
amzn-s3-demo-bucket/1/2/test.jpg
```

## Specifying multiple resources


You can specify multiple resources in the `Resource` element by using an array of ARNs. The following example refers to two DynamoDB tables.

```
"Resource": [
    "arn:aws:dynamodb:us-east-2:account-ID-without-hyphens:table/books_table",
    "arn:aws:dynamodb:us-east-2:account-ID-without-hyphens:table/magazines_table"
]
```

## Using policy variables in resource ARNs


In the `Resource` element, you can use JSON [policy variables](reference_policies_variables.md) in the part of the ARN that identifies the specific resource (that is, in the trailing part of the ARN). For example, you can use the key `{aws:username}` as part of a resource ARN to indicate that the current user's name should be included as part of the resource's name. The following example shows how you can use the `{aws:username}` key in a `Resource` element. The policy allows access to a Amazon DynamoDB table that matches the current user's name.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "dynamodb:*",
        "Resource": "arn:aws:dynamodb:us-east-2:111122223333:table/${aws:username}"
    }
}
```

------

For more information about JSON policy variables, see [IAM policy elements: Variables and tags](reference_policies_variables.md).

# IAM JSON policy elements: NotResource
NotResource

`NotResource` is an advanced policy element that explicitly matches every resource except those specified. Using `NotResource` can result in a shorter policy by listing only a few resources that should not match, rather than including a long list of resources that will match. This is particularly useful for policies that apply within a single AWS service. 

For example, imagine you have a group named `HRPayroll`. Members of `HRPayroll` should not be allowed to access any Amazon S3 resources except the `Payroll` folder in the `HRBucket` bucket. The following policy explicitly denies access to all Amazon S3 resources other than the listed resources. Note, however, that this policy does not grant the user access to any resources.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "s3:*",
    "NotResource": [
      "arn:aws:s3:::HRBucket/Payroll",
      "arn:aws:s3:::HRBucket/Payroll/*"
    ]
  }
}
```

------

Normally, to explicitly deny access to a resource you would write a policy that uses `"Effect":"Deny"` and that includes a `Resource` element that lists each folder individually. However, in that case, each time you add a folder to `HRBucket`, or add a resource to Amazon S3 that should not be accessed, you must add its name to the list in the `Resource` element. If you use a `NotResource` element instead, users are automatically denied access to new folders unless you add the folder names to the `NotResource` element. 

When using `NotResource`, you should keep in mind that resources specified in this element are the *only* resources that are not limited. This, in turn, limits all of the resources that would apply to the action. In the example above, the policy affects only Amazon S3 actions, and therefore only Amazon S3 resources. If the `Action` element also included Amazon EC2 actions, then the policy would deny access to any EC2 resources not specified in the `NotResource` element. To learn which actions in a service allow specifying the ARN of a resource, see [Actions, Resources, and Condition Keys for AWS Services](reference_policies_actions-resources-contextkeys.html).

## NotResource with other elements


You should **never** use the `"Effect": "Allow"`, `"Action": "*"`, and `"NotResource": "arn:aws:s3:::HRBucket"` elements together. This statement is very dangerous, because it allows all actions in AWS on all resources except the `HRBucket` S3 bucket. This would even allow the user to add a policy to themselves that allows them to access `HRBucket`. Do not do this. 

Be careful using the `NotResource` element and `"Effect": "Allow"` in the same statement or in a different statement within a policy. `NotResource` allows all services and resources that are not explicitly listed, and could result in granting users more permissions than you intended. Using the `NotResource` element and `"Effect": "Deny"` in the same statement denies services and resources that are not explicitly listed.

# IAM JSON policy elements: Condition
Condition

The `Condition` element (or `Condition` *block*) lets you specify conditions for when a policy is in effect. The `Condition` element is optional. In the `Condition` element, you build expressions in which you use [condition operators](reference_policies_elements_condition_operators.md) (equal, less than, and others) to match the context keys and values in the policy against keys and values in the request context. To learn more about the request context, see [Components of a request](intro-structure.md#intro-structure-request).

```
"Condition" : { "{condition-operator}" : { "{condition-key}" : "{condition-value}" }}
```

The context key that you specify in a policy condition can be a [global condition context key](reference_policies_condition-keys.md) or a service-specific context key. Global condition context keys have the `aws:` prefix. Service-specific context keys have the service's prefix. For example, Amazon EC2 lets you write a condition using the `ec2:InstanceType` context key, which is unique to that service. To view service-specific IAM context keys with the `iam:` prefix, see [IAM and AWS STS condition context keys](reference_policies_iam-condition-keys.md).

Context key *names* are not case-sensitive. For example, including the `aws:SourceIP` context key is equivalent to testing for `AWS:SourceIp`. Case-sensitivity of context key *values* depends on the [condition operator](reference_policies_elements_condition_operators.md) that you use. For example, the following condition includes the `StringEquals` operator to make sure that only requests made by `john` match. Users named `John` are denied access.

```
"Condition" : { "StringEquals" : { "aws:username" : "john" }}
```

The following condition uses the [`StringEqualsIgnoreCase`](reference_policies_elements_condition_operators.md#Conditions_String) operator to match users named `john` or `John`.

```
"Condition" : { "StringEqualsIgnoreCase" : { "aws:username" : "john" }}
```

Some context keys support key–value pairs that allow you to specify part of the key name. Examples include the [`aws:RequestTag/tag-key`](reference_policies_condition-keys.md#condition-keys-requesttag) context key, the AWS KMS [https://docs.aws.amazon.com/kms/latest/developerguide/policy-conditions.html#conditions-kms-encryption-context](https://docs.aws.amazon.com/kms/latest/developerguide/policy-conditions.html#conditions-kms-encryption-context), and the [`ResourceTag/tag-key`](reference_policies_condition-keys.md#condition-keys-resourcetag) context key supported by multiple services.
+ If you use the `ResourceTag/tag-key` context key for a service such as [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policy-structure.html#amazon-ec2-keys), then you must specify a key name for the `tag-key`. 
+ **Key names are not case-sensitive.** This means that if you specify `"aws:ResourceTag/TagKey1": "Value1"` in the condition element of your policy, then the condition matches a resource tag key named either `TagKey1` or `tagkey1`, but not both.
+ AWS services that support these attributes might allow you to create multiple key names that differ only by case. For example, you might tag an Amazon EC2 instance with `ec2=test1` and `EC2=test2`. When you use a condition such as `"aws:ResourceTag/EC2": "test1"` to allow access to that resource, the key name matches both tags, but only one value matches. This can result in unexpected condition failures.

**Important**  
As a best practice, make sure that members of your account follow a consistent naming convention when naming key–value pair attributes. Examples include tags or AWS KMS encryption contexts. You can enforce this using the [`aws:TagKeys`](reference_policies_condition-keys.md#condition-keys-tagkeys) context key for tagging, or the [https://docs.aws.amazon.com/kms/latest/developerguide/policy-conditions.html#conditions-kms-encryption-context-keys](https://docs.aws.amazon.com/kms/latest/developerguide/policy-conditions.html#conditions-kms-encryption-context-keys) for the AWS KMS encryption context.
+ For a list of all of the condition operators and a description of how they work, see [Condition operators](reference_policies_elements_condition_operators.md).
+ Unless otherwise specified, all context keys can have multiple values. For a description of how to handle context keys that have multiple values, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys).
+ For a list of all of the globally available context keys, see [AWS global condition context keys](reference_policies_condition-keys.md).
+ For condition context keys that are defined by each service, see [Actions, Resources, and Condition Keys for AWS Services](reference_policies_actions-resources-contextkeys.html).

## The request context


When a [principal](https://docs.aws.amazon.com/glossary/latest/reference/glos-chap.html?icmpid=docs_homepage_addtlrcs#principal) makes a [request](intro-structure.md#intro-structure-request) to AWS, AWS gathers the request information into a request context. The request context includes information about the principal, resources, actions, and other environmental properties. Policy evaluation matches the properties in the policy against the properties sent in the request to evaluate and authorize actions you can perform in AWS.

You can use the `Condition` element of a JSON policy to test specific context keys against the request context. For example, you can create a policy that uses the [aws:CurrentTime](reference_policies_condition-keys.md#condition-keys-currenttime) context key to [allow a user to perform actions within only a specific range of dates](reference_policies_examples_aws-dates.md).

The following example shows a representation of the request context when Martha Rivera sends a request to deactivate her MFA device.

```
Principal: AROA123456789EXAMPLE
Action: iam:DeactivateMFADevice
Resource: arn:aws:iam::user/martha
Context:
  – aws:UserId=AROA123456789EXAMPLE:martha
  – aws:PrincipalAccount=1123456789012
  – aws:PrincipalOrgId=o-example
  – aws:PrincipalARN=arn:aws:iam::1123456789012:assumed-role/TestAR
  – aws:MultiFactorAuthPresent=true
  – aws:MultiFactorAuthAge=2800
  – aws:CurrentTime=...
  – aws:EpochTime=...
  – aws:SourceIp=...
```

The request context is matched against a policy that allows users to remove their own multi-factor authentication (MFA) device, but only if they have signed in using MFA in the last hour (3,600 seconds).

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Sid": "AllowRemoveMfaOnlyIfRecentMfa",
        "Effect": "Allow",
        "Action": [
            "iam:DeactivateMFADevice"
        ],
        "Resource": "arn:aws:iam::*:user/${aws:username}",
        "Condition": {
            "NumericLessThanEquals": {"aws:MultiFactorAuthAge": "3600"}
        }
    }
}
```

------

In this example, the policy matches the request context: the action is the same, the resource matches the “\$1” wildcard, and the value for `aws:MultiFactorAuthAge` is 2800, which is less than 3600, so the policy allows this authorization request.

AWS evaluates each context key in the policy and returns a value of *true* or *false*. A context key that is not present in the request is considered a mismatch.

The request context can return the following values:
+ **True** – If the requester signed in using MFA in the last one hour or less, then the condition returns *true*.
+ **False** – If the requester signed in using MFA more than one hour ago, then the condition returns *false*.
  + **Not present** – If the requester made a request using their IAM user access keys in the AWS CLI or AWS API, the key is not present. In this case, the key is not present, and it won't match.

**Note**  
In some cases, when the condition key value is not present, the condition can still return true. For example, if you add the `ForAllValues` qualifier, the request returns true if the context key is not in the request. To prevent missing context keys or context keys with empty values from evaluating to true, you can include the [Null condition operator](reference_policies_elements_condition_operators.md#Conditions_Null) in your policy with a `false` value to check if the context key exists and its value is not null.

## The condition block


The following example shows the basic format of a `Condition` element:

```
"Condition": {"StringLike": {"s3:prefix": ["jane/*"]}}
```

A value from the request is represented by a context key, in this case `s3:prefix`. The context key value is compared to a value that you specify as a literal value, such as `jane/*`. The type of comparison to make is specified by the [condition operator](reference_policies_elements_condition_operators.md) (here, `StringLike`). You can create conditions that compare strings, dates, numbers, and more using typical Boolean comparisons such as equals, greater than, and less than. When you use [string operators](reference_policies_elements_condition_operators.md#Conditions_String) or [ARN operators](reference_policies_elements_condition_operators.md#Conditions_ARN), you can also use a [policy variable](reference_policies_variables.md) in the context key value. The following example includes the `aws:username` variable. 

```
"Condition": {"StringLike": {"s3:prefix": ["${aws:username}/*"]}}
```

Under some circumstances, context keys can contain multiple values. For example, a request to Amazon DynamoDB might ask to return or update multiple attributes from a table. A policy for access to DynamoDB tables can include the `dynamodb:Attributes` context key, which contains all the attributes listed in the request. You can test the multiple attributes in the request against a list of allowed attributes in a policy by using set operators in the `Condition` element. For more information, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys). 

When the policy is evaluated during a request, AWS replaces the key with the corresponding value from the request. (In this example, AWS would use the date and time of the request.) The condition is evaluated to return true or false, which is then factored into whether the policy as a whole allows or denies the request. 

### Multiple values in a condition


A `Condition` element can contain multiple condition operators, and each condition operator can contain multiple context key-value pairs. The following figure illustrates this. 

![\[two condition operator block diagrams. The first block includes two context key placeholders, each with multiple values. The second condition block includes one context key with multiple values.\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/AccessPolicyLanguage_Condition_Block.diagram.png)


For more information, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys). 

# IAM JSON policy elements: Condition operators
Condition operators

<a name="topiclist"></a>

Use condition operators in the `Condition` element to match the condition key and value in the policy against values in the request context. For more information about the `Condition` element, see [IAM JSON policy elements: Condition](reference_policies_elements_condition.md).

The condition operator that you can use in a policy depends on the condition key you choose. You can choose a global condition key or a service-specific condition key. To learn which condition operator you can use for a global condition key, see [AWS global condition context keys](reference_policies_condition-keys.md). To learn which condition operator you can use for a service-specific condition key, see [Actions, Resources, and Condition Keys for AWS Services](reference_policies_actions-resources-contextkeys.html) and choose the service that you want to view.

**Important**  
If the key that you specify in a policy condition is not present in the request context, the values do not match and the condition is *false*. If the policy condition requires that the key is *not* matched, such as `StringNotLike` or `ArnNotLike`, and the right key is not present, the condition is *true*. This logic applies to all condition operators except [...IfExists](#Conditions_IfExists) and [Null check](#Conditions_Null). These operators test whether the key is present (exists) in the request context.

The condition operators can be grouped into the following categories:
+ [String](#Conditions_String)
+ [Numeric](#Conditions_Numeric)
+ [Date and time](#Conditions_Date)
+ [Boolean](#Conditions_Boolean)
+ [Binary](#Conditions_BinaryEquals)
+ [IP address](#Conditions_IPAddress)
+ [Amazon Resource Name (ARN)](#Conditions_ARN) (available for only some services.)
+ [...IfExists](#Conditions_IfExists) (checks if the key value exists as part of another check)
+ [Null check](#Conditions_Null) (checks if the key value exists as a standalone check)

## String condition operators


String condition operators let you construct `Condition` elements that restrict access based on comparing a key to a string value.
+  **Policy variables** – [Supported](reference_policies_variables.md)
+ **Wildcards** – [Supported](#Conditions_String-wildcard)


****  

| Condition operator | Description | 
| --- | --- | 
|   `StringEquals`   |  Exact matching, case sensitive  | 
|   `StringNotEquals`   |  Negated matching  | 
|   `StringEqualsIgnoreCase`   |  Exact matching, ignoring case  | 
|   `StringNotEqualsIgnoreCase`   |  Negated matching, ignoring case  | 
|   `StringLike`   | Case-sensitive matching. The values can include multi-character match wildcards (\$1) and single-character match wildcards (?) anywhere in the string. You must specify wildcards to achieve partial string matches.   If a key contains multiple values, `StringLike` can be qualified with set operators—`ForAllValues:StringLike` and `ForAnyValue:StringLike`. For more information, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys).   | 
|   `StringNotLike`   |  Negated case-sensitive matching. The values can include multi-character match wildcards (\$1) or single-character match wildcards (?) anywhere in the string.  | 

**Example string condition operator**  
For example, the following statement contains a `Condition` element that uses [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag) key to specify that the principal making the request must be tagged with the `iamuser-admin` job category.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "iam:*AccessKey*",
        "Resource": "arn:aws:iam::111122223333:user/*",
        "Condition": {
            "StringEquals": {
                "aws:PrincipalTag/job-category": "iamuser-admin"
            }
        }
    }
}
```
If the key that you specify in a policy condition is not present in the request context, the values do not match. In this example, the `aws:PrincipalTag/job-category` key is present in the request context if the principal is using an IAM user with attached tags. It is also included for a principal using an IAM role with attached tags or session tags. If a user without the tag attempts to view or edit an access key, the condition returns `false` and the request is implicitly denied by this statement.  
The following table shows how AWS evaluates this policy based on the condition key values in your request.  


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/job-category": "iamuser-admin"<br />}</pre>  | <pre>aws:PrincipalTag/job-category:<br />  – iamuser-admin</pre>  |  Match | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/job-category": "iamuser-admin"<br />}</pre>  | <pre>aws:PrincipalTag/job-category:<br />  – dev-ops</pre>  | No match | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/job-category": "iamuser-admin"<br />}</pre>  |  No `aws:PrincipalTag/job-category` in the request context.  | No match | 

**Example using a policy variable with a string condition operator**  
The following example uses the `StringLike` condition operator to perform string matching with a [policy variable](reference_policies_variables.md) to create a policy that lets an IAM user use the Amazon S3 console to manage his or her own "home directory" in an Amazon S3 bucket. The policy allows the specified actions on an S3 bucket as long as the `s3:prefix` matches any one of the specified patterns.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListAllMyBuckets",
        "s3:GetBucketLocation"
      ],
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
      "Condition": {
        "StringLike": {
          "s3:prefix": [
            "",
            "home/",
            "home/${aws:username}/"
          ]
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/home/${aws:username}",
        "arn:aws:s3:::amzn-s3-demo-bucket/home/${aws:username}/*"
      ]
    }
  ]
}
```
The following table shows how AWS evaluates this policy for different users based on the [aws:username](reference_policies_condition-keys.md#condition-keys-username) value in the request context.  


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"StringLike": {<br />  "s3:prefix": [<br />    "home/",<br />    "home/${aws:username}/"<br />  ]<br />}</pre>  | <pre>aws:username:<br />  – martha_rivera</pre>  | <pre>"StringLike": {<br />  "s3:prefix": [<br />    "home/",<br />    "home/martha_rivera/"<br />  ]<br />}</pre>  | 
|  <pre>"StringLike": {<br />  "s3:prefix": [<br />    "home/",<br />    "home/${aws:username}/"<br />  ]<br />}</pre>  |  <pre>aws:username:<br />  – nikki_wolf</pre>  |  <pre>"StringLike": {<br />  "s3:prefix": [<br />    "home/",<br />    "home/nikki_wolf/"<br />  ]<br />}</pre>  | 
|  <pre>"StringLike": {<br />  "s3:prefix": [<br />    "home/",<br />    "home/${aws:username}/"<br />  ]<br />}</pre>  |  No `aws:username` in the request context.  | No match | 
For an example of a policy that shows how to use the `Condition` element to restrict access to resources based on an application ID and a user ID for OIDC federation, see [Amazon S3: Allows Amazon Cognito users to access objects in their bucket](reference_policies_examples_s3_cognito-bucket.md). 

### Multivalued string condition operators


If a key in the request contains multiple values, string operators can be qualified with set operators `ForAllValues` and `ForAnyValue`. For more information on the evaluation logic of multiple context keys or values, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys).


| Condition operator | Description | 
| --- | --- | 
|  `ForAllValues:StringEquals` `ForAllValues:StringEqualsIgnoreCase`  |  All of the values for the condition key in the request must match at least one of the values in your policy.  | 
|  `ForAnyValue:StringEquals` `ForAnyValue:StringEqualsIgnoreCase`  |  At least one condition key value in the request must match one of the values in your policy.  | 
|  `ForAllValues:StringNotEquals` `ForAllValues:StringNotEqualsIgnoreCase`  |  Negated matching. None of the values of the context key in the request can match any of the context key values in your policy.  | 
|  `ForAnyValue:StringNotEquals` `ForAnyValue:StringNotEqualsIgnoreCase`  |  Negated matching. At least one context key value in the request must NOT match any of values in the context key in your policy.  | 
|  `ForAllValues:StringLike`  |  All of the values for the condition key in the request must match at least one of the values in your policy.  | 
|  `ForAnyValue:StringLike`  |  At least one condition key value in the request must match one of the values in your policy.  | 
|  `ForAllValues:StringNotLike`  |  Negated matching. None of the values of the context key in the request can match any of the context key values in your policy.  | 
|  `ForAnyValue:StringNotLike`  |  Negated matching. At least one context key value in the request must NOT match any of values in the context key in your policy.  | 

**Example using `ForAnyValue` with a string condition operator**  
This example shows how you might create an identity-based policy that allows using the Amazon EC2 `CreateTags` action to attach tags to an instance. When you use `StringEqualsIgnoreCase`, you can attach tags only if the tag contains the `environment` key with the `preprod` or `storage` values. When you append `IgnoreCase` to the operator, you allow any existing tag value capitalization, such as `preprod`, `Preprod`, and `PreProd`, to resolve to true.  
When you add the `ForAnyValue` modifier with the [aws:TagKeys](reference_policies_condition-keys.md#condition-keys-tagkeys) condition key, at least one tag key value in the request must match the value `environment`. `ForAnyValue` comparison is case sensitive, which stops users from using the incorrect case for the tag key, such as using `Environment` instead of `environment`.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "ec2:CreateTags",
    "Resource": "arn:aws:ec2:*:*:instance/*",
    "Condition": {
      "StringEqualsIgnoreCase": {
        "aws:RequestTag/environment": [
          "preprod",
          "storage"
        ]
      },
      "ForAnyValue:StringEquals": {
        "aws:TagKeys": "environment"
      }
    }
  }
}
```
 The following table shows how AWS evaluates this policy based on the condition key values in your request.   


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />aws:RequestTag/environment:<br />  – preprod</pre>  | Match  | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – costcenter<br />aws:RequestTag/environment:<br />  – PreProd</pre>  | Match  | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  | <pre>aws:TagKeys:<br />  – Environment<br />aws:RequestTag/Environment:<br />  – preprod</pre>  | No match  | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  | <pre>aws:TagKeys:<br />  – costcenter<br />aws:RequestTag/environment:<br />  – preprod</pre>  | No match  | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  |  No `aws:TagKeys` in the request context. <pre>aws:RequestTag/environment:<br />  – storage</pre>  | No match  | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment</pre> No `aws:RequestTag/environment` in the request context.  | No match  | 
|  <pre>"StringEqualsIgnoreCase": {<br />  "aws:RequestTag/environment": [<br />    "preprod",<br />    "storage"<br />  ]<br />},<br />"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "environment"<br />}</pre>  |  No `aws:TagKeys` in the request context. No `aws:RequestTag/environment` in the request context.  | No match  | 

### Wildcard matching


String condition operators perform a patternless matching that does not enforce a predefined format. ARN and Date condition operators are a subset of string operators that enforce a structure on the condition key value.

We recommend you use condition operators that correspond to the values you're comparing keys to. For example, you should use [String condition operators](#Conditions_String) when comparing keys to string values. Similarly, you should use [Amazon Resource Name (ARN) condition operators](#Conditions_ARN) when comparing keys to ARN values.

**Example**  
This example shows how you might create a boundary around resources in your organization. The condition in this policy denies access to Amazon S3 actions unless the resource being accessed is in a specific set of organizational units (OUs) in AWS Organizations. An AWS Organizations path is a text representation of the structure of an organization's entity.  
The condition requires that `aws:ResourceOrgPaths` contains any of the listed OU paths. Because `aws:ResourceOrgPaths` is a multi-value condition, the policy uses the `ForAllValues:StringNotLike` operator to compare the values of `aws:ResourceOrgPaths` to the list of OUs in the policy.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyS3AccessOutsideMyBoundary",
      "Effect": "Deny",
      "Action": [
        "s3:*"
      ],
      "Resource": "*",
      "Condition": {
        "ForAllValues:StringNotLike": {
          "aws:ResourceOrgPaths": [
            "o-acorg/r-acroot/ou-acroot-mediaou/",
            "o-acorg/r-acroot/ou-acroot-sportsou/*"
          ] 
        }
      }
    }
  ]
}
```
The following table shows how AWS evaluates this policy based on the condition key values in your request.  


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"ForAllValues:StringNotLike": {<br />  "aws:ResourceOrgPaths": [<br />    "o-acorg/r-acroot/ou-acroot-mediaou/",<br />    "o-acorg/r-acroot/ou-acroot-sportsou/*"<br />  ] <br />}</pre>  | <pre>aws:ResourceOrgPaths:<br />  – o-acorg/r-acroot/ou-acroot-sportsou/costcenter/</pre>  | Match | 
|  <pre>"ForAllValues:StringNotLike": {<br />  "aws:ResourceOrgPaths": [<br />    "o-acorg/r-acroot/ou-acroot-mediaou/",<br />    "o-acorg/r-acroot/ou-acroot-sportsou/*"<br />  ] <br />}</pre>  | <pre>aws:ResourceOrgPaths:<br />  – o-acorg/r-acroot/ou-acroot-mediaou/costcenter/</pre>  | No match | 
|  <pre>"ForAllValues:StringNotLike": {<br />  "aws:ResourceOrgPaths": [<br />    "o-acorg/r-acroot/ou-acroot-mediaou/",<br />    "o-acorg/r-acroot/ou-acroot-sportsou/*"<br />  ] <br />}</pre>  |  No `aws:ResourceOrgPaths:` in the request.  | No match | 

## Numeric condition operators


Numeric condition operators let you construct `Condition` elements that restrict access based on comparing a key to an integer or decimal value.
+  **Policy variables** – Not supported
+ **Wildcards** – Not supported


****  

| Condition operator | Description | 
| --- | --- | 
|   `NumericEquals`   |  Matching  | 
|   `NumericNotEquals`   |  Negated matching  | 
|   `NumericLessThan`   |  "Less than" matching  | 
|   `NumericLessThanEquals`   |  "Less than or equals" matching  | 
|   `NumericGreaterThan`   |  "Greater than" matching  | 
|   `NumericGreaterThanEquals`   |  "Greater than or equals" matching  | 

For example, the following statement contains a `Condition` element that uses the `NumericLessThanEquals` condition operator with the `s3:max-keys` key to specify that the requester can list *up to* 10 objects in `amzn-s3-demo-bucket` at a time.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
    "Condition": {"NumericLessThanEquals": {"s3:max-keys": "10"}}
  }
}
```

------

If the key that you specify in a policy condition is not present in the request context, the values do not match. In this example, the `s3:max-keys` key is always present in the request when you perform the `ListBucket` operation. If this policy allowed all Amazon S3 operations, then only the operations that include the `max-keys` context key with a value of less than or equal to 10 would be allowed. 

## Date condition operators


Date condition operators let you construct `Condition` elements that restrict access based on comparing a key to a date/time value. You use these condition operators with [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-currenttime](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-currenttime) key or [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-epochtime](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-epochtime) key. You must specify date/time values with one of the [W3C implementations of the ISO 8601 date formats](http://www.w3.org/TR/NOTE-datetime) or in epoch (UNIX) time. 
+  **Policy variables** – Not supported
+ **Wildcards** – Not supported


****  

| Condition operator | Description | 
| --- | --- | 
|   `DateEquals`   |  Matching a specific date  | 
|   `DateNotEquals`   |  Negated matching  | 
|   `DateLessThan`   |  Matching before a specific date and time  | 
|   `DateLessThanEquals`   |  Matching at or before a specific date and time  | 
|   `DateGreaterThan`   |  Matching after a specific a date and time  | 
|   `DateGreaterThanEquals`   |  Matching at or after a specific date and time  | 

For example, the following statement contains a `Condition` element that uses the `DateGreaterThan` condition operator with the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tokenissuetime](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tokenissuetime) key. This condition specifies that the temporary security credentials used to make the request were issued in 2020. This policy can be updated programmatically every day to ensure that account members use fresh credentials.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "iam:*AccessKey*",
        "Resource": "arn:aws:iam::111122223333:user/*",
        "Condition": {
            "DateGreaterThan": {
                "aws:TokenIssueTime": "2020-01-01T00:00:01Z"
            }
        }
    }
}
```

------

If the key that you specify in a policy condition is not present in the request context, the values do not match. The `aws:TokenIssueTime` key is present in the request context only when the principal uses temporary credentials to make the request. The key is not present in AWS CLI, AWS API, or AWS SDK requests that are made using access keys. In this example, if an IAM user attempts to view or edit an access key, the request is denied.

## Boolean condition operators


Boolean conditions let you construct `Condition` elements that restrict access based on comparing a key to `true` or `false`.

If a key contains multiple values, boolean operators can be qualified with set operators `ForAllValues` and `ForAnyValue`. For more information on the evaluation logic of multiple context keys or values, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys).
+  **Policy variables** – [Supported](reference_policies_variables.md)
+ **Wildcards** – Not supported


****  

| Condition operator | Description | 
| --- | --- | 
|   `Bool`   |  Boolean matching  | 
|   `ForAllValues:Bool`   |  Use with the Array of Bool data type. All of the booleans in the context key values must match the boolean values in your policy. To prevent `ForAllValues` operators from evaluating missing context keys or context keys with empty values as Allowed, you can include the [Null condition operator](#Conditions_Null) in your policy.  | 
|   `ForAnyValue:Bool`   |  Use with the Array of Bool data type. At least one of the booleans in the context key values must match the boolean values in your policy.  | 

**Example boolean condition operator**  
The following identity-based policy uses the `Bool` condition operator with the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-securetransport](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-securetransport) key to deny replicating objects and object tags to the destination bucket and its contents if the request is not over SSL.  
This policy does not allow any actions. Use this policy in combination with other policies that allow specific actions.   
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "BooleanExample",
      "Action": "s3:ReplicateObject",
      "Effect": "Deny",
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket",
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    }
  ]
}
```
The following table shows how AWS evaluates this policy based on the condition key values in your request.  


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"Bool": {<br />  "aws:SecureTransport": "false"<br />}</pre>  | <pre>aws:SecureTransport:<br />  – false</pre>  | Match | 
|  <pre>"Bool": {<br />  "aws:SecureTransport": "false"<br />}</pre>  | <pre>aws:SecureTransport:<br />  – true</pre>  | No match | 
|  <pre>"Bool": {<br />  "aws:SecureTransport": "false"<br />}</pre>  |  No `aws:SecureTransport` in the request context.  | No match | 

## Binary condition operators


The `BinaryEquals` condition operator lets you construct `Condition` elements that test key values that are in binary format. It compares the value of the specified key byte for byte against a [base-64](https://en.wikipedia.org/wiki/Base64) encoded representation of the binary value in the policy. If the key that you specify in a policy condition is not present in the request context, the values do not match.
+  **Policy variables** – Not supported
+ **Wildcards** – Not supported

```
"Condition" : {
  "BinaryEquals": {
    "key" : "QmluYXJ5VmFsdWVJbkJhc2U2NA=="
  }
}
```


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"BinaryEquals": {<br />  "key" : "QmluYXJ5VmFsdWVJbkJhc2U2NA=="<br />}</pre>  | <pre>key:<br />  – QmluYXJ5VmFsdWVJbkJhc2U2NA==</pre>  | Match | 
|  <pre>"BinaryEquals": {<br />  "key" : "QmluYXJ5VmFsdWVJbkJhc2U2NA=="<br />}</pre>  | <pre>key:<br />  – ASIAIOSFODNN7EXAMPLE</pre>  | No match | 
|  <pre>"BinaryEquals": {<br />  "key" : "QmluYXJ5VmFsdWVJbkJhc2U2NA=="<br />}</pre>  |  No `key` in the request context.  | No match | 

## IP address condition operators


IP address condition operators let you construct `Condition` elements that restrict access based on comparing a key to an IPv4 or IPv6 address or range of IP addresses. You use these with the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceip](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceip) key. The value must be in the standard CIDR format (for example, 203.0.113.0/24 or 2001:DB8:1234:5678::/64). If you specify an IP address without the associated routing prefix, IAM uses the default prefix value of `/32`.

Some AWS services support IPv6, using :: to represent a range of 0s. To learn whether a service supports IPv6, see the documentation for that service.
+  **Policy variables** – Not supported
+ **Wildcards** – Not supported


****  

| Condition operator | Description | 
| --- | --- | 
|   `IpAddress`   |  The specified IP address or range  | 
|   `NotIpAddress`   |  All IP addresses except the specified IP address or range  | 

**Example IP address condition operator**  
The following statement uses the `IpAddress` condition operator with the `aws:SourceIp` key to specify that the request must come from the IP range 203.0.113.0 to 203.0.113.255.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "iam:*AccessKey*",
        "Resource": "arn:aws:iam::111122223333:user/*",
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": "203.0.113.0/24"
            }
        }
    }
}
```
The `aws:SourceIp` condition key resolves to the IP address that the request originates from. If the requests originates from an Amazon EC2 instance, `aws:SourceIp` evaluates to the instance's public IP address.   
If the key that you specify in a policy condition is not present in the request context, the values do not match. The `aws:SourceIp` key is always present in the request context, except when the requester uses a VPC endpoint to make the request. In this case, the condition returns `false` and the request is implicitly denied by this statement.  
The following table shows how AWS evaluates this policy based on the condition key values in your request.  


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"IpAddress": {<br />  "aws:SourceIp": "203.0.113.0/24"<br />}</pre>  | <pre>aws:SourceIp:<br />  – 203.0.113.1</pre>  | Match | 
|  <pre>"IpAddress": {<br />  "aws:SourceIp": "203.0.113.0/24"<br />}</pre>  | <pre>aws:SourceIp:<br />  – 198.51.100.1</pre>  | No match | 
The following example shows how to mix IPv4 and IPv6 addresses to cover all of your organization's valid IP addresses. We recommend that you update your organization's policies with your IPv6 address ranges in addition to IPv4 ranges you already have to ensure the policies continue to work as you make the transition to IPv6.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "someservice:*",
    "Resource": "*",
    "Condition": {
      "IpAddress": {
        "aws:SourceIp": [
          "203.0.113.0/24",
          "2001:DB8:1234:5678::/64"
        ]
      }
    }
  }
}
```
The `aws:SourceIp` condition key works only in a JSON policy if you are calling the tested API directly as a user. If you instead use a service to call the target service on your behalf, the target service sees the IP address of the calling service rather than the IP address of the originating user. This can happen, for example, if you use AWS CloudFormation to call Amazon EC2 to construct instances for you. There is currently no way to pass the originating IP address through a calling service to the target service for evaluation in a JSON policy. For these types of service API calls, do not use the `aws:SourceIp` condition key.

## Amazon Resource Name (ARN) condition operators


Amazon Resource Name (ARN) condition operators let you construct `Condition` elements that restrict access based on comparing a key to an ARN. The ARN is considered a string.
+  **Policy variables** – [Supported](reference_policies_variables.md)
+ **Wildcards** – [Supported](reference_policies_elements_resource.md#reference_policies_elements_resource_wildcards)


****  

| Condition operator | Description | 
| --- | --- | 
|   `ArnEquals`, `ArnLike`  |  Case-sensitive matching of the ARN. Each of the six colon-delimited components of the ARN is checked separately and each can include multi-character match wildcards (\$1) or single-character match wildcards (?). The `ArnEquals` and `ArnLike` condition operators behave identically.  | 
|   `ArnNotEquals`, `ArnNotLike`  |  Negated matching for ARN. The `ArnNotEquals` and `ArnNotLike` condition operators behave identically.  | 

**Example ARN condition operator**  
The following resource-based policy example shows a policy attached to an Amazon SQS queue to which you want to send SNS messages. It gives Amazon SNS permission to send messages to the queue (or queues) of your choice, but only if the service is sending the messages on behalf of a particular Amazon SNS topic (or topics). You specify the queue in the `Resource` field, and the Amazon SNS topic as the value for the `SourceArn` key.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Principal": {
            "Service": "sns.amazonaws.com"
        },
        "Action": "SQS:SendMessage",
        "Resource": "arn:aws:sqs:us-east-1:123456789012:QUEUE-ID",
        "Condition": {
            "ArnEquals": {
                "aws:SourceArn": "arn:aws:sns:us-east-1:123456789012:TOPIC-ID"
            }
        }
    }
}
```
The [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn) key is present in the request context only if a resource triggers a service to call another service on behalf of the resource owner. If an IAM user attempts to perform this operation directly, the condition returns `false` and the request is implicitly denied by this statement.  
The following table shows how AWS evaluates this policy based on the condition key values in your request.  


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"ArnEquals": {<br />  "aws:SourceArn": "arn:aws:sns:us-west-2:123456789012:TOPIC-ID"<br />}</pre>  | <pre>aws:SourceArn:<br />  – arn:aws:sns:us-west-2:123456789012:TOPIC-ID</pre>  | Match | 
|  <pre>"ArnEquals": {<br />  "aws:SourceArn": "arn:aws:sns:us-west-2:123456789012:TOPIC-ID"<br />}</pre>  | <pre>aws:SourceArn:<br />  – arn:aws:sns:us-west-2:777788889999:TOPIC-ID</pre>  | No match | 
|  <pre>"ArnEquals": {<br />  "aws:SourceArn": "arn:aws:sns:us-west-2:123456789012:TOPIC-ID"<br />}</pre>  |  No `aws:SourceArn` in the request context.  | No match | 

### Multivalued ARN condition operators


If a key in the request contains multiple values, ARN operators can be qualified with set operators `ForAllValues` and `ForAnyValue`. For more information on the evaluation logic of multiple context keys or values, see [Set operators for multivalued context keys](reference_policies_condition-single-vs-multi-valued-context-keys.md#reference_policies_condition-multi-valued-context-keys).


| Condition operator | Description | 
| --- | --- | 
|  `ForAllValues:ArnEquals` `ForAllValues:ArnLike`  |  All of the ARNs in the request context must match at least one of the ARN patterns in your policy.  | 
|  `ForAnyValue:ArnEquals` `ForAnyValue:ArnLike`  |  At least one ARN in the request context must match one of the ARN patterns in your policy.  | 
|  `ForAllValues:ArnNotEquals` `ForAllValues:ArnNotLike`  |  Negated matching. None of the ARNs in the request context can match any string ARN patterns in your policy.  | 
|  `ForAnyValue:ArnNotEquals` `ForAnyValue:ArnNotLike`  |  Negated matching. At least one ARN in the request context must NOT match any of ARN patterns in your policy.  | 

**Example using `ForAllValues` with an ARN condition operator**  
The following example uses `ForAllValues:ArnLike` to create or update a logical delivery source for Amazon CloudWatch Logs logs. The condition block includes the condition key [https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-policy-keys](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-policy-keys) to filter the log generating resource ARNs passed in the request. Using this condition operator, all of the ARNs in the request must match at least one ARN in the policy.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "logs:PutDeliverySource",
            "Resource": "arn:aws:logs:us-east-1:123456789012:delivery-source:*",
            "Condition": {
                "ForAllValues:ArnLike": {
                    "logs:LogGeneratingResourceArns": [
                        "arn:aws:cloudfront::123456789012:distribution/*",
                        "arn:aws:cloudfront::123456789012:distribution/support*"
                    ]
                }
            }
        }
    ]
}
```
The following table shows how AWS evaluates this policy based on the condition key values in your request.  


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"ForAllValues:ArnLike": {<br />  "logs:LogGeneratingResourceArns": [<br />    "arn:aws::cloudfront:123456789012:distribution/*",<br />    "arn:aws::cloudfront:123456789012:distribution/support*"<br />  ]<br />}</pre>  | <pre>logs:LogGeneratingResourceArns:<br />  – arn:aws::cloudfront:123456789012:distribution/costcenter</pre>  | Match | 
|  <pre>"ForAllValues:ArnLike": {<br />  "logs:LogGeneratingResourceArns": [<br />    "arn:aws::cloudfront:123456789012:distribution/*",<br />    "arn:aws::cloudfront:123456789012:distribution/support*"<br />  ]<br />}</pre>  | <pre>logs:LogGeneratingResourceArns:<br />  – arn:aws::cloudfront:123456789012:distribution/costcenter<br />  – arn:aws::cloudfront:123456789012:distribution/support2025</pre>  | Match | 
|  <pre>"ForAllValues:ArnLike": {<br />  "logs:LogGeneratingResourceArns": [<br />    "arn:aws::cloudfront:123456789012:distribution/*",<br />    "arn:aws::cloudfront:123456789012:distribution/support*"<br />  ]<br />}</pre>  | <pre>logs:LogGeneratingResourceArns:<br />  – arn:aws::cloudfront:123456789012:distribution/costcenter<br />  – arn:aws::cloudfront:123456789012:distribution/admin</pre>  | No match | 
|  <pre>"ForAllValues:ArnLike": {<br />  "logs:LogGeneratingResourceArns": [<br />    "arn:aws::cloudfront:123456789012:distribution/*",<br />    "arn:aws::cloudfront:123456789012:distribution/support*"<br />  ]<br />}</pre>  | <pre>logs:LogGeneratingResourceArns:<br />  – arn:aws::cloudfront:777788889999:distribution/costcenter</pre>  | No match | 
|  <pre>"ForAllValues:ArnLike": {<br />  "logs:LogGeneratingResourceArns": [<br />    "arn:aws::cloudfront:123456789012:distribution/*",<br />    "arn:aws::cloudfront:123456789012:distribution/support*"<br />  ]<br />}</pre>  |  No `logs:LogGeneratingResourceArns` in the request context.  | Match  | 
The `ForAllValues` qualifier returns true if there are no context keys in the request or if the context key value resolves to a null dataset, such as an empty string. To prevent missing context keys or context keys with empty values from evaluating to true, you can include the [Null condition operator](#Conditions_Null) in your policy with a `false` value to check if the context key exists and its value is not null.

## ...IfExists condition operators


You can add `IfExists` to the end of any condition operator name except the `Null` condition—for example, `StringLikeIfExists`. You do this to say "If the condition key is present in the context of the request, process the key as specified in the policy. If the key is not present, evaluate the condition element as true." Other condition elements in the statement can still result in a nonmatch, but not a missing key when checked with `...IfExists`. If you are using an `"Effect": "Deny"` element with a negated condition operator like `StringNotEqualsIfExists`, the request is still denied even if the condition key is not present.

**Example using `IfExists`**

Many condition keys describe information about a certain type of resource and only exist when accessing that type of resource. These condition keys are not present on other types of resources. This doesn't cause an issue when the policy statement applies to only one type of resource. However, there are cases where a single statement can apply to multiple types of resources, such as when the policy statement references actions from multiple services or when a given action within a service accesses several different resource types within the same service. In such cases, including a condition key that applies to only one of the resources in the policy statement can cause the `Condition` element in the policy statement to fail such that the statement's `"Effect"` does not apply.

For example, consider the following policy example:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Sid": "THISPOLICYDOESNOTWORK",
    "Effect": "Allow",
    "Action": "ec2:RunInstances",
    "Resource": "*",
    "Condition": {"StringLike": {"ec2:InstanceType": [
      "t1.*",
      "t2.*",
      "m3.*"
    ]}}
  }
}
```

------

The *intent* of the preceding policy is to enable the user to launch any instance that is type `t1`, `t2` or `m3`. However, launching an instance requires accessing many resources in addition to the instance itself; for example, images, key pairs, security groups, and more. The entire statement is evaluated against every resource that is required to launch the instance. These additional resources do not have the `ec2:InstanceType` condition key, so the `StringLike` check fails, and the user is not granted the ability to launch *any* instance type. 

To address this, use the `StringLikeIfExists` condition operator instead. This way, the test only happens if the condition key exists. You could read the following policy as: "If the resource being checked has an "`ec2:InstanceType`" condition key, then allow the action only if the key value begins with `t1.`, `t2.`, or `m3.`. If the resource being checked does not have that condition key, then don't worry about it." The asterisk (\$1) in the condition key values, when used with the `StringLikeIfExists` condition operator, is interpreted as a wildcard to achieve partial string matches. The `DescribeActions` statement includes the actions required to view the instance in the console.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "RunInstance",
      "Effect": "Allow",
      "Action": "ec2:RunInstances",
      "Resource": "*",
      "Condition": {
        "StringLikeIfExists": {
          "ec2:InstanceType": [
            "t1.*",
            "t2.*",
            "m3.*"
          ]
        }
      }
    },
    {
      "Sid": "DescribeActions",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeImages",
        "ec2:DescribeInstances",
        "ec2:DescribeVpcs",
        "ec2:DescribeKeyPairs",
        "ec2:DescribeSubnets",
        "ec2:DescribeSecurityGroups"
      ],
      "Resource": "*"
    }
  ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request.


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"StringLikeIfExists": {<br />  "ec2:InstanceType": [<br />    "t1.*",<br />    "t2.*",<br />    "m3.*"<br />  ]<br />}</pre>  | <pre>ec2:InstanceType:<br />  – t1.micro</pre>  | Match | 
|  <pre>"StringLikeIfExists": {<br />  "ec2:InstanceType": [<br />    "t1.*",<br />    "t2.*",<br />    "m3.*"<br />  ]<br />}</pre>  | <pre>ec2:InstanceType:<br />  – m2.micro</pre>  | No match | 
|  <pre>"StringLikeIfExists": {<br />  "ec2:InstanceType": [<br />    "t1.*",<br />    "t2.*",<br />    "m3.*"<br />  ]<br />}</pre>  |  No `ec2:InstanceType` in the request context.  | Match | 

## Condition operator to check existence of condition keys


Use a `Null` condition operator to check if a condition key is absent at the time of authorization. In the policy statement, use either `true` (the key doesn't exist — it is null) or `false` (the key exists and its value is not null).

You can not use a [policy variable](reference_policies_variables.md) with the `Null` condition operator.

For example, you can use this condition operator to determine whether a user is using temporary credentials or their own credentials to make a request. If the user is using temporary credentials, then the key `aws:TokenIssueTime` exists and has a value. The following example shows a condition that states that the user must be using temporary credentials (the key cannot be absent) for the user to use the Amazon EC2 API.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":{
      "Action":"ec2:*",
      "Effect":"Allow",
      "Resource":"*",
      "Condition":{"Null":{"aws:TokenIssueTime":"false"}}
  }
}
```

------

# Conditions with multiple context keys or values
Conditions with multiple context keys or values

You can use the `Condition` element of a policy to test multiple context keys or multiple values for a single context key in a request. When you make a request to AWS, either programmatically or through the AWS Management Console, your request includes information about your principal, operation, tags, and more. You can use context keys to test the values of the matching context keys in the request, with the context keys specified in the policy condition. To learn about information and data included in a request, see [The request context](reference_policies_elements_condition.md#AccessPolicyLanguage_RequestContext).

**Topics**
+ [

## Evaluation logic for multiple context keys or values
](#reference_policies_multiple-conditions-eval)
+ [

## Evaluation logic for negated matching condition operators
](#reference_policies_multiple-conditions-negated-matching-eval)

## Evaluation logic for multiple context keys or values


A `Condition` element can contain multiple condition operators, and each condition operator can contain multiple context key-value pairs. Most context keys support using multiple values, unless otherwise specified.
+ If your policy statement has multiple [condition operators](reference_policies_elements_condition_operators.md), the condition operators are evaluated using a logical `AND`.
+ If your policy statement has multiple context keys attached to a single condition operator, the context keys are evaluated using a logical `AND`.
+ If a single condition operator includes multiple values for a context key, those values are evaluated using a logical `OR`.
+ If a single negated matching condition operator includes multiple values for a context key, those values are evaluated using a logical `NOR`. 

All context keys in a condition element block must resolve to true to invoke the desired `Allow` or `Deny` effect. The following figure illustrates the evaluation logic for a condition with multiple condition operators and context key-value pairs.

![\[Condition block showing how AND and OR are applied to multiple context keys and values\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/AccessPolicyLanguage_Condition_Block_AND_2.diagram.png)


For example, the following S3 bucket policy illustrates how the previous figure is represented in a policy. The condition block includes condition operators `StringEquals` and `ArnLike`, and context keys `aws:PrincipalTag` and `aws:PrincipalArn`. To invoke the desired `Allow` or `Deny` effect, all context keys in the condition block must resolve to true. The user making the request must have both principal tag keys, *department* and *role*, that include one of the tag key values specified in the policy. Also, the principal ARN of the user making the request must match one of the `aws:PrincipalArn` values specified in the policy to be evaluated as true.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "ExamplePolicy",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::222222222222:root"
      },
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
      "Condition": {
        "StringEquals": {
          "aws:PrincipalTag/department": [
            "finance",
            "hr",
            "legal"
          ],
          "aws:PrincipalTag/role": [
            "audit",
            "security"
          ]
        },
        "ArnLike": {
          "aws:PrincipalArn": [
            "arn:aws:iam::222222222222:user/Ana",
            "arn:aws:iam::222222222222:user/Mary"
          ]
        }
      }
    }
  ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request.


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | <pre>aws:PrincipalTag/department: legal<br />aws:PrincipalTag/role: audit<br />aws:PrincipalArn: <br />  arn:aws:iam::222222222222:user/Mary</pre>  |  **Match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | <pre>aws:PrincipalTag/department: hr<br />aws:PrincipalTag/role: audit<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Nikki</pre>  | **No match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | <pre>aws:PrincipalTag/department: hr<br />aws:PrincipalTag/role: payroll<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Mary</pre>  | **No match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  |  No `aws:PrincipalTag/role` in the request context. <pre>aws:PrincipalTag/department: hr<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Mary</pre>  | **No match**  | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | No `aws:PrincipalTag` in the request context. <pre>aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Mary</pre>  | **No match**  | 

## Evaluation logic for negated matching condition operators


Some [condition operators,](reference_policies_elements_condition_operators.md) such as `StringNotEquals` or `ArnNotLike`, use negated matching to compare the context key-value pairs in your policy against the context key-value pairs in a request. When multiple values are specified for a single context key in a policy with negated matching condition operators, the effective permissions work like a logical `NOR`. In negated matching, a logical `NOR` or `NOT OR` returns true only if all values evaluate to false.

The following figure illustrates the evaluation logic for a condition with multiple condition operators and context key-value pairs. The figure includes a negated matching condition operator for context key 3.

![\[Condition block showing how AND and OR are applied to multiple context keys and values when a negated matching condition operator is used\]](http://docs.aws.amazon.com/IAM/latest/UserGuide/images/AccessPolicyLanguage_Condition_Block_AND_Negated_NOR_2.diagram.png)


For example, the following S3 bucket policy illustrates how the previous figure is represented in a policy. The condition block includes condition operators `StringEquals` and `ArnNotLike`, and context keys `aws:PrincipalTag` and `aws:PrincipalArn`. To invoke the desired `Allow` or `Deny` effect, all context keys in the condition block must resolve to true. The user making the request must have both principal tag keys, *department* and *role*, that include one of the tag key values specified in the policy. Since the `ArnNotLike` condition operator uses negated matching, the principal ARN of the user making the request must not match any of the `aws:PrincipalArn` values specified in the policy to be evaluated as true.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "ExamplePolicy",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::222222222222:root"
      },
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
      "Condition": {
        "StringEquals": {
          "aws:PrincipalTag/department": [
            "finance",
            "hr",
            "legal"
          ],
          "aws:PrincipalTag/role": [
            "audit",
            "security"
          ]
        },
        "ArnNotLike": {
          "aws:PrincipalArn": [
            "arn:aws:iam::222222222222:user/Ana",
            "arn:aws:iam::222222222222:user/Mary"
          ]
        }
      }
    }
  ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request.


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnNotLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | <pre>aws:PrincipalTag/department: legal<br />aws:PrincipalTag/role: audit<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Nikki<br /></pre>  |  **Match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnNotLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | <pre>aws:PrincipalTag/department: hr<br />aws:PrincipalTag/role: audit<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Mary</pre>  | **No match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnNotLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | <pre>aws:PrincipalTag/department: hr<br />aws:PrincipalTag/role: payroll<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Nikki</pre>  | **No match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnNotLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | >No `aws:PrincipalTag/role` in the request context. <pre>aws:PrincipalTag/department: hr<br />aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Nikki</pre>  | **No match** | 
|  <pre>"StringEquals": {<br />  "aws:PrincipalTag/department": [<br />    "finance",<br />    "hr",<br />    "legal"<br />  ],<br />  "aws:PrincipalTag/role": [<br />    "audit",<br />    "security"<br />  ]<br />},<br />"ArnNotLike": {<br />  "aws:PrincipalArn": [<br />      "arn:aws:iam::222222222222:user/Ana",<br />      "arn:aws:iam::222222222222:user/Mary"<br />  ]<br />}</pre>  | No `aws:PrincipalTag` in the request context. <pre>aws:PrincipalArn:<br />  arn:aws:iam::222222222222:user/Nikki</pre>  | **No match**  | 

# Single-valued vs. multivalued context keys


The difference between single-valued and multivalued context keys lies in the number of values in the [request context](intro-structure.md#intro-structure-request), not the number of values in the policy condition.
+ *Single-valued* condition context keys have at most one value in the request context. For example, when you tag resources in AWS, each resource tag is stored as a key-value pair. Since a resource tag key can have only a single tag value, [aws:ResourceTag/*tag-key*](reference_policies_condition-keys.md#condition-keys-resourcetag) is a single-valued context key. Do not use a condition set operator with a single-valued context key.
+ *Multivalued* condition context keys can have multiple values in the request context. For example, when you tag resources in AWS, you can include multiple tag key-value pairs in a single request. Therefore, [aws:TagKeys](reference_policies_condition-keys.md#condition-keys-tagkeys) is a multivalued context key. Multivalued context keys require a condition set operator.

For example, a request can originate from at most one VPC endpoint, so [aws:SourceVpce](reference_policies_condition-keys.md#condition-keys-sourcevpce) is a single-valued context key. Since a service can have more than one service principal name that belongs to the service, [aws:PrincipalServiceNamesList](reference_policies_condition-keys.md#condition-keys-principalservicenameslist) is a multivalued context key.

**Important**  
The difference between single-valued and multivalued context keys depends on the number of values in the request context, not the number of values in the policy condition.

## Key points

+ The *Single-valued* and *Multivalued* classifications are included in the description of each condition context key as *Value type* in the [AWS global condition context keys](reference_policies_condition-keys.md) topic.
+ Multivalued context keys in the [Service Authorization Reference](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html) use an `ArrayOf` prefix followed by the condition operator category type, such as `ArrayOfString` or `ArrayOfARN`, indicating that the request may include multiple values for a condition context key.
+ You can use any available single-valued context key as a policy variable, but you cannot use a multivalued context key as a policy variable. For more information about policy variables, see [IAM policy elements: Variables and tags](reference_policies_variables.md).
+ When using context keys that include key-value pairs, it's important to note that even though there can be multiple tag-key values, each `tag-key` can have only one value.
  + [aws:PrincipalTag/*tag-key*](reference_policies_condition-keys.md#condition-keys-principaltag), [aws:RequestTag/*tag-key*](reference_policies_condition-keys.md#condition-keys-requesttag) and [aws:ResourceTag/*tag-key*](reference_policies_condition-keys.md#condition-keys-resourcetag) are single-valued context keys.
  + [aws:TagKeys](reference_policies_condition-keys.md#condition-keys-tagkeys) defines what tag-keys are allowed in a request but does not include the tag-key values. Because you can include multiple tag key-value pairs in a request, `aws:TagKeys` is a multivalued context key.
+ Multivalued context keys require a condition set operator. Do not use condition set operators `ForAllValues` or `ForAnyValue` with single-valued context keys. Using condition set operators with single-valued context keys can lead to overly permissive policies.

## Set operators for multivalued context keys


To compare your condition context key against a [request context](intro-structure.md#intro-structure-request) key with multiple values, you must use the `ForAllValues` or `ForAnyValue` set operators. These set operators are used to compare two sets of values, such as the set of tags in a request and the set of tags in a policy condition.

The `ForAllValues` and `ForAnyValue` qualifiers add set-operation functionality to the condition operator, allowing you to test request context keys with multiple values against multiple context key values in a policy condition. Additionally, if you include a multivalued string context key in your policy with a wildcard or a variable, you must also use the `StringLike` [condition operator](reference_policies_elements_condition_operators.md#Conditions_String). Multiple condition key values must be enclosed in brackets like an [array](reference_policies_grammar.md#policies-grammar-json), for example, `"Key2":["Value2A", "Value2B"]`.

### ForAllValues


The `ForAllValues` qualifier tests whether the value of every member of the request context matches the condition operator that follows the qualifier. The condition returns `true` if every context key value in the request matches a context key value in the policy. It also returns `true` if there are no context keys in the request.

**Important**  
Use caution if you use `ForAllValues` with an `Allow` effect, as it can be overly permissive if the presence of missing context keys in the request context is unexpected. You should always include the [`Null`](reference_policies_elements_condition_operators.md#Conditions_Null) condition operator in your policy with a `false` value to check if the context key exists and its value is not null. For an example, see [Controlling access based on tag keys](access_tags.md#access_tags_control-tag-keys).

#### Example ForAllValues set operator


In the following example, ForAllValues is used with aws:TagKeys to allow users to delete specific tags assigned to an EC2 instance. This policy allows users to delete only the `environment` and `cost-center` tags. You can delete them separately or together. The tag-keys in the request must match exactly the specified keys in the policy.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:DeleteTags",
            "Resource": "arn:aws:ec2:us-east-1:111122223333:instance/*",
            "Condition": {
                "ForAllValues:StringEquals": {
                    "aws:TagKeys": [
                        "environment",
                        "cost-center"
                    ]
                },
                "Null": {
                    "aws:TagKeys": "false"
                }
            }
        }
    ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request.


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"ForAllValues:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />},<br />"Null": {<br />  "aws:TagKeys": "false"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment</pre>  |  **Match**  | 
|  <pre>"ForAllValues:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />},<br />"Null": {<br />  "aws:TagKeys": "false"<br />}</pre>  | <pre>aws:TagKeys:<br />  – cost-center</pre>  |  **Match**  | 
|  <pre>"ForAllValues:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />},<br />"Null": {<br />  "aws:TagKeys": "false"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – cost-center</pre>  |  **Match**  | 
|  <pre>"ForAllValues:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />},<br />"Null": {<br />  "aws:TagKeys": "false"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – dept</pre>  |  **No match**  | 
|  <pre>"ForAllValues:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />},<br />"Null": {<br />  "aws:TagKeys": "false"<br />}</pre>  |  No `aws:TagKeys` in the request context.  |  **No match**  | 

Note that in the last example, the result is "No Match" because the Null condition check prevents matching when the context key is missing. This is a best practice to avoid overly permissive policies.

### ForAnyValue


The `ForAnyValue` qualifier tests whether at least one member of the set of request context key values matches at least one member of the set of context key values in your policy condition. The condition returns `true` if any one of the context key values in the request matches any one of the context key values in the policy. For no matching context key or if the key does not exist, the condition returns `false`.

**Important**  
When using `ForAnyValue` with a `Deny` effect, if the context key is not present in the request, the policy evaluates as **No match**. For consistent behavior, add an explicit [`Null`](reference_policies_elements_condition_operators.md#Conditions_Null) condition check in your policy to verify whether the context key exists. For details, see [Condition operator to check existence of condition keys](reference_policies_elements_condition_operators.md#Conditions_Null).

#### Example ForAnyValue set operator


In the following example, ForAnyValue is used with aws:TagKeys to allow users to delete specific tags assigned to an EC2 instance. This policy allows users to delete tags for an instance if the tag keys specified in the request include `environment` or `cost-center`. The request can include additional tag keys beyond those specified in the policy, but must include at least one of the specified keys to match the condition.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:DeleteTags",
            "Resource": "arn:aws:ec2:us-east-1:111122223333:instance/*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "aws:TagKeys": [
                        "environment",
                        "cost-center"
                    ]
                }
            }
        }
    ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request.


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment</pre>  |  **Match**  | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – cost-center</pre>  |  **Match**  | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – cost-center</pre>  |  **Match**  | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – dept</pre>  |  **Match**  | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – dept</pre>  |  **No match**  | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": [<br />    "environment",<br />    "cost-center"<br />  ]<br />}</pre>  |  No `aws:TagKeys` in the request context.  |  **No match**  | 

# Condition policy examples


In IAM policies, you can specify multiple values for both single-valued and multivalued context keys for comparison against the request context. The following set of policy examples demonstrates policy conditions with multiple context keys and values.

**Note**  
If you would like to submit a policy to be included in this reference guide, use the **Feedback** button at the bottom of this page. For IAM identity-based policy examples, see [Example IAM identity-based policies](access_policies_examples.md).

## Condition policy examples: Single-valued context keys

+ Multiple condition blocks with single-valued context keys. ([View this example](reference_policies_condition_examples-single-valued-context-keys.md#reference_policies_condition_examples-single-valued-context-keys-1).)
+ One condition block with multiple single-valued context keys and values. ([View this example](reference_policies_condition_examples-single-valued-context-keys.md#reference_policies_condition_examples-single-valued-context-keys-2).)

## Condition policy examples: Multivalued context keys

+ Deny policy with condition set operator `ForAllValues`. ([View this example](reference_policies_condition_examples-multi-valued-context-keys.md#reference_policies_condition_examples-multi-valued-context-keys-1).)
+ Deny policy with condition set operator `ForAnyValue`. ([View this example](reference_policies_condition_examples-multi-valued-context-keys.md#reference_policies_condition_examples-multi-valued-context-keys-2).)

# Multivalued context key examples


The following set of policy examples demonstrate how to create policy conditions with multivalued context keys.

## Example: Deny policy with condition set operator ForAllValues


The following examples show how to use an identity-based policy to deny the use of IAM tagging actions when specific tag key prefixes are included in the request. The values for [`aws:TagKeys`](reference_policies_condition-keys.md#condition-keys-tagkeys) include a wildcard (\$1) for partial string matching. The policy includes the `ForAllValues` set operator with context key `aws:TagKeys` because the request context key can include multiple values. In order for context key `aws:TagKeys` to match, every value in the request context must match at least one value in the policy.

The `ForAllValues` set operator also returns true if there are no context keys in the request.

You can prevent missing context keys or context keys with empty values from evaluating to true by including a `Null` condition operator in your policy with a value of `false` to check if the context key in the request exists and its value is not null. For more information, see [Condition operator to check existence of condition keys](reference_policies_elements_condition_operators.md#Conditions_Null).

**Important**  
This policy does not allow any actions. Use this policy in combination with other policies that allow specific actions.

**Example Deny a single policy condition value for a multivalued context key**  
In the following example, the policy denies requests where the values for `aws:TagKeys` in the request do not include the prefix **key1**. The request context can have multiple values, but because of the `ForAllValues` condition set operator, all the tag key values in the request context must start with the prefix **key1**.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyRestrictedTags",
      "Effect": "Deny",
      "Action": [
        "iam:Tag*",
        "iam:UnTag*"
      ],
      "Resource": [
        "*"
      ],
      "Condition": {
        "ForAllValues:StringNotLike": {
          "aws:TagKeys": "key1*"
        }
      }
    }
  ]
}
```
The following table shows how AWS evaluates this policy based on the condition key values in your request. For a Deny statement, Match is Denied and No match is Not denied, so it may be allowed by another statement.  


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"ForAllValues:StringNotLike": {<br />  "aws:TagKeys": "key1*"<br />}</pre>  | <pre>aws:TagKeys:<br />  – key1:legal</pre>  |  **No match** May be allowed by another statement. | 
| <pre>"ForAllValues:StringNotLike": {<br />  "aws:TagKeys": "key1*"<br />}</pre>  | <pre>aws:TagKeys:<br />  – key1:hr<br />  – key1:personnel</pre>  | **No match** May be allowed by another statement. | 
| <pre>"ForAllValues:StringNotLike": {<br />  "aws:TagKeys": "key1*"<br />}</pre>  | <pre>aws:TagKeys:<br />  – key2:audit</pre>  | **Match** | 
| <pre>"ForAllValues:StringNotLike": {<br />  "aws:TagKeys": "key1*"<br />}</pre>  | No `aws:TagKeys` in the request context.  | **Match** | 

**Example Deny multiple policy condition values for a multivalued context key**  
In the following example, the policy denies requests where the values for `aws:TagKeys` in the request do not include the prefix **key1** or **key2**. The request context can have multiple values, but because of the `ForAllValues` condition set operator, all the tag key values in the request context must start with the prefix **key1** or **key2**.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyRestrictedTags",
      "Effect": "Deny",
      "Action": [
        "iam:Tag*",
        "iam:UnTag*"
      ],
      "Resource": [
        "*"
      ],
      "Condition": {
        "ForAllValues:StringNotLike": {
          "aws:TagKeys": [
            "key1*",
            "key2*"
          ]
        }
      }
    }
  ]
}
```
The following table shows how AWS evaluates this policy based on the condition key values in your request. For a Deny statement, Match is Denied and No match is Not denied, so it may be allowed by another statement.  


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"ForAllValues:StringNotLike": {<br />  "aws:TagKeys": [<br />    "key1*",<br />    "key2*"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – key1:legal</pre>  |  **No match** May be allowed by another statement. | 
| <pre>"ForAllValues:StringNotLike": {<br />   "aws:TagKeys": [<br />    "key1*",<br />    "key2*"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – key1:hr<br />  – key1:personnel</pre>  | **No match** May be allowed by another statement. | 
| <pre>"ForAllValues:StringNotLike": {<br />   "aws:TagKeys": [<br />    "key1*",<br />    "key2*"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – key1:hr<br />  – key2:audit</pre>  | **No match** May be allowed by another statement. | 
| <pre>"ForAllValues:StringNotLike": {<br />   "aws:TagKeys": [<br />    "key1*",<br />    "key2*"<br />  ]<br />}</pre>  | <pre>aws:TagKeys:<br />  – key3:legal</pre>  | **Match**  | 
| <pre>"ForAllValues:StringNotLike": {<br />   "aws:TagKeys": [<br />    "key1*",<br />    "key2*"<br />  ]<br />}</pre>  | No `aws:TagKeys` in the request context.  | **Match** | 

## Example: Deny policy with condition set operator ForAnyValue


The following identity-based policy example denies creating snapshots of EC2 instance volumes if any snapshots are tagged with one of the tag keys specified in the policy, `environment` or `webserver`. The policy includes the `ForAnyValue` set operator with context key `aws:TagKeys` because the request context key can include multiple values. If your tagging request includes any one of the tag key values specified in the policy, the `aws:TagKeys` context key returns true invoking the deny policy effect.

**Important**  
This policy does not allow any actions. Use this policy in combination with other policies that allow specific actions.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Deny",
      "Action": [
        "ec2:CreateSnapshot",
        "ec2:CreateSnapshots"
      ],
      "Resource": "arn:aws:ec2:us-west-2::snapshot/*",
      "Condition": {
        "ForAnyValue:StringEquals": {
          "aws:TagKeys": "webserver"
        }
      }
    }
  ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request. For a Deny statement, Match is Denied and No match is Not denied, so it may be allowed by another statement.


| Policy Condition | Request Context | Result | 
| --- | --- | --- | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "webserver"<br />}</pre>  | <pre>aws:TagKeys:<br />  – webserver</pre>  | **Match** | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "webserver"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – webserver<br />  – test</pre>  |  **Match** | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "webserver"<br />}</pre>  | <pre>aws:TagKeys:<br />  – environment<br />  – test</pre>  | **No match** May be allowed by another statement. | 
|  <pre>"ForAnyValue:StringEquals": {<br />  "aws:TagKeys": "webserver"<br />}</pre>  | No `aws:TagKeys` in the request context.  | **No match** May be allowed by another statement.  | 

# Single-valued context key policy examples


The following set of policy examples demonstrate how to create policy conditions with single-valued context keys.

## Example: Multiple condition blocks with single-valued context keys


When a condition block has multiple conditions, each with a single context key, all context keys must resolve to true for the desired `Allow` or `Deny` effect to be invoked. When you use negated matching condition operators, the evaluation logic of the condition value is reversed.

The following example lets users create EC2 volumes and apply tags to the volumes during volume creation. The request context must include a value for context key `aws:RequestTag/project`, and the value for context key `aws:ResourceTag/environment` can be anything except production.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "ec2:CreateVolume",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "ec2:CreateTags",
      "Resource": "arn:aws:ec2:us-east-1:123456789012:volume/*",
      "Condition": {
        "StringLike": {
          "aws:RequestTag/project": "*"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "ec2:CreateTags",
      "Resource": "arn:aws:ec2:us-east-1:123456789012:*/*",
      "Condition": {
        "StringNotEquals": {
          "aws:ResourceTag/environment": "production"
        }
      }
    }
  ]
}
```

------

The request context must include a project tag-value and cannot be created for a production resource to invoke the `Allow` effect. The following EC2 volume is successfully created because the project name is `Feature3` with a `QA` resource tag.

```
aws ec2 create-volume \
    --availability-zone us-east-1a \
    --volume-type gp2 \
    --size 80 \
    --tag-specifications 'ResourceType=volume,Tags=[{Key=project,Value=Feature3},{Key=environment,Value=QA}]'
```

## Example: One condition block with multiple single-valued context keys and values


When a condition block contains multiple context keys and each context key has multiple values, each context key must resolve to true for at least one key value for the desired `Allow` or `Deny` effect to be invoked. When you use negated matching condition operators, the evaluation logic of the context key value is reversed.

The following example allows users to start and run tasks on Amazon Elastic Container Service clusters.
+ The request context must include `production` **OR** `prod-backup` for the `aws:RequestTag/environment` context key **AND**.
+ The `ecs:cluster` context key makes sure that tasks are run on either the `default1` **OR** `default2` ARN ECS clusters.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecs:RunTask",
        "ecs:StartTask"
      ],
      "Resource": [
        "*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:RequestTag/environment": [
            "production",
            "prod-backup"
          ]
        },
        "ArnEquals": {
          "ecs:cluster": [
            "arn:aws:ecs:us-east-1:111122223333:cluster/default1",
            "arn:aws:ecs:us-east-1:111122223333:cluster/default2"
          ]
        }
      }
    }
  ]
}
```

------

The following table shows how AWS evaluates this policy based on the condition key values in your request.


| Policy condition | Request context | Result | 
| --- | --- | --- | 
|  <pre>"StringEquals": {<br />  "aws:RequestTag/environment": [<br />    "production",<br />    "prod-backup"<br />  ]<br />},<br />"ArnEquals": {<br />  "ecs:cluster": [<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default1",<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default2"<br />  ]<br />}</pre>  | <pre>aws:RequestTag: environment:production<br />ecs:cluster:<br />  arn:aws:ecs:us-east-1:111122223333:cluster/default1</pre>  | Match | 
| <pre>"StringEquals": {<br />  "aws:RequestTag/environment": [<br />    "production",<br />    "prod-backup"<br />  ]<br />},<br />"ArnEquals": {<br />  "ecs:cluster": [<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default1",<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default2"<br />  ]<br />}</pre>  | <pre>aws:RequestTag: environment:prod-backup<br />ecs:cluster:<br />  arn:aws:ecs:us-east-1:111122223333:cluster/default2</pre>  | Match | 
| <pre>"StringEquals": {<br />  "aws:RequestTag/environment": [<br />    "production",<br />    "prod-backup"<br />  ]<br />},<br />"ArnEquals": {<br />  "ecs:cluster": [<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default1",<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default2"<br />  ]<br />}</pre>  | <pre>aws:RequestTag: webserver:production<br />ecs:cluster:<br />  arn:aws:ecs:us-east-1:111122223333:cluster/default2</pre>  | No match | 
| <pre>"StringEquals": {<br />  "aws:RequestTag/environment": [<br />    "production",<br />    "prod-backup"<br />  ]<br />},<br />"ArnEquals": {<br />  "ecs:cluster": [<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default1",<br />    "arn:aws:ecs:us-east-1:111122223333:cluster/default2"<br />  ]<br />}</pre>  |  No `aws:RequestTag` in the request context. <pre>ecs:cluster<br />  arn:aws:ecs:us-east-1:111122223333:cluster/default2</pre>  | No match | 

# IAM policy elements: Variables and tags
Variables and tags

Use AWS Identity and Access Management (IAM) policy variables as placeholders when you don't know the exact value of a resource or condition key when you write the policy.

**Note**  
If AWS cannot resolve a variable this might cause the entire statement to be invalid. For example, if you use the `aws:TokenIssueTime` variable, the variable resolves to a value only when the requester authenticated using temporary credentials (an IAM role). To prevent variables from causing invalid statements, use the [...IfExists condition operator.](reference_policies_elements_condition_operators.md#Conditions_IfExists)

**Topics**
+ [

## Introduction
](#policy-vars-intro)
+ [

## Using variables in policies
](#policy-vars-using-variables)
+ [

## Tags as policy variables
](#policy-vars-tags)
+ [

## Where you can use policy variables
](#policy-vars-wheretouse)
+ [

## Policy variables with no value
](#policy-vars-no-value)
+ [

## Request information that you can use for policy variables
](#policy-vars-infotouse)
+ [

## Specifying default values
](#policy-vars-default-values)
+ [

## For more information
](#policy-vars-formoreinfo)

## Introduction


In IAM policies, many actions allow you to provide a name for the specific resources that you want to control access to. For example, the following policy allows users to list, read, and write objects in the S3 bucket `amzn-s3-demo-bucket` for `marketing` projects.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],      
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket"],
      "Condition": {"StringLike": {"s3:prefix": ["marketing/*"]}}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],      
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket/marketing/*"]
    }
  ]
}
```

------

In some cases, you might not know the exact name of the resource when you write the policy. You might want to generalize the policy so it works for many users without having to make a unique copy of the policy for each user. Instead of creating a separate policy for each user, we recommend you create a single group policy that works for any user in that group. 

## Using variables in policies


You can define dynamic values inside policies by using *policy variables* that set placeholders in a policy.

Variables are marked using a **`$`** prefix followed by a pair of curly braces (**`{ }`**) that include the variable name of the value from the request.

When the policy is evaluated, the policy variables are replaced with values that come from the conditional context keys passed in the request. Variables can be used in [identity-based policies, resource policies, service control policies, session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html), and [VPC endpoint policies](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-access.html). Identity-based policies used as permissions boundaries also support policy variables. 

Global condition context keys can be used as variables in requests across AWS services. Service specific condition keys can also be used as variables when interacting with AWS resources, but are only available when requests are made against resources which support them. For a list of context keys available for each AWS service and resource, see the [https://docs.aws.amazon.com/service-authorization/latest/reference/reference.html](https://docs.aws.amazon.com/service-authorization/latest/reference/reference.html). Under certain circumstances, you can’t populate global condition context keys with a value. To learn more about each key, see [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html).

**Important**  
Key names are case-insensitive. For example, `aws:CurrentTime` is equivalent to `AWS:currenttime`.
You can use any single-valued condition key as a variable. You can't use a multivalued condition key as a variable.

The following example shows a policy for an IAM role or user that replaces a specific resource name with a policy variable. You can reuse this policy by taking advantage of the `aws:PrincipalTag` condition key. When this policy is evaluated, `${aws:PrincipalTag/team}` allows the actions only if the bucket name ends with a team name from the `team` principal tag.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],      
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket"],
      "Condition": {"StringLike": {"s3:prefix": ["${aws:PrincipalTag/team}/*"]}}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],      
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket/${aws:PrincipalTag/team}/*"]
    }
  ]
}
```

------

The variable is marked using a `$` prefix followed by a pair of curly braces (`{ }`). Inside the `${ }` characters, you can include the name of the value from the request that you want to use in the policy. The values you can use are discussed later on this page.

For details about this global condition key, see [aws:PrincipalTag/*tag-key*](reference_policies_condition-keys.md#condition-keys-principaltag) in the list of global condition keys.

**Note**  
In order to use policy variables, you must include the `Version` element in a statement, and the version must be set to a version that supports policy variables. Variables were introduced in version `2012-10-17`. Earlier versions of the policy language don't support policy variables. If you don't include the `Version` element and set it to an appropriate version date, variables like `${aws:username}` are treated as literal strings in the policy.   
A `Version` policy element is different from a policy version. The `Version` policy element is used within a policy and defines the version of the policy language. A policy version, on the other hand, is created when you change a customer managed policy in IAM. The changed policy doesn't overwrite the existing policy. Instead, IAM creates a new version of the managed policy. To learn more about the `Version` policy element see [IAM JSON policy elements: Version](reference_policies_elements_version.md). To learn more about policy versions, see [Versioning IAM policies](access_policies_managed-versioning.md).

A policy that allows a principal to get objects from the /David path of an S3 bucket looks like this:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/David/*"
      ]
    }
  ]
}
```

------

If this policy is attached to user `David`, that user get objects from his own S3 bucket, but you would have to create a separate policy for each user that includes the user's name. You would then attach each policy to the individual users.

By using a policy variable, you can create policies that can be reused. The following policy allows a user to get objects from an Amazon S3 bucket if the tag-key value for `aws:PrincipalTag` matches the tag-key `owner` value passed in the request. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [{
    "Sid": "AllowUnlessOwnedBySomeoneElse",
    "Effect": "Allow",
    "Action": ["s3:GetObject"],    
    "Resource": ["*"],
    "Condition": {
        "StringEquals": {
          "s3:ExistingObjectTag/owner": "${aws:PrincipalTag/owner}"
        }
      }
    }
  ]
}
```

------

When you use a policy variable in place of a user like this, you don't have to have a separate policy for each individual user. In the following example, the policy is attached to an IAM role that is assumed by Product Managers using temporary security credentials. When a user makes a request to add an Amazon S3 object, IAM substitutes the `dept` tag value from the current request for the `${aws:PrincipalTag}` variable and evaluates the policy. 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowOnlyDeptS3Prefix",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket/${aws:PrincipalTag/dept}/*"
            ]
        }
    ]
}
```

------

## Tags as policy variables


In some AWS services you can attach your own custom attributes to resources that are created by those services. For example, you can apply tags to Amazon S3 buckets or to IAM users. These tags are key-value pairs. You define the tag key name and the value that is associated with that key name. For example, you might create a tag with a **department** key and a **Human Resources** value. For more information about tagging IAM entities, see [Tags for AWS Identity and Access Management resources](id_tags.md). For information about tagging resources created by other AWS services, see the documentation for that service. For information about using Tag Editor, see [Working with Tag Editor](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/tag-editor.html) in the *AWS Management Console User Guide*.

You can tag IAM resources to simplify discovering, organizing, and tracking your IAM resources. You can also tag IAM identities to control access to resources or to tagging itself. To learn more about using tags to control access, see [Controlling access to and for IAM users and roles using tags](access_iam-tags.md). 

## Where you can use policy variables


 You can use policy variables in the `Resource` element and in string comparisons in the `Condition` element.

### Resource element


You can use a policy variable in the `Resource` element, but only in the resource portion of the ARN. This portion of the ARN appears after the fifth colon (:). You can't use a variable to replace parts of the ARN before the fifth colon, such as the service or account. For more information about the ARN format, see [IAM ARNs](reference_identifiers.md#identifiers-arns).

To replace part of an ARN with a tag value, surround the prefix and key name with `${ }`. For example, the following Resource element refers to only a bucket that is named the same as the value in the requesting user's department tag.

`"Resource": ["arn:aws::s3:::amzn-s3-demo-bucket/${aws:PrincipalTag/department}"]`

Many AWS resources use ARNs that contain a user-created name. The following IAM policy ensures that only intended users with matching access-project, access-application, and access-environment tag values can modify their resources. In addition, using [\$1 wildcard matches](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html), they are able to allow for custom resource name suffixes. 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowAccessBasedOnArnMatching",
      "Effect": "Allow",
      "Action": [
        "sns:CreateTopic",
        "sns:DeleteTopic"],      
      "Resource": ["arn:aws:sns:*:*:${aws:PrincipalTag/access-project}-${aws:PrincipalTag/access-application}-${aws:PrincipalTag/access-environment}-*"
      ]
    }
  ]
}
```

------

### Condition element


You can use a policy variable for `Condition` values in any condition that involves the string operators or the ARN operators. String operators include `StringEquals`, `StringLike`, and `StringNotLike`. ARN operators include `ArnEquals` and `ArnLike`. You can't use a policy variable with other operators, such as `Numeric`, `Date`, `Boolean`, `Binary`, `IP Address`, or `Null` operators. For more information about condition operators, see [IAM JSON policy elements: Condition operators](reference_policies_elements_condition_operators.md).

When referencing a tag in a `Condition` element expression, use the relevant prefix and key name as the condition key. Then use the value that you want to test in the condition value.

For example, the following policy example allows full access to users, but only if the tag `costCenter` is attached to the user. The tag must also have a value of either `12345` or `67890`. If the tag has no value, or has any other value, then the request fails.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
          "iam:*user*"
       ],
      "Resource": "*",
      "Condition": {
        "StringLike": {
          "iam:ResourceTag/costCenter": [ "12345", "67890" ]
        }
      }
    }
  ]
}
```

------

## Policy variables with no value


When policy variables reference a condition context key that has no value or is not present in an authorization context for a request, the value is effectively null. There is no equal or like value. Condition context keys may not be present in the authorization context when:
+ You are using service specific condition context keys in requests to resources that do not support that condition key.
+ Tags on IAM principals, sessions, resources, or requests are not present.
+ Other circumstances as listed for each global condition context key in [AWS global condition context keys](reference_policies_condition-keys.md).

When you use a variable with no value in the condition element of an IAM policy, [IAM JSON policy elements: Condition operators](reference_policies_elements_condition_operators.md) like `StringEquals` or `StringLike` do not match, and the policy statement does not take effect.

Inverted condition operators like `StringNotEquals` or `StringNotLike` do match against a null value, as the value of the condition key they are testing against is not equal to or like the effectively null value.

In the following example, `aws:principaltag/Team` must be equal to `s3:ExistingObjectTag/Team` to allow access. Access is explicitly denied when `aws:principaltag/Team` is not set. If a variable that has no value in the authorization context is used as part of the `Resource` or `NotResource` element of a policy, the resource that includes a policy variable with no value will not match any resource.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
   {
    "Effect": "Deny", 
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
    "Condition": {
      "StringNotEquals": {
        "s3:ExistingObjectTag/Team": "${aws:PrincipalTag/Team}"
       }
      }
    }
  ]
}
```

------

## Request information that you can use for policy variables


 You can use the `Condition` element of a JSON policy to compare keys in the [request context](reference_policies_evaluation-logic_policy-eval-reqcontext.md) with key values that you specify in your policy. When you use a policy variable, AWS substitutes a value from the request context key in place of the variable in your policy.

### Principal key values


The values for `aws:username`, `aws:userid`, and `aws:PrincipalType` depend on what type of principal initiated the request. For example, the request could be made using the credentials of an IAM user, an IAM role, or the AWS account root user. The following table shows values for these keys for different types of principals. 


****  

| Principal | `aws:username` | `aws:userid` | `aws:PrincipalType` | 
| --- | --- | --- | --- | 
| AWS account root user | (not present) | AWS account ID | Account | 
| IAM user | IAM-user-name | [unique ID](reference_identifiers.md#identifiers-unique-ids) | User | 
| AWS STS federated user principal | (not present) | account:caller-specified-name | FederatedUser | 
| OIDC federated principal For information about policy keys that are available when you use web identity federation, see [Available keys for AWS OIDC federation](reference_policies_iam-condition-keys.md#condition-keys-wif).  | (not present) |   *role-id*:*caller-specified-role-name*  where `role-id` is the [unique id of the role](reference_identifiers.md#identifiers-unique-ids) and the caller-specified-role-name is specified by the [RoleSessionName parameter](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AssumeRole.html#API_AssumeRoleWithWebIdentity_RequestParameters) passed to the AssumeRoleWithWebIdentity request.  | AssumedRole | 
| SAML federated principal For information about policy keys that are available when you use SAML federation, see [Uniquely identifying users in SAML-based federation](id_roles_providers_saml.md#CreatingSAML-userid).  | (not present) |  *role-id*:*caller-specified-role-name* where `role-id` is the [unique id of the role](reference_identifiers.md#identifiers-unique-ids) and the caller-specified-role-name is specified by the Attribute element with the [Name attribute](id_roles_providers_create_saml_assertions.md) set to https://aws.amazon.com/SAML/attributes/RoleSessionName.  | AssumedRole | 
| Assumed role | (not present) |  *role-id*:*caller-specified-role-name* where `role-id` is the [unique id of the role](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) and the caller-specified-role-name is specified by the [RoleSessionName parameter](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters) passed to the AssumeRole request.  | AssumedRole | 
| Role assigned to an Amazon EC2 instance | (not present) |  *role-id*:*ec2-instance-id* where `role-id` is [the unique id of the role](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) and the ec2-instance-id is the [unique identifier of the EC2 instance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html).  | AssumedRole | 
| Anonymous caller (Amazon SQS, Amazon SNS, and Amazon S3 only) | (not present) | anonymous | Anonymous | 

For the items in this table, note the following:
+ *not present* means that the value is not in the current request information, and any attempt to match it fails and causes the statement to be invalid. 
+ *role-id* is a unique identifier assigned to each role at creation. You can display the role ID with the AWS CLI command: `aws iam get-role --role-name rolename`
+ *caller-specified-name* and *caller-specified-role-name* are names that are passed by the calling process (such as an application or service) when it makes a call to get temporary credentials.
+ *ec2-instance-id* is a value assigned to the instance when it is launched and appears on the **Instances** page of the Amazon EC2 console. You can also display the instance ID by running the AWS CLI command: `aws ec2 describe-instances`

### Information available in requests for federated principals


Federated principals are users who are authenticated using a system other than IAM. For example, a company might have an application for use in-house that makes calls to AWS. It might be impractical to give an IAM identity to every corporate user who uses the application. Instead, the company might use a proxy (middle-tier) application that has a single IAM identity, or the company might use a SAML identity provider (IdP). The proxy application or SAML IdP authenticates individual users using the corporate network. A proxy application can then use its IAM identity to get temporary security credentials for individual users. A SAML IdP can in effect exchange identity information for AWS temporary security credentials. The temporary credentials can then be used to access AWS resources. 

Similarly, you might create an app for a mobile device in which the app needs to access AWS resources. In that case, you might use *OIDC federation*, where the app authenticates the user using a well-known identity provider like Login with Amazon, Amazon Cognito, Facebook, or Google. The app can then use the user's authentication information from these providers to get temporary security credentials for accessing AWS resources. 

The recommended way to use OIDC federation is by taking advantage of Amazon Cognito and the AWS mobile SDKs. For more information, see the following:
+ [Amazon Cognito User Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) 
+ [Common scenarios for temporary credentials](id_credentials_temp.md#sts-introduction)

### Special characters


There are a few special predefined policy variables that have fixed values that enable you to represent characters that otherwise have special meaning. If these special characters are part of the string, you are trying to match and you inserted them literally they would be misinterpreted. For example, inserting an \$1 asterisk in the string would be interpreted as a wildcard, matching any characters, instead of as a literal \$1. In these cases, you can use the following predefined policy variables:
+ **\$1\$1\$1\$1** - use where you need an \$1 (asterisk) character.
+ **\$1\$1?\$1** - use where you need a ? (question mark) character.
+ **\$1\$1\$1\$1** - use where you need a \$1 (dollar sign) character.

These predefined policy variables can be used in any string where you can use regular policy variables.

## Specifying default values


To add a default value to a variable, surround the default value with single quotes (`' '`), and separate the variable text and the default value with a comma and space (`, `).

For example, if a principal is tagged with `team=yellow`, they can access `ExampleCorp's` Amazon S3 bucket named `amzn-s3-demo-bucket-yellow`. A policy with this resource allows team members to access their team bucket, but not those of other teams. For users without team tags, it sets a default value of `company-wide` for the bucket name. These users can access only the `amzn-s3-demo-bucket-company-wide` bucket where they can view broad information, such as instructions for joining a team.

```
"Resource":"arn:aws:s3:::amzn-s3-demo-bucket-${aws:PrincipalTag/team, 'company-wide'}"
```

## For more information


For more information about policies, see the following: 
+  [Policies and permissions in AWS Identity and Access Management](access_policies.md) 
+  [Example IAM identity-based policies](access_policies_examples.md) 
+  [IAM JSON policy element reference](reference_policies_elements.md) 
+  [Policy evaluation logic](reference_policies_evaluation-logic.md) 
+  [OIDC federation](id_roles_providers_oidc.md)

# IAM JSON policy elements: Supported data types
Supported data types

This section lists the data types that are supported when you specify values in JSON policies. The policy language doesn't support all types for each policy element; for information about each element, see the preceding sections.
+ Strings
+ Numbers (Ints and Floats)
+ Boolean
+ Null
+ Lists
+ Maps
+ Structs (which are just nested Maps)

The following table maps each data type to the serialization. Note that all policies must be in UTF-8. For information about the JSON data types, go to [RFC 4627](https://datatracker.ietf.org/doc/html/rfc4627).


****  

| Type | JSON | 
| --- | --- | 
|  String  |  String  | 
|  Integer  |  Number  | 
|  Float  |  Number  | 
|  Boolean  |  true false  | 
|  Null  |  null  | 
|  Date  |  String adhering to the [W3C Profile of ISO 8601](http://www.w3.org/TR/NOTE-datetime)  | 
|  IpAddress  |  String adhering to [RFC 4632](https://datatracker.ietf.org/doc/html/rfc4632)  | 
|  List  |  Array  | 
|  Object  |  Object  | 