diff --git a/.changelog/25569.txt b/.changelog/25569.txt new file mode 100644 index 000000000000..7df0ee2e471f --- /dev/null +++ b/.changelog/25569.txt @@ -0,0 +1,3 @@ +```release-note:new-data-source +aws_iam_principal_policy_simulation: Run simulated requests against a user's, group's, or role's IAM policies. +``` diff --git a/internal/provider/provider.go b/internal/provider/provider.go index cccc08412c9f..12fc9cc4562f 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -665,21 +665,22 @@ func Provider() *schema.Provider { "aws_guardduty_detector": guardduty.DataSourceDetector(), - "aws_iam_account_alias": iam.DataSourceAccountAlias(), - "aws_iam_group": iam.DataSourceGroup(), - "aws_iam_instance_profile": iam.DataSourceInstanceProfile(), - "aws_iam_instance_profiles": iam.DataSourceInstanceProfiles(), - "aws_iam_openid_connect_provider": iam.DataSourceOpenIDConnectProvider(), - "aws_iam_policy": iam.DataSourcePolicy(), - "aws_iam_policy_document": iam.DataSourcePolicyDocument(), - "aws_iam_role": iam.DataSourceRole(), - "aws_iam_roles": iam.DataSourceRoles(), - "aws_iam_saml_provider": iam.DataSourceSAMLProvider(), - "aws_iam_server_certificate": iam.DataSourceServerCertificate(), - "aws_iam_session_context": iam.DataSourceSessionContext(), - "aws_iam_user": iam.DataSourceUser(), - "aws_iam_user_ssh_key": iam.DataSourceUserSSHKey(), - "aws_iam_users": iam.DataSourceUsers(), + "aws_iam_account_alias": iam.DataSourceAccountAlias(), + "aws_iam_group": iam.DataSourceGroup(), + "aws_iam_instance_profile": iam.DataSourceInstanceProfile(), + "aws_iam_instance_profiles": iam.DataSourceInstanceProfiles(), + "aws_iam_openid_connect_provider": iam.DataSourceOpenIDConnectProvider(), + "aws_iam_policy": iam.DataSourcePolicy(), + "aws_iam_policy_document": iam.DataSourcePolicyDocument(), + "aws_iam_principal_policy_simulation": iam.DataSourcePrincipalPolicySimulation(), + "aws_iam_role": iam.DataSourceRole(), + "aws_iam_roles": iam.DataSourceRoles(), + "aws_iam_saml_provider": iam.DataSourceSAMLProvider(), + "aws_iam_server_certificate": iam.DataSourceServerCertificate(), + "aws_iam_session_context": iam.DataSourceSessionContext(), + "aws_iam_user": iam.DataSourceUser(), + "aws_iam_user_ssh_key": iam.DataSourceUserSSHKey(), + "aws_iam_users": iam.DataSourceUsers(), "aws_identitystore_group": identitystore.DataSourceGroup(), "aws_identitystore_user": identitystore.DataSourceUser(), diff --git a/internal/service/iam/principal_policy_simulation_data_source.go b/internal/service/iam/principal_policy_simulation_data_source.go new file mode 100644 index 000000000000..5b240ad6bdfa --- /dev/null +++ b/internal/service/iam/principal_policy_simulation_data_source.go @@ -0,0 +1,326 @@ +package iam + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/conns" +) + +func DataSourcePrincipalPolicySimulation() *schema.Resource { + return &schema.Resource{ + Read: dataSourcePrincipalPolicySimulationRead, + + Schema: map[string]*schema.Schema{ + // Arguments + "action_names": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `One or more names of actions, like "iam:CreateUser", that should be included in the simulation.`, + }, + "caller_arn": { + Type: schema.TypeString, + Optional: true, + Description: `ARN of a user to use as the caller of the simulated requests. If not specified, defaults to the principal specified in policy_source_arn, if it is a user ARN.`, + }, + "context": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Required: true, + Description: `The key name of the context entry, such as "aws:CurrentTime".`, + }, + "type": { + Type: schema.TypeString, + Required: true, + Description: `The type that the simulator should use to interpret the strings given in argument "values".`, + }, + "values": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `One or more values to assign to the context key, given as a string in a syntax appropriate for the selected value type.`, + }, + }, + }, + Description: `Each block specifies one item of additional context entry to include in the simulated requests. These are the additional properties used in the 'Condition' element of an IAM policy, and in dynamic value interpolations.`, + }, + "permissions_boundary_policies_json": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `Additional permission boundary policies to use in the simulation.`, + }, + "additional_policies_json": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `Additional principal-based policies to use in the simulation.`, + }, + "policy_source_arn": { + Type: schema.TypeString, + Required: true, + Description: `ARN of the principal (e.g. user, role) whose existing configured access policies will be used as the basis for the simulation. If you specify a role ARN here, you can also set caller_arn to simulate a particular user acting with the given role.`, + }, + "resource_arns": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `ARNs of specific resources to use as the targets of the specified actions during simulation. If not specified, the simulator assumes "*" which represents general access across all resources.`, + }, + "resource_handling_option": { + Type: schema.TypeString, + Optional: true, + Description: `Specifies the type of simulation to run. Some API operations need a particular resource handling option in order to produce a correct reesult.`, + }, + "resource_owner_account_id": { + Type: schema.TypeString, + Optional: true, + Description: `An AWS account ID to use as the simulated owner for any resource whose ARN does not include a specific owner account ID. Defaults to the account given as part of caller_arn.`, + }, + "resource_policy_json": { + Type: schema.TypeString, + Optional: true, + Description: `A resource policy to associate with all of the target resources for simulation purposes. The policy simulator does not automatically retrieve resource-level policies, so if a resource policy is crucial to your test then you must specify here the same policy document associated with your target resource(s).`, + }, + + // Result Attributes + "all_allowed": { + Type: schema.TypeBool, + Computed: true, + Description: `A summary of the results attribute which is true if all of the results have decision "allowed", and false otherwise.`, + }, + "results": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "action_name": { + Type: schema.TypeString, + Computed: true, + Description: `The name of the action whose simulation this result is describing.`, + }, + "decision": { + Type: schema.TypeString, + Computed: true, + Description: `The exact decision keyword returned by the policy simulator: "allowed", "explicitDeny", or "implicitDeny".`, + }, + "allowed": { + Type: schema.TypeBool, + Computed: true, + Description: `A summary of attribute "decision" which is true only if the decision is "allowed".`, + }, + "decision_details": { + Type: schema.TypeMap, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `A mapping of various additional details that are relevant to the decision, exactly as returned by the policy simulator.`, + }, + "resource_arn": { + Type: schema.TypeString, + Computed: true, + Description: `ARN of the resource that the action was tested against.`, + }, + "matched_statements": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "source_policy_id": { + Type: schema.TypeString, + Computed: true, + Description: `Identifier of one of the policies used as input to the simulation.`, + }, + "source_policy_type": { + Type: schema.TypeString, + Computed: true, + Description: `The type of the policy identified in source_policy_id.`, + }, + // NOTE: start position and end position + // omitted right now because they would + // ideally be singleton objects with + // column/line attributes, but this SDK + // can't support that. Maybe we later adopt + // the new framework and add support for + // those. + }, + }, + Description: `Detail about which specific policies contributed to this result.`, + }, + "missing_context_keys": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: `Set of context entry keys that were needed for one or more of the relevant policies but not included in the request. You must specify suitable values for all context keys used in all of the relevant policies in order to obtain a correct simulation result.`, + }, + // NOTE: organizations decision detail, permissions + // boundary decision detail, and resource-specific + // results omitted for now because it isn't clear + // that they will be useful and they would make the + // results of this data source considerably larger + // and more complicated. + }, + }, + }, + "id": { + Type: schema.TypeString, + Computed: true, + Description: `Do not use`, + }, + }, + } +} + +func dataSourcePrincipalPolicySimulationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*conns.AWSClient).IAMConn + + setAsAWSStringSlice := func(raw interface{}) []*string { + listOfInterface := raw.(*schema.Set).List() + if len(listOfInterface) == 0 { + return nil + } + ret := make([]*string, len(listOfInterface)) + for i, iface := range listOfInterface { + str := iface.(string) + ret[i] = &str + } + return ret + } + + input := &iam.SimulatePrincipalPolicyInput{ + ActionNames: setAsAWSStringSlice(d.Get("action_names")), + PermissionsBoundaryPolicyInputList: setAsAWSStringSlice(d.Get("permissions_boundary_policies_json")), + PolicyInputList: setAsAWSStringSlice(d.Get("additional_policies_json")), + PolicySourceArn: aws.String(d.Get("policy_source_arn").(string)), + ResourceArns: setAsAWSStringSlice(d.Get("resource_arns")), + } + + for _, entryRaw := range d.Get("context").(*schema.Set).List() { + entryRaw := entryRaw.(map[string]interface{}) + entry := &iam.ContextEntry{ + ContextKeyName: aws.String(entryRaw["key"].(string)), + ContextKeyType: aws.String(entryRaw["type"].(string)), + ContextKeyValues: setAsAWSStringSlice(entryRaw["values"]), + } + input.ContextEntries = append(input.ContextEntries, entry) + } + + if v := d.Get("caller_arn").(string); v != "" { + input.CallerArn = aws.String(v) + } + if v := d.Get("resource_handling_option").(string); v != "" { + input.ResourceHandlingOption = aws.String(v) + } + if v := d.Get("resource_owner_account_id").(string); v != "" { + input.ResourceOwner = aws.String(v) + } + if v := d.Get("resource_policy_json").(string); v != "" { + input.ResourcePolicy = aws.String(v) + } + + // We are going to keep fetching through potentially multiple pages of + // results in order to return a complete result, so we'll ask the API + // to return as much as possible in each request to minimize the + // round-trips. + input.MaxItems = aws.Int64(1000) + + var results []*iam.EvaluationResult + + for { // Terminates below, once we see a result that does not set IsTruncated. + resp, err := conn.SimulatePrincipalPolicy(input) + if err != nil { + return fmt.Errorf("policy simulation error (%s): %w", d.Id(), err) + } + + results = append(results, resp.EvaluationResults...) + + if !aws.BoolValue(resp.IsTruncated) { + break // All done! + } + + // If we're making another request then we need to specify the marker + // to get the next page of results. + input.Marker = resp.Marker + } + + // While we build the result we'll also tally up the number of allowed + // vs. denied decisions to use for our top-level "all_allowed" summary + // result. + allowedCount := 0 + deniedCount := 0 + + rawResults := make([]interface{}, len(results)) + for i, result := range results { + rawResult := map[string]interface{}{} + rawResult["action_name"] = aws.StringValue(result.EvalActionName) + rawResult["decision"] = aws.StringValue(result.EvalDecision) + allowed := aws.StringValue(result.EvalDecision) == "allowed" + rawResult["allowed"] = allowed + if allowed { + allowedCount++ + } else { + deniedCount++ + } + if result.EvalResourceName != nil { + rawResult["resource_arn"] = aws.StringValue(result.EvalResourceName) + } + + var missingContextKeys []string + for _, mkk := range result.MissingContextValues { + if mkk != nil { + missingContextKeys = append(missingContextKeys, *mkk) + } + } + rawResult["missing_context_keys"] = missingContextKeys + + decisionDetails := make(map[string]string, len(result.EvalDecisionDetails)) + for k, pv := range result.EvalDecisionDetails { + if pv != nil { + decisionDetails[k] = aws.StringValue(pv) + } + } + rawResult["decision_details"] = decisionDetails + + rawMatchedStmts := make([]interface{}, len(result.MatchedStatements)) + for i, stmt := range result.MatchedStatements { + rawStmt := map[string]interface{}{ + "source_policy_id": stmt.SourcePolicyId, + "source_policy_type": stmt.SourcePolicyType, + } + rawMatchedStmts[i] = rawStmt + } + rawResult["matched_statements"] = rawMatchedStmts + + rawResults[i] = rawResult + } + d.Set("results", rawResults) + + // "all" are allowed only if there is at least one result and no other + // results were denied. We require at least one allowed here just as + // a safety-net against a confusing result from a degenerate request. + d.Set("all_allowed", allowedCount > 0 && deniedCount == 0) + + d.SetId("-") + + return nil +} diff --git a/internal/service/iam/principal_policy_simulation_data_source_test.go b/internal/service/iam/principal_policy_simulation_data_source_test.go new file mode 100644 index 000000000000..ed2f13147be5 --- /dev/null +++ b/internal/service/iam/principal_policy_simulation_data_source_test.go @@ -0,0 +1,209 @@ +package iam_test + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/iam" + sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" +) + +func TestAccIAMPrincipalPolicySimulationDataSource(t *testing.T) { + + uniqueName := fmt.Sprintf("policy-simulation-test-%d", sdkacctest.RandInt()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, iam.EndpointsID), + ProviderFactories: acctest.ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccPrincipalPolicySimulationDataSource_main(uniqueName), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "all_allowed", "true"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.#", "1"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.0.action_name", "ec2:AssociateVpcCidrBlock"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.0.allowed", "true"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.0.decision", "allowed"), + + // IAM seems to generate the SourcePolicyId by concatenating + // together the username, the policy name, and some other + // hard-coded bits. Not sure if this is constractual, so + // if this turns out to change in future it may be better + // to test this in a different way. + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.0.matched_statements.0.source_policy_id", fmt.Sprintf("user_%s_%s", uniqueName, uniqueName)), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.0.matched_statements.0.source_policy_type", "IAM Policy"), + + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_explicit", "all_allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_explicit", "results.#", "1"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_explicit", "results.0.action_name", "ec2:AttachClassicLinkVpc"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_explicit", "results.0.allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_explicit", "results.0.decision", "explicitDeny"), + + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_implicit", "all_allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_implicit", "results.#", "1"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_implicit", "results.0.action_name", "ec2:AttachVpnGateway"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_implicit", "results.0.allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.deny_implicit", "results.0.decision", "implicitDeny"), + + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_context", "all_allowed", "true"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_context", "results.#", "1"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_context", "results.0.action_name", "ec2:AttachInternetGateway"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_context", "results.0.allowed", "true"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_context", "results.0.decision", "allowed"), + + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_wrong_context", "all_allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_wrong_context", "results.#", "1"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_wrong_context", "results.0.action_name", "ec2:AttachInternetGateway"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_wrong_context", "results.0.allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_with_wrong_context", "results.0.decision", "implicitDeny"), + + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.multiple_mixed", "all_allowed", "false"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.multiple_mixed", "results.#", "2"), + + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.multiple_allow", "all_allowed", "true"), + resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.multiple_allow", "results.#", "2"), + + func(state *terraform.State) error { + vpcARN := state.RootModule().Outputs["vpc_arn"].Value.(string) + return resource.TestCheckResourceAttr("data.aws_iam_principal_policy_simulation.allow_simple", "results.0.resource_arn", vpcARN)(state) + }, + ), + }, + }, + }) +} + +func testAccPrincipalPolicySimulationDataSource_main(name string) string { + return fmt.Sprintf(` +resource "aws_iam_user" "test" { + name = "%s" +} + +resource "aws_vpc" "test" { + cidr_block = "192.168.0.0/16" +} + +resource "aws_iam_user_policy" "test" { + name = "%s" + user = aws_iam_user.test.name + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Action = "ec2:AssociateVpcCidrBlock" + Effect = "Allow" + Resource = aws_vpc.test.arn + }, + { + Action = "ec2:AttachClassicLinkVpc" + Effect = "Deny" + Resource = aws_vpc.test.arn + }, + { + Action = "ec2:AttachInternetGateway" + Effect = "Allow" + Resource = aws_vpc.test.arn + Condition = { + StringEquals = { + "ec2:ResourceTag/Foo" = "bar" + } + } + }, + ] + }) +} + +data "aws_iam_principal_policy_simulation" "allow_simple" { + action_names = ["ec2:AssociateVpcCidrBlock"] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + depends_on = [aws_iam_user_policy.test] +} + +data "aws_iam_principal_policy_simulation" "deny_explicit" { + action_names = ["ec2:AttachClassicLinkVpc"] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + depends_on = [aws_iam_user_policy.test] +} + +data "aws_iam_principal_policy_simulation" "deny_implicit" { + # This one is implicit deny because our policy + # doesn't mention ec2:AttachVpnGateway at all. + action_names = ["ec2:AttachVpnGateway"] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + depends_on = [aws_iam_user_policy.test] +} + +data "aws_iam_principal_policy_simulation" "allow_with_context" { + action_names = ["ec2:AttachInternetGateway"] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + context { + key = "ec2:ResourceTag/Foo" + type = "string" + values = ["bar"] + } + + depends_on = [aws_iam_user_policy.test] +} + +data "aws_iam_principal_policy_simulation" "allow_with_wrong_context" { + action_names = ["ec2:AttachInternetGateway"] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + context { + key = "ec2:ResourceTag/Foo" + type = "string" + values = ["baz"] + } + + depends_on = [aws_iam_user_policy.test] +} + +data "aws_iam_principal_policy_simulation" "multiple_mixed" { + action_names = [ + "ec2:AssociateVpcCidrBlock", + "ec2:AttachClassicLinkVpc", + ] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + depends_on = [aws_iam_user_policy.test] +} + +data "aws_iam_principal_policy_simulation" "multiple_allow" { + action_names = [ + "ec2:AssociateVpcCidrBlock", + "ec2:AttachInternetGateway", + ] + resource_arns = [aws_vpc.test.arn] + policy_source_arn = aws_iam_user.test.arn + + context { + key = "ec2:ResourceTag/Foo" + type = "string" + values = ["bar"] + } + + depends_on = [aws_iam_user_policy.test] +} + +output "vpc_arn" { + value = aws_vpc.test.arn +} +`, + name, name, + ) +} diff --git a/website/docs/d/iam_principal_policy_simulation.html.markdown b/website/docs/d/iam_principal_policy_simulation.html.markdown new file mode 100644 index 000000000000..3d877227165c --- /dev/null +++ b/website/docs/d/iam_principal_policy_simulation.html.markdown @@ -0,0 +1,220 @@ +--- +subcategory: "IAM (Identity & Access Management)" +layout: "aws" +page_title: "AWS: aws_iam_principal_policy_simulation" +description: |- + Runs a simulation of the IAM policies of a particular princial against a given hypothetical request. +--- + +# Data Source: aws_iam_principal_policy_simulation + +Runs a simulation of the IAM policies of a particular princial against a given hypothetical request. + +You can use this data source in conjunction with +[Preconditions and Postconditions](https://www.terraform.io/language/expressions/custom-conditions#preconditions-and-postconditions) so that your configuration can test either whether it should have sufficient access to do its own work, or whether policies your configuration declares itself are sufficient for their intended use elsewhere. + +-> **Note:** Correctly using this data source requires familiarity with various details of AWS Identity and Access Management, and how various AWS services integrate with it. For general information on the AWS IAM policy simulator, see [Testing IAM policies with the IAM policy simulator](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html). This data source wraps the `iam:SimulatePrincipalPolicy` API action described on that page. + +## Example Usage + +### Self Access-checking Example + +The following example raises an error if the credentials passed to the AWS provider do not have access to perform the three actions `s3:GetObject`, `s3:PutObject`, and `s3:DeleteObject` on the S3 bucket with the given ARN. It combines `aws_iam_principal_policy_simulation` with the core Terraform postconditions feature. + +```terraform +data "aws_caller_identity" "current" {} + +data "aws_iam_principal_policy_simulation" "s3_object_access" { + action_names = [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + ] + policy_source_arn = data.aws_caller_identity.current.arn + resource_arns = ["arn:aws:s3:::my-test-bucket"] + + # The "lifecycle" and "postcondition" block types are part of + # the main Terraform language, not part of this data source. + lifecycle { + postcondition { + condition = self.all_allowed + error_message = <