Skip to content
v2.274.0

AWS Config Construct Library ​

AWS Config provides a detailed view of the configuration of AWS resources in your AWS account. This includes how the resources are related to one another and how they were configured in the past so that you can see how the configurations and relationships change over time.

This module is part of the AWS Cloud Development Kit project.

Initial Setup ​

Before using the constructs provided in this module, you need to set up AWS Config in the region in which it will be used. This setup includes the one-time creation of the following resources per region:

  • ConfigurationRecorder: Configure which resources will be recorded for config changes.
  • DeliveryChannel: Configure where to store the recorded data.

The following guides provide the steps for getting started with AWS Config:

Rules ​

AWS Config can evaluate the configuration settings of your AWS resources by creating AWS Config rules, which represent your ideal configuration settings.

See Evaluating Resources with AWS Config Rules to learn more about AWS Config rules.

AWS Managed Rules ​

AWS Config provides AWS managed rules, which are predefined, customizable rules that AWS Config uses to evaluate whether your AWS resources comply with common best practices.

For example, you could create a managed rule that checks whether active access keys are rotated within the number of days specified.

ts
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
new config.ManagedRule(this, 'AccessKeysRotated', {
  identifier: config.ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED,
  inputParameters: {
    maxAccessKeyAge: 60, // default is 90 days
  },

  // default is 24 hours
  maximumExecutionFrequency: config.MaximumExecutionFrequency.TWELVE_HOURS,
});
python
# https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
config.ManagedRule(self, "AccessKeysRotated",
    identifier=config.ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED,
    input_parameters={
        "max_access_key_age": 60
    },

    # default is 24 hours
    maximum_execution_frequency=config.MaximumExecutionFrequency.TWELVE_HOURS
)
java
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
ManagedRule.Builder.create(this, "AccessKeysRotated")
        .identifier(ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED)
        .inputParameters(Map.of(
                "maxAccessKeyAge", 60))

        // default is 24 hours
        .maximumExecutionFrequency(MaximumExecutionFrequency.TWELVE_HOURS)
        .build();
csharp
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
new ManagedRule(this, "AccessKeysRotated", new ManagedRuleProps {
    Identifier = ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED,
    InputParameters = new Dictionary<string, object> {
        { "maxAccessKeyAge", 60 }
    },

    // default is 24 hours
    MaximumExecutionFrequency = MaximumExecutionFrequency.TWELVE_HOURS
});
go
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
// https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html
config.NewManagedRule(this, jsii.String("AccessKeysRotated"), &ManagedRuleProps{
	Identifier: config.ManagedRuleIdentifiers_ACCESS_KEYS_ROTATED(),
	InputParameters: map[string]interface{}{
		"maxAccessKeyAge": jsii.Number(60),
	},

	// default is 24 hours
	MaximumExecutionFrequency: config.MaximumExecutionFrequency_TWELVE_HOURS,
})

Identifiers for AWS managed rules are available through static constants in the ManagedRuleIdentifiers class. You can find supported input parameters in the List of AWS Config Managed Rules.

The following higher level constructs for AWS managed rules are available.

Access Key rotation ​

Checks whether your active access keys are rotated within the number of days specified.

ts
// compliant if access keys have been rotated within the last 90 days
new config.AccessKeysRotated(this, 'AccessKeyRotated');
python
# compliant if access keys have been rotated within the last 90 days
config.AccessKeysRotated(self, "AccessKeyRotated")
java
// compliant if access keys have been rotated within the last 90 days
// compliant if access keys have been rotated within the last 90 days
new AccessKeysRotated(this, "AccessKeyRotated");
csharp
// compliant if access keys have been rotated within the last 90 days
// compliant if access keys have been rotated within the last 90 days
new AccessKeysRotated(this, "AccessKeyRotated");
go
// compliant if access keys have been rotated within the last 90 days
// compliant if access keys have been rotated within the last 90 days
config.NewAccessKeysRotated(this, jsii.String("AccessKeyRotated"))

CloudFormation Stack drift detection ​

Checks whether your CloudFormation stack's actual configuration differs, or has drifted, from it's expected configuration.

ts
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
new config.CloudFormationStackDriftDetectionCheck(this, 'Drift', {
  ownStackOnly: true, // checks only the stack containing the rule
});
python
# compliant if stack's status is 'IN_SYNC'
# non-compliant if the stack's drift status is 'DRIFTED'
config.CloudFormationStackDriftDetectionCheck(self, "Drift",
    own_stack_only=True
)
java
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
CloudFormationStackDriftDetectionCheck.Builder.create(this, "Drift")
        .ownStackOnly(true)
        .build();
csharp
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
new CloudFormationStackDriftDetectionCheck(this, "Drift", new CloudFormationStackDriftDetectionCheckProps {
    OwnStackOnly = true
});
go
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
// compliant if stack's status is 'IN_SYNC'
// non-compliant if the stack's drift status is 'DRIFTED'
config.NewCloudFormationStackDriftDetectionCheck(this, jsii.String("Drift"), &CloudFormationStackDriftDetectionCheckProps{
	OwnStackOnly: jsii.Boolean(true),
})

CloudFormation Stack notifications ​

Checks whether your CloudFormation stacks are sending event notifications to a SNS topic.

ts
// topics to which CloudFormation stacks may send event notifications
const topic1 = new sns.Topic(this, 'AllowedTopic1');
const topic2 = new sns.Topic(this, 'AllowedTopic2');

// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
new config.CloudFormationStackNotificationCheck(this, 'NotificationCheck', {
  topics: [topic1, topic2],
});
python
# topics to which CloudFormation stacks may send event notifications
topic1 = sns.Topic(self, "AllowedTopic1")
topic2 = sns.Topic(self, "AllowedTopic2")

# non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
config.CloudFormationStackNotificationCheck(self, "NotificationCheck",
    topics=[topic1, topic2]
)
java
// topics to which CloudFormation stacks may send event notifications
Topic topic1 = new Topic(this, "AllowedTopic1");
Topic topic2 = new Topic(this, "AllowedTopic2");

// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
CloudFormationStackNotificationCheck.Builder.create(this, "NotificationCheck")
        .topics(List.of(topic1, topic2))
        .build();
csharp
// topics to which CloudFormation stacks may send event notifications
var topic1 = new Topic(this, "AllowedTopic1");
var topic2 = new Topic(this, "AllowedTopic2");

// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
new CloudFormationStackNotificationCheck(this, "NotificationCheck", new CloudFormationStackNotificationCheckProps {
    Topics = new [] { topic1, topic2 }
});
go
// topics to which CloudFormation stacks may send event notifications
topic1 := sns.NewTopic(this, jsii.String("AllowedTopic1"))
topic2 := sns.NewTopic(this, jsii.String("AllowedTopic2"))

// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
// non-compliant if CloudFormation stack does not send notifications to 'topic1' or 'topic2'
config.NewCloudFormationStackNotificationCheck(this, jsii.String("NotificationCheck"), &CloudFormationStackNotificationCheckProps{
	Topics: []ITopic{
		topic1,
		topic2,
	},
})

Custom rules ​

You can develop custom rules and add them to AWS Config. You associate each custom rule with an AWS Lambda function and Guard.

Custom Lambda Rules ​

Lambda function which contains the logic that evaluates whether your AWS resources comply with the rule.

ts
// Lambda function containing logic that evaluates compliance with the rule.
const evalComplianceFn = new lambda.Function(this, "CustomFunction", {
  code: lambda.AssetCode.fromInline(
    "exports.handler = (event) => console.log(event);"
  ),
  handler: "index.handler",
  runtime: lambda.Runtime.NODEJS_LATEST,
});

// A custom rule that runs on configuration changes of EC2 instances
const customRule = new config.CustomRule(this, "Custom", {
  configurationChanges: true,
  lambdaFunction: evalComplianceFn,
  ruleScope: config.RuleScope.fromResource(config.ResourceType.EC2_INSTANCE),
});
python
# Lambda function containing logic that evaluates compliance with the rule.
eval_compliance_fn = lambda_.Function(self, "CustomFunction",
    code=lambda_.AssetCode.from_inline("exports.handler = (event) => console.log(event);"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST
)

# A custom rule that runs on configuration changes of EC2 instances
custom_rule = config.CustomRule(self, "Custom",
    configuration_changes=True,
    lambda_function=eval_compliance_fn,
    rule_scope=config.RuleScope.from_resource(config.ResourceType.EC2_INSTANCE)
)
java
// Lambda function containing logic that evaluates compliance with the rule.
Function evalComplianceFn = Function.Builder.create(this, "CustomFunction")
        .code(AssetCode.fromInline("exports.handler = (event) => console.log(event);"))
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .build();

// A custom rule that runs on configuration changes of EC2 instances
CustomRule customRule = CustomRule.Builder.create(this, "Custom")
        .configurationChanges(true)
        .lambdaFunction(evalComplianceFn)
        .ruleScope(RuleScope.fromResource(ResourceType.EC2_INSTANCE))
        .build();
csharp
// Lambda function containing logic that evaluates compliance with the rule.
var evalComplianceFn = new Function(this, "CustomFunction", new FunctionProps {
    Code = AssetCode.FromInline("exports.handler = (event) => console.log(event);"),
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST
});

// A custom rule that runs on configuration changes of EC2 instances
var customRule = new CustomRule(this, "Custom", new CustomRuleProps {
    ConfigurationChanges = true,
    LambdaFunction = evalComplianceFn,
    RuleScope = RuleScope.FromResource(ResourceType.EC2_INSTANCE)
});
go
// Lambda function containing logic that evaluates compliance with the rule.
evalComplianceFn := lambda.NewFunction(this, jsii.String("CustomFunction"), &FunctionProps{
	Code: lambda.AssetCode_FromInline(jsii.String("exports.handler = (event) => console.log(event);")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
})

// A custom rule that runs on configuration changes of EC2 instances
customRule := config.NewCustomRule(this, jsii.String("Custom"), &CustomRuleProps{
	ConfigurationChanges: jsii.Boolean(true),
	LambdaFunction: evalComplianceFn,
	RuleScope: config.RuleScope_FromResource(config.ResourceType_EC2_INSTANCE()),
})

Custom Policy Rules ​

Guard which contains the logic that evaluates whether your AWS resources comply with the rule.

ts
const samplePolicyText = `
# This rule checks if point in time recovery (PITR) is enabled on active Amazon DynamoDB tables
let status = ['ACTIVE']

rule tableisactive when
    resourceType == "AWS::DynamoDB::Table" {
    configuration.tableStatus == %status
}

rule checkcompliance when
    resourceType == "AWS::DynamoDB::Table"
    tableisactive {
        let pitr = supplementaryConfiguration.ContinuousBackupsDescription.pointInTimeRecoveryDescription.pointInTimeRecoveryStatus
        %pitr == "ENABLED"
}
`;

new config.CustomPolicy(this, "Custom", {
  policyText: samplePolicyText,
  enableDebugLog: true,
  ruleScope: config.RuleScope.fromResources([
    config.ResourceType.DYNAMODB_TABLE,
  ]),
});
python
sample_policy_text = """
# This rule checks if point in time recovery (PITR) is enabled on active Amazon DynamoDB tables
let status = ['ACTIVE']

rule tableisactive when
    resourceType == "AWS::DynamoDB::Table" {
    configuration.tableStatus == %status
}

rule checkcompliance when
    resourceType == "AWS::DynamoDB::Table"
    tableisactive {
        let pitr = supplementaryConfiguration.ContinuousBackupsDescription.pointInTimeRecoveryDescription.pointInTimeRecoveryStatus
        %pitr == "ENABLED"
}
"""

config.CustomPolicy(self, "Custom",
    policy_text=sample_policy_text,
    enable_debug_log=True,
    rule_scope=config.RuleScope.from_resources([config.ResourceType.DYNAMODB_TABLE
    ])
)
java
String samplePolicyText = "\n# This rule checks if point in time recovery (PITR) is enabled on active Amazon DynamoDB tables\nlet status = ['ACTIVE']\n\nrule tableisactive when\n    resourceType == \"AWS::DynamoDB::Table\" {\n    configuration.tableStatus == %status\n}\n\nrule checkcompliance when\n    resourceType == \"AWS::DynamoDB::Table\"\n    tableisactive {\n        let pitr = supplementaryConfiguration.ContinuousBackupsDescription.pointInTimeRecoveryDescription.pointInTimeRecoveryStatus\n        %pitr == \"ENABLED\"\n}\n";

CustomPolicy.Builder.create(this, "Custom")
        .policyText(samplePolicyText)
        .enableDebugLog(true)
        .ruleScope(RuleScope.fromResources(List.of(ResourceType.DYNAMODB_TABLE)))
        .build();
csharp
var samplePolicyText = @"
# This rule checks if point in time recovery (PITR) is enabled on active Amazon DynamoDB tables
let status = ['ACTIVE']

rule tableisactive when
    resourceType == ""AWS::DynamoDB::Table"" {
    configuration.tableStatus == %status
}

rule checkcompliance when
    resourceType == ""AWS::DynamoDB::Table""
    tableisactive {
        let pitr = supplementaryConfiguration.ContinuousBackupsDescription.pointInTimeRecoveryDescription.pointInTimeRecoveryStatus
        %pitr == ""ENABLED""
}
";

new CustomPolicy(this, "Custom", new CustomPolicyProps {
    PolicyText = samplePolicyText,
    EnableDebugLog = true,
    RuleScope = RuleScope.FromResources(new [] { ResourceType.DYNAMODB_TABLE })
});
go
samplePolicyText := `
# This rule checks if point in time recovery (PITR) is enabled on active Amazon DynamoDB tables
let status = ['ACTIVE']

rule tableisactive when
    resourceType == "AWS::DynamoDB::Table" {
    configuration.tableStatus == %status
}

rule checkcompliance when
    resourceType == "AWS::DynamoDB::Table"
    tableisactive {
        let pitr = supplementaryConfiguration.ContinuousBackupsDescription.pointInTimeRecoveryDescription.pointInTimeRecoveryStatus
        %pitr == "ENABLED"
}
`

config.NewCustomPolicy(this, jsii.String("Custom"), &CustomPolicyProps{
	PolicyText: samplePolicyText,
	EnableDebugLog: jsii.Boolean(true),
	RuleScope: config.RuleScope_FromResources([]ResourceType{
		config.ResourceType_DYNAMODB_TABLE(),
	}),
})

Triggers ​

AWS Lambda executes functions in response to events that are published by AWS Services. The function for a custom Config rule receives an event that is published by AWS Config, and is responsible for evaluating the compliance of the rule.

Evaluations can be triggered by configuration changes, periodically, or both. To create a custom rule, define a CustomRule and specify the Lambda Function to run and the trigger types.

ts
declare const evalComplianceFn: lambda.Function;

new config.CustomRule(this, 'CustomRule', {
  lambdaFunction: evalComplianceFn,
  configurationChanges: true,
  periodic: true,

  // default is 24 hours
  maximumExecutionFrequency: config.MaximumExecutionFrequency.SIX_HOURS,
});
python
# eval_compliance_fn: lambda.Function


config.CustomRule(self, "CustomRule",
    lambda_function=eval_compliance_fn,
    configuration_changes=True,
    periodic=True,

    # default is 24 hours
    maximum_execution_frequency=config.MaximumExecutionFrequency.SIX_HOURS
)
java
Function evalComplianceFn;


CustomRule.Builder.create(this, "CustomRule")
        .lambdaFunction(evalComplianceFn)
        .configurationChanges(true)
        .periodic(true)

        // default is 24 hours
        .maximumExecutionFrequency(MaximumExecutionFrequency.SIX_HOURS)
        .build();
csharp
Function evalComplianceFn;


new CustomRule(this, "CustomRule", new CustomRuleProps {
    LambdaFunction = evalComplianceFn,
    ConfigurationChanges = true,
    Periodic = true,

    // default is 24 hours
    MaximumExecutionFrequency = MaximumExecutionFrequency.SIX_HOURS
});
go
var evalComplianceFn Function


config.NewCustomRule(this, jsii.String("CustomRule"), &CustomRuleProps{
	LambdaFunction: evalComplianceFn,
	ConfigurationChanges: jsii.Boolean(true),
	Periodic: jsii.Boolean(true),

	// default is 24 hours
	MaximumExecutionFrequency: config.MaximumExecutionFrequency_SIX_HOURS,
})

When the trigger for a rule occurs, the Lambda function is invoked by publishing an event. See example events for AWS Config Rules

The AWS documentation has examples of Lambda functions for evaluations that are triggered by configuration changes and triggered periodically

Scope ​

By default rules are triggered by changes to all resources.

Use the RuleScope APIs (fromResource(), fromResources() or fromTag()) to restrict the scope of both managed and custom rules:

ts
const sshRule = new config.ManagedRule(this, 'SSH', {
  identifier: config.ManagedRuleIdentifiers.EC2_SECURITY_GROUPS_INCOMING_SSH_DISABLED,
  ruleScope: config.RuleScope.fromResource(config.ResourceType.EC2_SECURITY_GROUP, 'sg-1234567890abcdefgh'), // restrict to specific security group
});

declare const evalComplianceFn: lambda.Function;
const customRule = new config.CustomRule(this, 'Lambda', {
  lambdaFunction: evalComplianceFn,
  configurationChanges: true,
  ruleScope: config.RuleScope.fromResources([config.ResourceType.CLOUDFORMATION_STACK, config.ResourceType.S3_BUCKET]), // restrict to all CloudFormation stacks and S3 buckets
});

const tagRule = new config.CustomRule(this, 'CostCenterTagRule', {
  lambdaFunction: evalComplianceFn,
  configurationChanges: true,
  ruleScope: config.RuleScope.fromTag('Cost Center', 'MyApp'), // restrict to a specific tag
});
python
# eval_compliance_fn: lambda.Function
ssh_rule = config.ManagedRule(self, "SSH",
    identifier=config.ManagedRuleIdentifiers.EC2_SECURITY_GROUPS_INCOMING_SSH_DISABLED,
    rule_scope=config.RuleScope.from_resource(config.ResourceType.EC2_SECURITY_GROUP, "sg-1234567890abcdefgh")
)
custom_rule = config.CustomRule(self, "Lambda",
    lambda_function=eval_compliance_fn,
    configuration_changes=True,
    rule_scope=config.RuleScope.from_resources([config.ResourceType.CLOUDFORMATION_STACK, config.ResourceType.S3_BUCKET])
)

tag_rule = config.CustomRule(self, "CostCenterTagRule",
    lambda_function=eval_compliance_fn,
    configuration_changes=True,
    rule_scope=config.RuleScope.from_tag("Cost Center", "MyApp")
)
java
Function evalComplianceFn;
ManagedRule sshRule = ManagedRule.Builder.create(this, "SSH")
        .identifier(ManagedRuleIdentifiers.EC2_SECURITY_GROUPS_INCOMING_SSH_DISABLED)
        .ruleScope(RuleScope.fromResource(ResourceType.EC2_SECURITY_GROUP, "sg-1234567890abcdefgh"))
        .build();
CustomRule customRule = CustomRule.Builder.create(this, "Lambda")
        .lambdaFunction(evalComplianceFn)
        .configurationChanges(true)
        .ruleScope(RuleScope.fromResources(List.of(ResourceType.CLOUDFORMATION_STACK, ResourceType.S3_BUCKET)))
        .build();

CustomRule tagRule = CustomRule.Builder.create(this, "CostCenterTagRule")
        .lambdaFunction(evalComplianceFn)
        .configurationChanges(true)
        .ruleScope(RuleScope.fromTag("Cost Center", "MyApp"))
        .build();
csharp
Function evalComplianceFn;
var sshRule = new ManagedRule(this, "SSH", new ManagedRuleProps {
    Identifier = ManagedRuleIdentifiers.EC2_SECURITY_GROUPS_INCOMING_SSH_DISABLED,
    RuleScope = RuleScope.FromResource(ResourceType.EC2_SECURITY_GROUP, "sg-1234567890abcdefgh")
});
var customRule = new CustomRule(this, "Lambda", new CustomRuleProps {
    LambdaFunction = evalComplianceFn,
    ConfigurationChanges = true,
    RuleScope = RuleScope.FromResources(new [] { ResourceType.CLOUDFORMATION_STACK, ResourceType.S3_BUCKET })
});

var tagRule = new CustomRule(this, "CostCenterTagRule", new CustomRuleProps {
    LambdaFunction = evalComplianceFn,
    ConfigurationChanges = true,
    RuleScope = RuleScope.FromTag("Cost Center", "MyApp")
});
go
var evalComplianceFn Function
sshRule := config.NewManagedRule(this, jsii.String("SSH"), &ManagedRuleProps{
	Identifier: config.ManagedRuleIdentifiers_EC2_SECURITY_GROUPS_INCOMING_SSH_DISABLED(),
	RuleScope: config.RuleScope_FromResource(config.ResourceType_EC2_SECURITY_GROUP(), jsii.String("sg-1234567890abcdefgh")),
})
customRule := config.NewCustomRule(this, jsii.String("Lambda"), &CustomRuleProps{
	LambdaFunction: evalComplianceFn,
	ConfigurationChanges: jsii.Boolean(true),
	RuleScope: config.RuleScope_FromResources([]ResourceType{
		config.ResourceType_CLOUDFORMATION_STACK(),
		config.ResourceType_S3_BUCKET(),
	}),
})

tagRule := config.NewCustomRule(this, jsii.String("CostCenterTagRule"), &CustomRuleProps{
	LambdaFunction: evalComplianceFn,
	ConfigurationChanges: jsii.Boolean(true),
	RuleScope: config.RuleScope_FromTag(jsii.String("Cost Center"), jsii.String("MyApp")),
})

Evaluation Mode ​

You can specify the evaluation mode for a rule to determine when AWS Config runs evaluations.

Use the evaluationModes property to specify the evaluation mode:

ts
declare const fn: lambda.Function;
declare const samplePolicyText: string;

new config.ManagedRule(this, 'ManagedRule', {
  identifier: config.ManagedRuleIdentifiers.API_GW_XRAY_ENABLED,
  evaluationModes: config.EvaluationMode.DETECTIVE_AND_PROACTIVE,
});

new config.CustomRule(this, 'CustomRule', {
  lambdaFunction: fn,
  evaluationModes: config.EvaluationMode.PROACTIVE,
});

new config.CustomPolicy(this, 'CustomPolicy', {
  policyText: samplePolicyText,
  evaluationModes: config.EvaluationMode.DETECTIVE,
});
python
# fn: lambda.Function
# sample_policy_text: str


config.ManagedRule(self, "ManagedRule",
    identifier=config.ManagedRuleIdentifiers.API_GW_XRAY_ENABLED,
    evaluation_modes=config.EvaluationMode.DETECTIVE_AND_PROACTIVE
)

config.CustomRule(self, "CustomRule",
    lambda_function=fn,
    evaluation_modes=config.EvaluationMode.PROACTIVE
)

config.CustomPolicy(self, "CustomPolicy",
    policy_text=sample_policy_text,
    evaluation_modes=config.EvaluationMode.DETECTIVE
)
java
Function fn;
String samplePolicyText;


ManagedRule.Builder.create(this, "ManagedRule")
        .identifier(ManagedRuleIdentifiers.API_GW_XRAY_ENABLED)
        .evaluationModes(EvaluationMode.DETECTIVE_AND_PROACTIVE)
        .build();

CustomRule.Builder.create(this, "CustomRule")
        .lambdaFunction(fn)
        .evaluationModes(EvaluationMode.PROACTIVE)
        .build();

CustomPolicy.Builder.create(this, "CustomPolicy")
        .policyText(samplePolicyText)
        .evaluationModes(EvaluationMode.DETECTIVE)
        .build();
csharp
Function fn;
string samplePolicyText;


new ManagedRule(this, "ManagedRule", new ManagedRuleProps {
    Identifier = ManagedRuleIdentifiers.API_GW_XRAY_ENABLED,
    EvaluationModes = EvaluationMode.DETECTIVE_AND_PROACTIVE
});

new CustomRule(this, "CustomRule", new CustomRuleProps {
    LambdaFunction = fn,
    EvaluationModes = EvaluationMode.PROACTIVE
});

new CustomPolicy(this, "CustomPolicy", new CustomPolicyProps {
    PolicyText = samplePolicyText,
    EvaluationModes = EvaluationMode.DETECTIVE
});
go
var fn Function
var samplePolicyText string


config.NewManagedRule(this, jsii.String("ManagedRule"), &ManagedRuleProps{
	Identifier: config.ManagedRuleIdentifiers_API_GW_XRAY_ENABLED(),
	EvaluationModes: config.EvaluationMode_DETECTIVE_AND_PROACTIVE(),
})

config.NewCustomRule(this, jsii.String("CustomRule"), &CustomRuleProps{
	LambdaFunction: fn,
	EvaluationModes: config.EvaluationMode_PROACTIVE(),
})

config.NewCustomPolicy(this, jsii.String("CustomPolicy"), &CustomPolicyProps{
	PolicyText: samplePolicyText,
	EvaluationModes: config.EvaluationMode_DETECTIVE(),
})

Note: Proactive evaluation mode is not supported for all rules. See AWS Config documentation for more information.

Events ​

You can define Amazon EventBridge event rules which trigger when a compliance check fails or when a rule is re-evaluated.

Use the onComplianceChange() APIs to trigger an EventBridge event when a compliance check of your AWS Config Rule fails:

ts
// Topic to which compliance notification events will be published
const complianceTopic = new sns.Topic(this, 'ComplianceTopic');

const rule = new config.CloudFormationStackDriftDetectionCheck(this, 'Drift');
rule.onComplianceChange('TopicEvent', {
  target: new targets.SnsTopic(complianceTopic),
});
python
# Topic to which compliance notification events will be published
compliance_topic = sns.Topic(self, "ComplianceTopic")

rule = config.CloudFormationStackDriftDetectionCheck(self, "Drift")
rule.on_compliance_change("TopicEvent",
    target=targets.SnsTopic(compliance_topic)
)
java
// Topic to which compliance notification events will be published
Topic complianceTopic = new Topic(this, "ComplianceTopic");

CloudFormationStackDriftDetectionCheck rule = new CloudFormationStackDriftDetectionCheck(this, "Drift");
rule.onComplianceChange("TopicEvent", OnEventOptions.builder()
        .target(new SnsTopic(complianceTopic))
        .build());
csharp
// Topic to which compliance notification events will be published
var complianceTopic = new Topic(this, "ComplianceTopic");

var rule = new CloudFormationStackDriftDetectionCheck(this, "Drift");
rule.OnComplianceChange("TopicEvent", new OnEventOptions {
    Target = new SnsTopic(complianceTopic)
});
go
// Topic to which compliance notification events will be published
complianceTopic := sns.NewTopic(this, jsii.String("ComplianceTopic"))

rule := config.NewCloudFormationStackDriftDetectionCheck(this, jsii.String("Drift"))
rule.onComplianceChange(jsii.String("TopicEvent"), &OnEventOptions{
	Target: targets.NewSnsTopic(complianceTopic),
})

Use the onReEvaluationStatus() status to trigger an EventBridge event when an AWS Config rule is re-evaluated.

ts
// Topic to which re-evaluation notification events will be published
const reEvaluationTopic = new sns.Topic(this, 'ComplianceTopic');

const rule = new config.CloudFormationStackDriftDetectionCheck(this, 'Drift');
rule.onReEvaluationStatus('ReEvaluationEvent', {
  target: new targets.SnsTopic(reEvaluationTopic),
});
python
# Topic to which re-evaluation notification events will be published
re_evaluation_topic = sns.Topic(self, "ComplianceTopic")

rule = config.CloudFormationStackDriftDetectionCheck(self, "Drift")
rule.on_re_evaluation_status("ReEvaluationEvent",
    target=targets.SnsTopic(re_evaluation_topic)
)
java
// Topic to which re-evaluation notification events will be published
Topic reEvaluationTopic = new Topic(this, "ComplianceTopic");

CloudFormationStackDriftDetectionCheck rule = new CloudFormationStackDriftDetectionCheck(this, "Drift");
rule.onReEvaluationStatus("ReEvaluationEvent", OnEventOptions.builder()
        .target(new SnsTopic(reEvaluationTopic))
        .build());
csharp
// Topic to which re-evaluation notification events will be published
var reEvaluationTopic = new Topic(this, "ComplianceTopic");

var rule = new CloudFormationStackDriftDetectionCheck(this, "Drift");
rule.OnReEvaluationStatus("ReEvaluationEvent", new OnEventOptions {
    Target = new SnsTopic(reEvaluationTopic)
});
go
// Topic to which re-evaluation notification events will be published
reEvaluationTopic := sns.NewTopic(this, jsii.String("ComplianceTopic"))

rule := config.NewCloudFormationStackDriftDetectionCheck(this, jsii.String("Drift"))
rule.onReEvaluationStatus(jsii.String("ReEvaluationEvent"), &OnEventOptions{
	Target: targets.NewSnsTopic(reEvaluationTopic),
})

Example ​

The following example creates a custom rule that evaluates whether EC2 instances are compliant. Compliance events are published to an SNS topic.

ts
// Lambda function containing logic that evaluates compliance with the rule.
const evalComplianceFn = new lambda.Function(this, 'CustomFunction', {
  code: lambda.AssetCode.fromInline('exports.handler = (event) => console.log(event);'),
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
});

// A custom rule that runs on configuration changes of EC2 instances
const customRule = new config.CustomRule(this, 'Custom', {
  configurationChanges: true,
  lambdaFunction: evalComplianceFn,
  ruleScope: config.RuleScope.fromResource(config.ResourceType.EC2_INSTANCE),
});

// A rule to detect stack drifts
const driftRule = new config.CloudFormationStackDriftDetectionCheck(this, 'Drift');

// Topic to which compliance notification events will be published
const complianceTopic = new sns.Topic(this, 'ComplianceTopic');

// Send notification on compliance change events
driftRule.onComplianceChange('ComplianceChange', {
  target: new targets.SnsTopic(complianceTopic),
});
python
# Lambda function containing logic that evaluates compliance with the rule.
eval_compliance_fn = lambda_.Function(self, "CustomFunction",
    code=lambda_.AssetCode.from_inline("exports.handler = (event) => console.log(event);"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST
)

# A custom rule that runs on configuration changes of EC2 instances
custom_rule = config.CustomRule(self, "Custom",
    configuration_changes=True,
    lambda_function=eval_compliance_fn,
    rule_scope=config.RuleScope.from_resource(config.ResourceType.EC2_INSTANCE)
)

# A rule to detect stack drifts
drift_rule = config.CloudFormationStackDriftDetectionCheck(self, "Drift")

# Topic to which compliance notification events will be published
compliance_topic = sns.Topic(self, "ComplianceTopic")

# Send notification on compliance change events
drift_rule.on_compliance_change("ComplianceChange",
    target=targets.SnsTopic(compliance_topic)
)
java
// Lambda function containing logic that evaluates compliance with the rule.
Function evalComplianceFn = Function.Builder.create(this, "CustomFunction")
        .code(AssetCode.fromInline("exports.handler = (event) => console.log(event);"))
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .build();

// A custom rule that runs on configuration changes of EC2 instances
CustomRule customRule = CustomRule.Builder.create(this, "Custom")
        .configurationChanges(true)
        .lambdaFunction(evalComplianceFn)
        .ruleScope(RuleScope.fromResource(ResourceType.EC2_INSTANCE))
        .build();

// A rule to detect stack drifts
CloudFormationStackDriftDetectionCheck driftRule = new CloudFormationStackDriftDetectionCheck(this, "Drift");

// Topic to which compliance notification events will be published
Topic complianceTopic = new Topic(this, "ComplianceTopic");

// Send notification on compliance change events
driftRule.onComplianceChange("ComplianceChange", OnEventOptions.builder()
        .target(new SnsTopic(complianceTopic))
        .build());
csharp
// Lambda function containing logic that evaluates compliance with the rule.
var evalComplianceFn = new Function(this, "CustomFunction", new FunctionProps {
    Code = AssetCode.FromInline("exports.handler = (event) => console.log(event);"),
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST
});

// A custom rule that runs on configuration changes of EC2 instances
var customRule = new CustomRule(this, "Custom", new CustomRuleProps {
    ConfigurationChanges = true,
    LambdaFunction = evalComplianceFn,
    RuleScope = RuleScope.FromResource(ResourceType.EC2_INSTANCE)
});

// A rule to detect stack drifts
var driftRule = new CloudFormationStackDriftDetectionCheck(this, "Drift");

// Topic to which compliance notification events will be published
var complianceTopic = new Topic(this, "ComplianceTopic");

// Send notification on compliance change events
driftRule.OnComplianceChange("ComplianceChange", new OnEventOptions {
    Target = new SnsTopic(complianceTopic)
});
go
// Lambda function containing logic that evaluates compliance with the rule.
evalComplianceFn := lambda.NewFunction(this, jsii.String("CustomFunction"), &FunctionProps{
	Code: lambda.AssetCode_FromInline(jsii.String("exports.handler = (event) => console.log(event);")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
})

// A custom rule that runs on configuration changes of EC2 instances
customRule := config.NewCustomRule(this, jsii.String("Custom"), &CustomRuleProps{
	ConfigurationChanges: jsii.Boolean(true),
	LambdaFunction: evalComplianceFn,
	RuleScope: config.RuleScope_FromResource(config.ResourceType_EC2_INSTANCE()),
})

// A rule to detect stack drifts
driftRule := config.NewCloudFormationStackDriftDetectionCheck(this, jsii.String("Drift"))

// Topic to which compliance notification events will be published
complianceTopic := sns.NewTopic(this, jsii.String("ComplianceTopic"))

// Send notification on compliance change events
driftRule.onComplianceChange(jsii.String("ComplianceChange"), &OnEventOptions{
	Target: targets.NewSnsTopic(complianceTopic),
})

Types ​

NameKindSummary
AccessKeysRotatedConstruct (L2)Checks whether the active access keys are rotated within the number of days specified in maxAge.
CloudFormationStackDriftDetectionCheckConstruct (L2)Checks whether your CloudFormation stacks' actual configuration differs, or has drifted, from its expected configuration.
CloudFormationStackNotificationCheckConstruct (L2)Checks whether your CloudFormation stacks are sending event notifications to a SNS topic.
CustomPolicyConstruct (L2)A new custom policy.
CustomRuleConstruct (L2)A new custom rule.
ManagedRuleConstruct (L2)A new managed rule.
CfnAggregationAuthorizationConstruct (L1)An object that represents the authorizations granted to aggregator accounts and regions.
CfnConfigRuleConstruct (L1)> You must first create and start the AWS Config configuration recorder in order to create AWS Config managed rules with AWS CloudFormation .
CfnConfigurationAggregatorConstruct (L1)The details about the configuration aggregator, including information about source accounts, regions, and metadata of the aggregator.
CfnConfigurationRecorderConstruct (L1)The AWS::Config::ConfigurationRecorder resource type describes the AWS resource types that AWS Config records for configuration changes.
CfnConformancePackConstruct (L1)A conformance pack is a collection of AWS Config rules and remediation actions that can be easily deployed in an account and a region.
CfnConnectorConstruct (L1)Resource Type definition for AWS::Config::Connector.
CfnDeliveryChannelConstruct (L1)Specifies a delivery channel object to deliver configuration information to an Amazon S3 bucket and Amazon topic.
CfnOrganizationConfigRuleConstruct (L1)Adds or updates an AWS Config rule for your entire organization to evaluate if your AWS resources comply with your desired configurations.
CfnOrganizationConformancePackConstruct (L1)OrganizationConformancePack deploys conformance packs across member accounts in an AWS Organizations .
CfnRemediationConfigurationConstruct (L1)An object that represents the details about the remediation configuration that includes the remediation action, parameters, and data to execute the action.
CfnStoredQueryConstruct (L1)Provides the details of a stored query.
AccessKeysRotatedPropsStructConstruction properties for a AccessKeysRotated.
CfnAggregationAuthorizationPropsStructProperties for defining a CfnAggregationAuthorization.
CfnConfigRule.CompliancePropertyStructIndicates whether an AWS resource or AWS Config rule is compliant and provides the number of contributors that affect the compliance.
CfnConfigRule.CustomPolicyDetailsPropertyStructProvides the CustomPolicyDetails, the rule owner ( AWS for managed rules, CUSTOM_POLICY for Custom Policy rules, and CUSTOM_LAMBDA for Custom Lambda rules), the rule identifier, and the events that cause the evaluation of your AWS resources.
CfnConfigRule.EvaluationModeConfigurationPropertyStructThe configuration object for AWS Config rule evaluation mode.
CfnConfigRule.ScopePropertyStructDefines which resources trigger an evaluation for an AWS Config rule.
CfnConfigRule.SourceDetailPropertyStructProvides the source and the message types that trigger AWS Config to evaluate your AWS resources against a rule.
CfnConfigRule.SourcePropertyStructProvides the CustomPolicyDetails, the rule owner ( AWS for managed rules, CUSTOM_POLICY for Custom Policy rules, and CUSTOM_LAMBDA for Custom Lambda rules), the rule identifier, and the events that cause the evaluation of your AWS resources.
CfnConfigRulePropsStructProperties for defining a CfnConfigRule.
CfnConfigurationAggregator.AccountAggregationSourcePropertyStructA collection of accounts and regions.
CfnConfigurationAggregator.OrganizationAggregationSourcePropertyStructThis object contains regions to set up the aggregator and an IAM role to retrieve organization details.
CfnConfigurationAggregatorPropsStructProperties for defining a CfnConfigurationAggregator.
CfnConfigurationRecorder.ExclusionByResourceTypesPropertyStructSpecifies whether the configuration recorder excludes certain resource types from being recorded.
CfnConfigurationRecorder.RecordingGroupPropertyStructSpecifies which resource types AWS Config records for configuration changes.
CfnConfigurationRecorder.RecordingModeOverridePropertyStructAn object for you to specify your overrides for the recording mode.
CfnConfigurationRecorder.RecordingModePropertyStructSpecifies the default recording frequency that AWS Config uses to record configuration changes.
CfnConfigurationRecorder.RecordingStrategyPropertyStructSpecifies the recording strategy of the configuration recorder.
CfnConfigurationRecorderPropsStructProperties for defining a CfnConfigurationRecorder.
CfnConformancePack.ConformancePackInputParameterPropertyStructInput parameters in the form of key-value pairs for the conformance pack, both of which you define.
CfnConformancePack.TemplateSSMDocumentDetailsPropertyStructThis API allows you to create a conformance pack template with an AWS Systems Manager document (SSM document).
CfnConformancePackPropsStructProperties for defining a CfnConformancePack.
CfnConnector.AzureConnectorConfigurationPropertyStructConfiguration for connecting to Microsoft Azure.
CfnConnector.ConnectorConfigurationPropertyStructThe configuration for the connector.
CfnConnectorPropsStructProperties for defining a CfnConnector.
CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesPropertyStructProvides options for how often AWS Config delivers configuration snapshots to the Amazon S3 bucket in your delivery channel.
CfnDeliveryChannelPropsStructProperties for defining a CfnDeliveryChannel.
CfnOrganizationConfigRule.OrganizationCustomPolicyRuleMetadataPropertyStructAn object that specifies metadata for your organization's AWS Config Custom Policy rule.
CfnOrganizationConfigRule.OrganizationCustomRuleMetadataPropertyStructAn object that specifies organization custom rule metadata such as resource type, resource ID of AWS resource, Lambda function ARN, and organization trigger types that trigger AWS Config to evaluate your AWS resources against a rule.
CfnOrganizationConfigRule.OrganizationManagedRuleMetadataPropertyStructAn object that specifies organization managed rule metadata such as resource type and ID of AWS resource along with the rule identifier.
CfnOrganizationConfigRulePropsStructProperties for defining a CfnOrganizationConfigRule.
CfnOrganizationConformancePack.ConformancePackInputParameterPropertyStructInput parameters in the form of key-value pairs for the conformance pack, both of which you define.
CfnOrganizationConformancePackPropsStructProperties for defining a CfnOrganizationConformancePack.
CfnRemediationConfiguration.ExecutionControlsPropertyStructAn ExecutionControls object.
CfnRemediationConfiguration.RemediationParameterValuePropertyStructThe value is either a dynamic (resource) value or a static value.
CfnRemediationConfiguration.ResourceValuePropertyStruct
CfnRemediationConfiguration.SsmControlsPropertyStructAWS Systems Manager (SSM) specific remediation controls.
CfnRemediationConfiguration.StaticValuePropertyStruct
CfnRemediationConfigurationPropsStructProperties for defining a CfnRemediationConfiguration.
CfnStoredQueryPropsStructProperties for defining a CfnStoredQuery.
CloudFormationStackDriftDetectionCheckPropsStructConstruction properties for a CloudFormationStackDriftDetectionCheck.
CloudFormationStackNotificationCheckPropsStructConstruction properties for a CloudFormationStackNotificationCheck.
CustomPolicyPropsStructConstruction properties for a CustomPolicy.
CustomRulePropsStructConstruction properties for a CustomRule.
EvaluationModeClassThe mode of evaluation for the rule.
IRuleInterfaceInterface representing an AWS Config rule.
ManagedRuleIdentifiersClassManaged rules that are supported by AWS Config.
ManagedRulePropsStructConstruction properties for a ManagedRule.
MaximumExecutionFrequencyEnumThe maximum frequency at which the AWS Config rule runs evaluations.
ResourceTypeClassResources types that are supported by AWS Config.
RulePropsStructConstruction properties for a new rule.
RuleScopeClassDetermines which resources trigger an evaluation of an AWS Config rule.