Debug School

rakesh kumar
rakesh kumar

Posted on

Explain IAM JSON policy in Aws

How to create IAM Policy in aws

IAM JSON policy elements

You can type or paste policies in JSON by choosing the JSON option. This method is useful for copying an example policy to use in your account. Or, you can type your own JSON policy document in the JSON editor. You can also use the JSON option to toggle between the visual editor and JSON to compare the views.

When you create or edit a policy in the JSON editor, IAM performs policy validation to help you create an effective policy. IAM identifies JSON syntax errors, while IAM Access Analyzer provides additional policy checks with actionable recommendations to help you further refine the policy.

A JSON policy document consists of one or more statements. Each statement should contain all the actions that share the same effect (Allow or Deny) and support the same resources and conditions. If one action requires you to specify all resources ("*") and another action supports the Amazon Resource Name (ARN) of a specific resource, they must be in two separate JSON statements. For details about ARN formats, see Amazon Resource Name (ARN) in the AWS General Reference Guide. For general information about IAM policies, see Policies and permissions in IAM. For information about the IAM

how-to-create-iam-policy-in-aws
This section presents detailed syntax, descriptions, and examples of the elements, variables, and evaluation logic of JSON policies in IAM. For more general information, see Overview of JSON policies.

This reference includes the following sections.

IAM JSON policy elements reference — Learn more about the elements that you can use when you create a policy. View additional policy examples and learn about conditions, supported data types, and how they are used in various services.

Policy evaluation logic — This section describes AWS requests, how they are authenticated, and how AWS uses policies to determine access to resources.

Grammar of the IAM JSON policy language — This section presents a formal grammar for the language that is used to create policies in IAM.

AWS managed policies for job functions — This section lists all the AWS managed policies that directly map to common job functions in the IT industry. Use these policies to grant the permissions that are needed to carry out the tasks expected of someone in a specific job function. These policies consolidate permissions for many services into a single policy.

AWS global condition context keys — This section includes a list of all the AWS global condition keys that you can use to limit permissions in an IAM policy.

IAM and AWS STS condition context keys — This section includes a list of all the IAM and AWS STS condition keys that you can use to limit permissions in an IAM policy.

Actions, Resources, and Condition Keys for AWS Services — This section presents a list of all the AWS API operations that you can use as permissions in an IAM policy. It also includes the service-specific condition keys that can be used to further refine the request.

IAM JSON policy elements

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.

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.

IAM JSON policy elements: Version
IAM JSON policy elements: Id
IAM JSON policy elements: Statement
IAM JSON policy elements: Sid
IAM JSON policy elements: Effect
AWS JSON policy elements: Principal
AWS JSON policy elements: NotPrincipal
IAM JSON policy elements: Action
IAM JSON policy elements: NotAction
IAM JSON policy elements: Resource
IAM JSON policy elements: NotResource
IAM JSON policy elements: Condition
Variables and tags
Supported data types

IAM JSON policy elements: 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.
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.

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

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 that were introduced with this versio

IAM JSON policy elements: 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.

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

IAM JSON policy elements: 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 { }. For multiple statements, the array must be enclosed in square brackets [ ].

"Statement": [{...},{...},{...}]
Enter fullscreen mode Exit fullscreen mode

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,

{
  "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:::BUCKET-NAME",
      "Condition": {"StringLike": {"s3:prefix": [
        "",
        "home/",
        "home/${aws:username}/"
      ]}}
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::BUCKET-NAME/home/${aws:username}",
        "arn:aws:s3:::BUCKET-NAME/home/${aws:username}/*"
      ]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

IAM JSON policy elements: Sid

You can provide 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.

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

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

IAM JSON policy elements: 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"
Enter fullscreen mode Exit fullscreen mode

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

AWS JSON policy elements: 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. 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.

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.

Specifying a principal
AWS account principals
IAM role principals
Role session principals
IAM user principals
IAM Identity Center principals
AWS STS federated user session principals
AWS service principals
AWS service principals in opt-in Regions
All principals
More information
Enter fullscreen mode Exit fullscreen mode

Specifying 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 sessions

AWS services

All principals
Enter fullscreen mode Exit fullscreen mode

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" 
  ]
}
Enter fullscreen mode Exit fullscreen mode

All principals

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" }
Enter fullscreen mode Exit fullscreen mode

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.

Some AWS services support additional options for specifying an account principal. For example, Amazon S3 lets you specify a canonical user ID using the following format:

"Principal": { "CanonicalUser": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be" }
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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.

IAM roles are identities that exist in IAM. Roles trust another authenticated identity, such as a principal in AWS or a user from an external identity provider. When a principal or identity assumes a role, they receive temporary security credentials. They can then use those credentials as a role session principal to perform operations in AWS.

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.

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


"Principal": { "AWS": "arn:aws:iam::AWS-account-ID:role/role-name" }
Enter fullscreen mode Exit fullscreen mode

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 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.

Alternatively, you can specify the role principal as the principal in a resource-based policy or create a broad-permission policy 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(*) 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.

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.

Assumed-role session principals
An assumed-role session principal is a session principal that results from using the AWS STS AssumeRole operation. For more information about which principals can assume a role using this operation, see Comparing the AWS STS API operations.

To specify the assumed-role session ARN in the Principal element, use the following format:

"Principal": { "AWS": "arn:aws:sts::AWS-account-ID:assumed-role/role-name/role-session-name" }
Enter fullscreen mode Exit fullscreen mode

When you specify an assumed-role session in a Principal element, you cannot use a wildcard "*" to mean all sessions. Principals must always name a specific session.

Web identity session principals
A web identity session principal is a session principal that results from using the AWS STS AssumeRoleWithWebIdentity operation. You can use an external web identity provider (IdP) to sign in, and then assume an IAM role using this operation. This leverages identity federation and issues a role session. For more information about which principals can assume a role using this operation, see Comparing the AWS STS API operations.

When you issue a role from a web identity provider, you get this special type of session principal that includes information about the web identity provider.

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

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

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

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

"Principal": { "Federated": "accounts.google.com" }
Enter fullscreen mode Exit fullscreen mode

SAML session principals
A SAML session principal is a session principal that results from using the AWS STS AssumeRoleWithSAML operation. You can use an external SAML identity provider (IdP) to sign in, and then assume an IAM role using this operation. This leverages identity federation and issues a role session. For more information about which principals can assume a role using this operation, see Comparing the AWS STS API operations.

When you issue a role from a SAML identity provider, you get this special type of session principal that includes information about the SAML identity provider.

Use this principal type in your policy to allow or deny access 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" }
Enter fullscreen mode Exit fullscreen mode

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) 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"
  ]
}
Enter fullscreen mode Exit fullscreen mode

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

IAM 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 in the IAM Identity Center User Guide.

AWS STS federated user session principals

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

An AWS STS federated user session principal is a session principal that results from using the AWS STS GetFederationToken operation. In this case, AWS STS uses identity federation as the method to obtain temporary access tokens instead of using IAM roles.

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 Comparing the AWS STS API operations.

IAM federated user – An IAM user federates using the GetFederationToken operation that results in a federated user session principal for that IAM user.

Federated root user – A root user federates using the GetFederationToken operation that results in a federated user session principal 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" }
Enter fullscreen mode Exit fullscreen mode

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. 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 identifier for a service principal includes the service name, and is usually in the following format:

service-name.amazonaws.com
Enter fullscreen mode Exit fullscreen mode

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, 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"
   ]
}
Enter fullscreen mode Exit fullscreen mode

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 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode

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 (*) to specify all principals in the Principal element of a resource-based policy or in condition keys that support principals. Resource-based policies grant permissions and condition keys are used to limit the conditions of a policy statement.

For resource-based policies, using a wildcard (*) 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.

For anonymous users, the following elements are equivalent:

"Principal": "*"

"Principal" : { "AWS" : "*" }
Enter fullscreen mode Exit fullscreen mode

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 Specifying NotPrincipal with Deny to explicitly deny all principals except for the ones specified in the Condition element.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "UsePrincipalArnInsteadOfNotPrincipalWithDeny",
      "Effect": "Deny",
      "Action": "s3:*",
      "Principal": "*",
      "Resource": [
        "arn:aws:s3:::BUCKETNAME/*",
        "arn:aws:s3:::BUCKETNAME"
      ],
      "Condition": {
        "ArnNotEquals": {
          "aws:PrincipalArn": "arn:aws:iam::444455556666:user/user-name"
        }
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

AWS JSON policy elements: NotPrincipal

You can use the NotPrincipal element to deny access to all principals except the IAM user, federated user, IAM role, AWS account, AWS service, or other principal specified in the NotPrincipal element.

You can use it 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.

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

Specifying NotPrincipal with Deny

When you use NotPrincipal with Deny, 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.

Important
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 with the aws:PrincipalArn context key to limit access instead of the NotPrincipal element. For information about permissions boundaries, see Permissions boundaries for IAM entities.

Note
As a best practice, you should include the ARNs for the account in your policy. Some services require the account ARN, although this is not required in all cases. Any existing policies without the required ARN will continue to work, but new policies that include these services must meet this requirement. IAM does not track these services, and therefore recommends that you always include the account ARN.

The following examples show how to use NotPrincipal and "Effect": "Deny" in the same policy statement effectively.

Example IAM user in the same or a different account
In the following example, all principals except the user named Bob in AWS account 444455556666 are explicitly denied access to a resource. Note that as a best practice, the NotPrincipal element contains the ARN of both the user Bob and the AWS account that Bob belongs to (arn:aws:iam::444455556666:root). If the NotPrincipal element contained only Bob's ARN, the effect of the policy might be to explicitly deny access to the AWS account that contains the user Bob. In some cases, a user cannot have more permissions than its parent account, so if Bob's account is explicitly denied access then Bob might be unable to access the resource.

This example works as intended when it is part of a policy statement in a resource-based policy that is attached to a resource in either the same or a different AWS account (not 444455556666). This example by itself does not grant access to Bob, it only omits Bob from the list of principals that are explicitly denied. To allow Bob access to the resource, another policy statement must explicitly allow access using "Effect": "Allow".

{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Deny",
        "NotPrincipal": {"AWS": [
            "arn:aws:iam::444455556666:user/Bob",
            "arn:aws:iam::444455556666:root"
        ]},
        "Action": "s3:*",
        "Resource": [
            "arn:aws:s3:::BUCKETNAME",
            "arn:aws:s3:::BUCKETNAME/*"
        ]
    }]
}
Enter fullscreen mode Exit fullscreen mode

Example IAM role in the same or different account
In the following example, all principals except the assumed-role user named cross-account-audit-app in AWS account 444455556666 are explicitly denied access to a resource. As a best practice, the NotPrincipal element contains the ARN of the assumed-role user (cross-account-audit-app), the role (cross-account-read-only-role), and the AWS account that the role belongs to (444455556666). If the NotPrincipal element was missing the ARN of the role, the effect of the policy might be to explicitly deny access to the role. Similarly, if the NotPrincipal element was missing the ARN of the AWS account that the role belongs to, the effect of the policy might be to explicitly deny access to the AWS account and all entities in that account. In some cases, assumed-role users cannot have more permissions than their parent role, and roles cannot have more permissions than their parent AWS account, so when the role or the account is explicitly denied access, the assumed role user might be unable to access the resource.

This example works as intended when it is part of a policy statement in a resource-based policy that is attached to a resource in a different AWS account (not 444455556666). This example by itself does not allow access to the assumed-role user cross-account-audit-app, it only omits cross-account-audit-app from the list of principals that are explicitly denied. To give cross-account-audit-app access to the resource, another policy statement must explicitly allow access using "Effect": "Allow".

{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Deny",
        "NotPrincipal": {"AWS": [
            "arn:aws:sts::444455556666:assumed-role/cross-account-read-only-role/cross-account-audit-app",
            "arn:aws:iam::444455556666:role/cross-account-read-only-role",
            "arn:aws:iam::444455556666:root"
        ]},
        "Action": "s3:*",
        "Resource": [
            "arn:aws:s3:::Bucket_AccountAudit",
            "arn:aws:s3:::Bucket_AccountAudit/*"
        ]
    }]
}
Enter fullscreen mode Exit fullscreen mode

IAM JSON policy elements: 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 in the Amazon Simple Storage Service User Guide, the list of actions for Amazon EC2 can be found in the Amazon EC2 API Reference, and the list of actions for AWS Identity and Access Management can be found in the IAM API Reference. To find the list of actions for other services, consult the API reference documentation for the service.

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"
Enter fullscreen mode Exit fullscreen mode

Amazon EC2 action

"Action": "ec2:StartInstances"
Enter fullscreen mode Exit fullscreen mode

IAM action

"Action": "iam:ChangePassword"
Enter fullscreen mode Exit fullscreen mode

Amazon S3 action

"Action": "s3:GetObject"
Enter fullscreen mode Exit fullscreen mode

You can specify multiple values for the Action element.

"Action": [ "sqs:SendMessage", "sqs:ReceiveMessage", "ec2:StartInstances", "iam:ChangePassword", "s3:GetObject" ]
Enter fullscreen mode Exit fullscreen mode

You can use a wildcard (*) 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:*"
Enter fullscreen mode Exit fullscreen mode

You can also use wildcards (*) 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*"
Enter fullscreen mode Exit fullscreen mode

IAM JSON policy elements: 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. When using NotAction, you should keep in mind that actions specified in this element are the only actions in that are limited. 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 does not allow users to use the ListAllMyBuckets S3 API operation, because that action requires the "*" resource. 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:::*",
Enter fullscreen mode Exit fullscreen mode

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": "*"
Enter fullscreen mode Exit fullscreen mode

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.

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

IAM JSON policy elements: Resource

The Resource element specifies the object or objects that the statement covers. Statements must include either a Resource or a NotResource element. You specify a resource using an ARN. For more information about the format of ARNs, see IAM ARNs.

Each service has its own set of resources. Although you always use an ARN to specify a resource, the details of the ARN for a resource depend on the service and the resource. For information about how to specify a resource, refer to the documentation for the service you want to write a statement.

Some services do not let you specify actions for individual resources; instead, any actions that you list in the Action or NotAction element apply to all resources in that service. In these cases, you use the wildcard * 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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Using wildcards in resource ARNs

You can use wildcards as part of the resource ARN. You can use wildcard characters (* and ?) within ARN segments (the parts separated by colons) to represent any combination of characters with an asterisk () and any single character with a question mark (?). 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 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 Amazon Resource Names (ARNs)

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

"Resource": "arn:aws:iam::account-ID-without-hyphens:user/accounting/*"
Enter fullscreen mode Exit fullscreen mode

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


"Resource": "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*"
Enter fullscreen mode Exit fullscreen mode

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:::DOC-EXAMPLE-BUCKET/*/test/*"
Enter fullscreen mode Exit fullscreen mode

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

DOC-EXAMPLE-BUCKET/1/test/object.jpg
DOC-EXAMPLE-BUCKET/1/2/test/object.jpg
DOC-EXAMPLE-BUCKET/1/2/test/3/object.jpg 
DOC-EXAMPLE-BUCKET/1/2/3/test/4/object.jpg
DOC-EXAMPLE-BUCKET/1///test///object.jpg
DOC-EXAMPLE-BUCKET/1/test/.jpg
DOC-EXAMPLE-BUCKET//test/object.jpg
DOC-EXAMPLE-BUCKET/1/test/
Enter fullscreen mode Exit fullscreen mode

Consider the last two objects in the previous list. An Amazon S3 object name can validly 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:


DOC-EXAMPLE-BUCKET/1-test/object.jpg
DOC-EXAMPLE-BUCKET/test/object.jpg
DOC-EXAMPLE-BUCKET/1/2/test.jpg
Enter fullscreen mode Exit fullscreen mode

Specifying multiple resources

You can specify multiple resources. 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"
]
Enter fullscreen mode Exit fullscreen mode

Using policy variables in resource ARNs

In the Resource element, you can use JSON policy variables 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.

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "dynamodb:*",
    "Resource": "arn:aws:dynamodb:us-east-2:account-id:table/${aws:username}"
  }
}
Enter fullscreen mode Exit fullscreen mode

IAM JSON policy elements: 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.

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

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 Resource. 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 also included Amazon EC2 actions, then the policy would not deny access to any EC2 resources. To learn which actions in a service allow specifying the ARN of a resource, see Actions, Resources, and Condition Keys for AWS Services.

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

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 (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 Request.

"Condition" : { "{condition-operator}" : { "{condition-key}" : "{condition-value}" }}
Enter fullscreen mode Exit fullscreen mode

The context key that you specify in a policy condition can be a global condition context key 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.

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 that you use. For example, the following condition includes the StringEquals operator to make sure that only requests made by johndoe match. Users named JohnDoe are denied access.

"Condition" : { "StringEquals" : { "aws:username" : "johndoe" }}
Enter fullscreen mode Exit fullscreen mode

The following condition uses the StringEqualsIgnoreCase operator to match users named johndoe or JohnDoe.

"Condition" : { "StringEqualsIgnoreCase" : { "aws:username" : "johndoe" }}
Enter fullscreen mode Exit fullscreen mode

Some context keys support key–value pairs that allow you to specify part of the key name. Examples include the aws:RequestTag/tag-key context key, the AWS KMS kms:EncryptionContext:encryption_context_key, and the ResourceTag/tag-key context key supported by multiple services.

If you use the ResourceTag/tag-key context key for a service such as Amazon EC2, 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 context key for tagging, or the kms:EncryptionContextKeys 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.

Unless otherwise specified, all context keys can have multiple values. For a description of how to handle context keys that have multiple values, see Multivalued context keys.

For a list of all of the globally available context keys, see AWS global condition context keys.

For condition context keys that are defined by each service, see Actions, Resources, and Condition Keys for AWS Services.

IAM policy elements: 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.

Introduction

Using variables in policies
Tags as policy variables
Where you can use policy variables
Policy variables with no value
Request information that you can use for policy variables
Specifying default values
Enter fullscreen mode Exit fullscreen mode

For more information
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 DOC-EXAMPLE-BUCKET for marketing projects.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],      
      "Resource": ["arn:aws:s3:::DOC-EXAMPLE-BUCKET"],
      "Condition": {"StringLike": {"s3:prefix": ["marketing/*"]}}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],      
      "Resource": ["arn:aws:s3:::DOC-EXAMPLE-BUCKET/marketing/*"]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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, and VPC endpoint policies. 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 Service Authorization Reference. 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.

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.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],      
      "Resource": ["arn:aws:s3:::DOC-EXAMPLE-BUCKET"],
      "Condition": {"StringLike": {"s3:prefix": ["${aws:PrincipalTag/team}/*"]}}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],      
      "Resource": ["arn:aws:s3:::DOC-EXAMPLE-BUCKET/${aws:PrincipalTag/team}/*"]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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 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. To learn more about policy versions, see Versioning IAM policies.

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

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["s3:GetObject"],    
    "Resource": ["arn:aws:s3::DOC-EXAMPLE-BUCKET/David/*"]
  }]
}
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowOnlyDeptS3Prefix",
    "Effect": "Allow",
    "Action": ["s3:GetObject"],    
    "Resource": ["arn:aws:s3:::DOC-EXAMPLE-BUCKET/${aws:PrincipalTag/dept}/*"],    
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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 Tagging IAM resources. 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 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.

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.

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:::bucket/${aws:PrincipalTag/department}"]
Enter fullscreen mode Exit fullscreen mode

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 * wildcard matches, they are able to allow for custom resource name suffixes.

{
  "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}-*"
      ]
    }
  ]
} 
Enter fullscreen mode Exit fullscreen mode

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.

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.


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

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:

1.You are using service specific condition context keys in requests to resources that do not support that condition key.

2.Tags on IAM principals, sessions, resources, or requests are not present.

3.Other circumstances as listed for each global condition context key in AWS global condition context keys.

When you use a variable with no value in the condition element of an IAM policy, IAM JSON policy elements: Condition operators 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.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::/example-bucket/*",
        "StringNotEquals": {
          "s3:ExistingObjectTag/Team": "${aws:PrincipalTag/Team}"
        }
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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 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.

Image description

Image description

Image description

json policy

Top comments (0)