Skip to content

Data Source: awsIamPolicyDocument

Generates an IAM policy document in JSON format for use with resources that expect policy documents such as awsIamPolicy.

Using this data source to generate policy documents is optional. It is also valid to use literal JSON strings in your configuration or to use the file interpolation function to read a raw JSON policy document from a file.

\~> NOTE: AWS's IAM policy document syntax allows for replacement of policy variables within a statement using ${...}-style notation, which conflicts with Terraform's interpolation syntax. In order to use AWS policy variables with this data source, use &{...} notation for interpolations that should be processed by AWS rather than by Terraform.

-> For more information about building AWS IAM policy documents with Terraform, see the AWS IAM Policy Document Guide.

Example Usage

Basic Example

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentExample =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "example", {
    statement: [
      {
        actions: ["s3:ListAllMyBuckets", "s3:GetBucketLocation"],
        resources: ["arn:aws:s3:::*"],
        sid: "1",
      },
      {
        actions: ["s3:ListBucket"],
        condition: [
          {
            test: "StringLike",
            values: ["", "home/", "home/&{aws:username}/"],
            variable: "s3:prefix",
          },
        ],
        resources: ["arn:aws:s3:::${var.s3_bucket_name}"],
      },
      {
        actions: ["s3:*"],
        resources: [
          "arn:aws:s3:::${var.s3_bucket_name}/home/&{aws:username}",
          "arn:aws:s3:::${var.s3_bucket_name}/home/&{aws:username}/*",
        ],
      },
    ],
  });
const awsIamPolicyExample = new aws.iamPolicy.IamPolicy(this, "example_1", {
  name: "example_policy",
  path: "/",
  policy: dataAwsIamPolicyDocumentExample.json,
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsIamPolicyExample.overrideLogicalId("example");

Example Multiple Condition Keys and Values

You can specify a condition with multiple keys and values by supplying multiple condition blocks with the same test value, but differing variable and values values.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
  this,
  "example_multiple_condition_keys_and_values",
  {
    statement: [
      {
        actions: ["kms:Decrypt", "kms:GenerateDataKey"],
        condition: [
          {
            test: "ForAnyValue:StringEquals",
            values: ["pi"],
            variable: "kms:EncryptionContext:service",
          },
          {
            test: "ForAnyValue:StringEquals",
            values: ["rds"],
            variable: "kms:EncryptionContext:aws:pi:service",
          },
          {
            test: "ForAnyValue:StringEquals",
            values: [
              "db-AAAAABBBBBCCCCCDDDDDEEEEE",
              "db-EEEEEDDDDDCCCCCBBBBBAAAAA",
            ],
            variable: "kms:EncryptionContext:aws:rds:db-id",
          },
        ],
        resources: ["*"],
      },
    ],
  }
);

dataAwsIamPolicyDocumentExampleMultipleConditionKeysAndValuesJson will evaluate to:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": [
        "kms:GenerateDataKey",
        "kms:Decrypt"
      ],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:StringEquals": {
          "kms:EncryptionContext:aws:pi:service": "rds",
          "kms:EncryptionContext:aws:rds:db-id": [
            "db-AAAAABBBBBCCCCCDDDDDEEEEE",
            "db-EEEEEDDDDDCCCCCBBBBBAAAAA"
          ],
          "kms:EncryptionContext:service": "pi"
        }
      }
    }
  ]
}

Example Assume-Role Policy with Multiple Principals

You can specify multiple principal blocks with different types. You can also use this data source to generate an assume-role policy.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
  this,
  "event_stream_bucket_role_assume_role_policy",
  {
    statement: [
      {
        actions: ["sts:AssumeRole"],
        principals: [
          {
            identifiers: ["firehose.amazonaws.com"],
            type: "Service",
          },
          {
            identifiers: ["${var.trusted_role_arn}"],
            type: "AWS",
          },
          {
            identifiers: [
              "arn:aws:iam::${var.account_id}:saml-provider/${var.provider_name}",
              "cognito-identity.amazonaws.com",
            ],
            type: "Federated",
          },
        ],
      },
    ],
  }
);

Example Using A Source Document

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentSource =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "source", {
    statement: [
      {
        actions: ["ec2:*"],
        resources: ["*"],
      },
      {
        actions: ["s3:*"],
        resources: ["*"],
        sid: "SidToOverride",
      },
    ],
  });
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
  this,
  "source_document_example",
  {
    sourcePolicyDocuments: [dataAwsIamPolicyDocumentSource.json],
    statement: [
      {
        actions: ["s3:*"],
        resources: ["arn:aws:s3:::somebucket", "arn:aws:s3:::somebucket/*"],
        sid: "SidToOverride",
      },
    ],
  }
);

dataAwsIamPolicyDocumentSourceDocumentExampleJson will evaluate to:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": "ec2:*",
      "Resource": "*"
    },
    {
      "Sid": "SidToOverride",
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::somebucket/*",
        "arn:aws:s3:::somebucket"
      ]
    }
  ]
}

Example Using An Override Document

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentOverride =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "override", {
    statement: [
      {
        actions: ["s3:*"],
        resources: ["*"],
        sid: "SidToOverride",
      },
    ],
  });
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
  this,
  "override_policy_document_example",
  {
    overridePolicyDocuments: [dataAwsIamPolicyDocumentOverride.json],
    statement: [
      {
        actions: ["ec2:*"],
        resources: ["*"],
      },
      {
        actions: ["s3:*"],
        resources: ["arn:aws:s3:::somebucket", "arn:aws:s3:::somebucket/*"],
        sid: "SidToOverride",
      },
    ],
  }
);

dataAwsIamPolicyDocumentOverridePolicyDocumentExampleJson will evaluate to:

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

Example with Both Source and Override Documents

You can also combine sourcePolicyDocuments and overridePolicyDocuments in the same document.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentOverride =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "override", {
    statement: [
      {
        actions: ["s3:GetObject"],
        resources: ["*"],
        sid: "OverridePlaceholder",
      },
    ],
  });
const dataAwsIamPolicyDocumentSource =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "source", {
    statement: [
      {
        actions: ["ec2:DescribeAccountAttributes"],
        resources: ["*"],
        sid: "OverridePlaceholder",
      },
    ],
  });
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "politik", {
  overridePolicyDocuments: [dataAwsIamPolicyDocumentOverride.json],
  sourcePolicyDocuments: [dataAwsIamPolicyDocumentSource.json],
});

dataAwsIamPolicyDocumentPolitikJson will evaluate to:

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

Example of Merging Source Documents

Multiple documents can be combined using the sourcePolicyDocuments or overridePolicyDocuments attributes. sourcePolicyDocuments requires that all documents have unique Sids, while overridePolicyDocuments will iteratively override matching Sids.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentSourceOne =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "source_one",
    {
      statement: [
        {
          actions: ["ec2:*"],
          resources: ["*"],
        },
        {
          actions: ["s3:*"],
          resources: ["*"],
          sid: "UniqueSidOne",
        },
      ],
    }
  );
const dataAwsIamPolicyDocumentSourceTwo =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "source_two",
    {
      statement: [
        {
          actions: ["iam:*"],
          resources: ["*"],
          sid: "UniqueSidTwo",
        },
        {
          actions: ["lambda:*"],
          resources: ["*"],
        },
      ],
    }
  );
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "combined", {
  sourcePolicyDocuments: [
    dataAwsIamPolicyDocumentSourceOne.json,
    dataAwsIamPolicyDocumentSourceTwo.json,
  ],
});

dataAwsIamPolicyDocumentCombinedJson will evaluate to:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": "ec2:*",
      "Resource": "*"
    },
    {
      "Sid": "UniqueSidOne",
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    },
    {
      "Sid": "UniqueSidTwo",
      "Effect": "Allow",
      "Action": "iam:*",
      "Resource": "*"
    },
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": "lambda:*",
      "Resource": "*"
    }
  ]
}

Example of Merging Override Documents

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentPolicyOne =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "policy_one",
    {
      statement: [
        {
          actions: ["s3:*"],
          effect: "Allow",
          resources: ["*"],
          sid: "OverridePlaceHolderOne",
        },
      ],
    }
  );
const dataAwsIamPolicyDocumentPolicyThree =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "policy_three",
    {
      statement: [
        {
          actions: ["logs:*"],
          effect: "Deny",
          resources: ["*"],
          sid: "OverridePlaceHolderOne",
        },
      ],
    }
  );
const dataAwsIamPolicyDocumentPolicyTwo =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "policy_two",
    {
      statement: [
        {
          actions: ["ec2:*"],
          effect: "Allow",
          resources: ["*"],
        },
        {
          actions: ["iam:*"],
          effect: "Allow",
          resources: ["*"],
          sid: "OverridePlaceHolderTwo",
        },
      ],
    }
  );
new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "combined", {
  overridePolicyDocuments: [
    dataAwsIamPolicyDocumentPolicyOne.json,
    dataAwsIamPolicyDocumentPolicyTwo.json,
    dataAwsIamPolicyDocumentPolicyThree.json,
  ],
  statement: [
    {
      actions: ["*"],
      effect: "Deny",
      resources: ["*"],
      sid: "OverridePlaceHolderTwo",
    },
  ],
});

dataAwsIamPolicyDocumentCombinedJson will evaluate to:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OverridePlaceholderTwo",
      "Effect": "Allow",
      "Action": "iam:*",
      "Resource": "*"
    },
    {
      "Sid": "OverridePlaceholderOne",
      "Effect": "Deny",
      "Action": "logs:*",
      "Resource": "*"
    },
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": "ec2:*",
      "Resource": "*"
    },
  ]
}

Argument Reference

The following arguments are optional:

  • overrideJson (Optional, Deprecated use the overridePolicyDocuments attribute instead) - IAM policy document whose statements with non-blank sids will override statements with the same sid from documents assigned to the sourceJson, sourcePolicyDocuments, and overridePolicyDocuments arguments. Non-overriding statements will be added to the exported document.

\~> NOTE: Statements without a sid cannot be overridden. In other words, a statement without a sid from documents assigned to the sourceJson or sourcePolicyDocuments arguments cannot be overridden by statements from documents assigned to the overrideJson or overridePolicyDocuments arguments.

  • overridePolicyDocuments (Optional) - List of IAM policy documents that are merged together into the exported document. In merging, statements with non-blank sids will override statements with the same sid from earlier documents in the list. Statements with non-blank sids will also override statements with the same sid from documents provided in the sourceJson and sourcePolicyDocuments arguments. Non-overriding statements will be added to the exported document.
  • policyId (Optional) - ID for the policy document.
  • sourceJson (Optional, Deprecated use the sourcePolicyDocuments attribute instead) - IAM policy document used as a base for the exported policy document. Statements with the same sid from documents assigned to the overrideJson and overridePolicyDocuments arguments will override source statements.
  • sourcePolicyDocuments (Optional) - List of IAM policy documents that are merged together into the exported document. Statements defined in sourcePolicyDocuments or sourceJson must have unique sids. Statements with the same sid from documents assigned to the overrideJson and overridePolicyDocuments arguments will override source statements.
  • statement (Optional) - Configuration block for a policy statement. Detailed below.
  • version (Optional) - IAM policy document version. Valid values are 20081017 and 20121017. Defaults to 20121017. For more information, see the AWS IAM User Guide.

statement

The following arguments are optional:

  • actions (Optional) - List of actions that this statement either allows or denies. For example, ["ec2:runInstances", "s3:*"].
  • condition (Optional) - Configuration block for a condition. Detailed below.
  • effect (Optional) - Whether this statement allows or denies the given actions. Valid values are allow and deny. Defaults to allow.
  • notActions (Optional) - List of actions that this statement does not apply to. Use to apply a policy statement to all actions except those listed.
  • notPrincipals (Optional) - Like principals except these are principals that the statement does not apply to.
  • notResources (Optional) - List of resource ARNs that this statement does not apply to. Use to apply a policy statement to all resources except those listed. Conflicts with resources.
  • principals (Optional) - Configuration block for principals. Detailed below.
  • resources (Optional) - List of resource ARNs that this statement applies to. This is required by AWS if used for an IAM policy. Conflicts with notResources.
  • sid (Optional) - Sid (statement ID) is an identifier for a policy statement.

condition

A condition constrains whether a statement applies in a particular situation. Conditions can be specific to an AWS service. When using multiple condition blocks, they must all evaluate to true for the policy statement to apply. In other words, AWS evaluates the conditions as though with an "AND" boolean operation.

The following arguments are required:

  • test (Required) Name of the IAM condition operator to evaluate.
  • values (Required) Values to evaluate the condition against. If multiple values are provided, the condition matches if at least one of them applies. That is, AWS evaluates multiple values as though using an "OR" boolean operation.
  • variable (Required) Name of a Context Variable to apply the condition to. Context variables may either be standard AWS variables starting with aws: or service-specific variables prefixed with the service name.

principals and notPrincipals

The principals and notPrincipals arguments define to whom a statement applies or does not apply, respectively.

\~> NOTE: Even though the IAM Documentation states that "principal": "*" and "principal": {"aws": "*"} are equivalent, those principal elements have different behavior in some situations, e.g., IAM Role Trust Policy. To have Terraform render JSON containing "principal": "*", use type = "*" and identifiers = ["*"]. To have Terraform render JSON containing "principal": {"aws": "*"}, use type = "aws" and identifiers = ["*"].

-> For more information about AWS principals, refer to the AWS Identity and Access Management User Guide: AWS JSON policy elements: Principal.

The following arguments are required:

  • identifiers (Required) List of identifiers for principals. When type is aws, these are IAM principal ARNs, e.g., arn:aws:iam::12345678901:role/yakRole. When type is service, these are AWS Service roles, e.g., lambdaAmazonawsCom. When type is federated, these are web identity users or SAML provider ARNs, e.g., accountsGoogleCom or arn:aws:iam::12345678901:samlProvider/yakSamlProvider. When type is canonicalUser, these are canonical user IDs, e.g., 79A59Df900B949E55D96A1E698Fbacedfd6E09D98Eacf8F8D5218E7Cd47Ef2Be.
  • type (Required) Type of principal. Valid values include aws, service, federated, canonicalUser and *.

Attributes Reference

The following attribute is exported:

  • json - Standard JSON policy document rendered based on the arguments above.