Skip to content
v2.274.0

Amazon OpenSearch Service Construct Library ​

Instead of this module, we recommend using the aws-cdk-lib/aws-opensearchservice module. See Amazon OpenSearch Service FAQs for details. See Migrating to OpenSearch for migration instructions.

Quick start ​

Create a development cluster by simply specifying the version:

ts
const devDomain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
});
python
dev_domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1
)
java
Domain devDomain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .build();
csharp
var devDomain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1
});
go
devDomain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
})

To perform version upgrades without replacing the entire domain, specify the enableVersionUpgrade property.

ts
const devDomain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_10,
  enableVersionUpgrade: true, // defaults to false
});
python
dev_domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_10,
    enable_version_upgrade=True
)
java
Domain devDomain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_10)
        .enableVersionUpgrade(true)
        .build();
csharp
var devDomain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_10,
    EnableVersionUpgrade = true
});
go
devDomain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_10(),
	EnableVersionUpgrade: jsii.Boolean(true),
})

Create a production grade cluster by also specifying things like capacity and az distribution

ts
const prodDomain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
  capacity: {
    masterNodes: 5,
    dataNodes: 20,
  },
  ebs: {
    volumeSize: 20,
  },
  zoneAwareness: {
    availabilityZoneCount: 3,
  },
  logging: {
    slowSearchLogEnabled: true,
    appLogEnabled: true,
    slowIndexLogEnabled: true,
  },
});
python
prod_domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1,
    capacity=es.CapacityConfig(
        master_nodes=5,
        data_nodes=20
    ),
    ebs=es.EbsOptions(
        volume_size=20
    ),
    zone_awareness=es.ZoneAwarenessConfig(
        availability_zone_count=3
    ),
    logging=es.LoggingOptions(
        slow_search_log_enabled=True,
        app_log_enabled=True,
        slow_index_log_enabled=True
    )
)
java
Domain prodDomain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .capacity(CapacityConfig.builder()
                .masterNodes(5)
                .dataNodes(20)
                .build())
        .ebs(EbsOptions.builder()
                .volumeSize(20)
                .build())
        .zoneAwareness(ZoneAwarenessConfig.builder()
                .availabilityZoneCount(3)
                .build())
        .logging(LoggingOptions.builder()
                .slowSearchLogEnabled(true)
                .appLogEnabled(true)
                .slowIndexLogEnabled(true)
                .build())
        .build();
csharp
var prodDomain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1,
    Capacity = new CapacityConfig {
        MasterNodes = 5,
        DataNodes = 20
    },
    Ebs = new EbsOptions {
        VolumeSize = 20
    },
    ZoneAwareness = new ZoneAwarenessConfig {
        AvailabilityZoneCount = 3
    },
    Logging = new LoggingOptions {
        SlowSearchLogEnabled = true,
        AppLogEnabled = true,
        SlowIndexLogEnabled = true
    }
});
go
prodDomain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
	Capacity: &CapacityConfig{
		MasterNodes: jsii.Number(5),
		DataNodes: jsii.Number(20),
	},
	Ebs: &EbsOptions{
		VolumeSize: jsii.Number(20),
	},
	ZoneAwareness: &ZoneAwarenessConfig{
		AvailabilityZoneCount: jsii.Number(3),
	},
	Logging: &LoggingOptions{
		SlowSearchLogEnabled: jsii.Boolean(true),
		AppLogEnabled: jsii.Boolean(true),
		SlowIndexLogEnabled: jsii.Boolean(true),
	},
})

This creates an Elasticsearch cluster and automatically sets up log groups for logging the domain logs and slow search logs.

A note about SLR ​

Some cluster configurations (e.g VPC access) require the existence of the AWSServiceRoleForAmazonElasticsearchService service-linked role.

When performing such operations via the AWS Console, this SLR is created automatically when needed. However, this is not the behavior when using CloudFormation. If an SLR is needed, but doesn't exist, you will encounter a failure message similar to:

console
Before you can proceed, you must enable a service-linked role to give Amazon ES...

To resolve this, you need to create the SLR. We recommend using the AWS CLI:

console
aws iam create-service-linked-role --aws-service-name es.amazonaws.com

You can also create it using the CDK, but note that only the first application deploying this will succeed:

ts
const slr = new iam.CfnServiceLinkedRole(this, 'ElasticSLR', {
  awsServiceName: 'es.amazonaws.com',
});
python
slr = iam.CfnServiceLinkedRole(self, "ElasticSLR",
    aws_service_name="es.amazonaws.com"
)
java
CfnServiceLinkedRole slr = CfnServiceLinkedRole.Builder.create(this, "ElasticSLR")
        .awsServiceName("es.amazonaws.com")
        .build();
csharp
var slr = new CfnServiceLinkedRole(this, "ElasticSLR", new CfnServiceLinkedRoleProps {
    AwsServiceName = "es.amazonaws.com"
});
go
slr := iam.NewCfnServiceLinkedRole(this, jsii.String("ElasticSLR"), &CfnServiceLinkedRoleProps{
	AwsServiceName: jsii.String("es.amazonaws.com"),
})

Importing existing domains ​

To import an existing domain into your CDK application, use the Domain.fromDomainEndpoint factory method. This method accepts a domain endpoint of an already existing domain:

ts
const domainEndpoint = 'https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com';
const domain = es.Domain.fromDomainEndpoint(this, 'ImportedDomain', domainEndpoint);
python
domain_endpoint = "https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com"
domain = es.Domain.from_domain_endpoint(self, "ImportedDomain", domain_endpoint)
java
String domainEndpoint = "https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com";
IDomain domain = Domain.fromDomainEndpoint(this, "ImportedDomain", domainEndpoint);
csharp
var domainEndpoint = "https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com";
var domain = Domain.FromDomainEndpoint(this, "ImportedDomain", domainEndpoint);
go
domainEndpoint := "https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com"
domain := es.Domain_FromDomainEndpoint(this, jsii.String("ImportedDomain"), domainEndpoint)

Permissions ​

IAM ​

Helper methods also exist for managing access to the domain.

ts
declare const fn: lambda.Function;
declare const domain: es.Domain;

// Grant write access to the app-search index
domain.grantIndexWrite('app-search', fn);

// Grant read access to the 'app-search/_search' path
domain.grantPathRead('app-search/_search', fn);
python
# fn: lambda.Function
# domain: es.Domain


# Grant write access to the app-search index
domain.grant_index_write("app-search", fn)

# Grant read access to the 'app-search/_search' path
domain.grant_path_read("app-search/_search", fn)
java
Function fn;
Domain domain;


// Grant write access to the app-search index
domain.grantIndexWrite("app-search", fn);

// Grant read access to the 'app-search/_search' path
domain.grantPathRead("app-search/_search", fn);
csharp
Function fn;
Domain domain;


// Grant write access to the app-search index
domain.GrantIndexWrite("app-search", fn);

// Grant read access to the 'app-search/_search' path
domain.GrantPathRead("app-search/_search", fn);
go
var fn Function
var domain Domain


// Grant write access to the app-search index
domain.grantIndexWrite(jsii.String("app-search"), fn)

// Grant read access to the 'app-search/_search' path
domain.grantPathRead(jsii.String("app-search/_search"), fn)

Encryption ​

The domain can also be created with encryption enabled:

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_4,
  ebs: {
    volumeSize: 100,
    volumeType: ec2.EbsDeviceVolumeType.GENERAL_PURPOSE_SSD,
  },
  nodeToNodeEncryption: true,
  encryptionAtRest: {
    enabled: true,
  },
});
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_4,
    ebs=es.EbsOptions(
        volume_size=100,
        volume_type=ec2.EbsDeviceVolumeType.GENERAL_PURPOSE_SSD
    ),
    node_to_node_encryption=True,
    encryption_at_rest=es.EncryptionAtRestOptions(
        enabled=True
    )
)
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_4)
        .ebs(EbsOptions.builder()
                .volumeSize(100)
                .volumeType(EbsDeviceVolumeType.GENERAL_PURPOSE_SSD)
                .build())
        .nodeToNodeEncryption(true)
        .encryptionAtRest(EncryptionAtRestOptions.builder()
                .enabled(true)
                .build())
        .build();
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_4,
    Ebs = new EbsOptions {
        VolumeSize = 100,
        VolumeType = EbsDeviceVolumeType.GENERAL_PURPOSE_SSD
    },
    NodeToNodeEncryption = true,
    EncryptionAtRest = new EncryptionAtRestOptions {
        Enabled = true
    }
});
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_4(),
	Ebs: &EbsOptions{
		VolumeSize: jsii.Number(100),
		VolumeType: ec2.EbsDeviceVolumeType_GENERAL_PURPOSE_SSD,
	},
	NodeToNodeEncryption: jsii.Boolean(true),
	EncryptionAtRest: &EncryptionAtRestOptions{
		Enabled: jsii.Boolean(true),
	},
})

This sets up the domain with node to node encryption and encryption at rest. You can also choose to supply your own KMS key to use for encryption at rest.

VPC Support ​

Elasticsearch domains can be placed inside a VPC, providing a secure communication between Amazon ES and other services within the VPC without the need for an internet gateway, NAT device, or VPN connection.

See Launching your Amazon OpenSearch Service domains within a VPC for more details.

ts
const vpc = new ec2.Vpc(this, 'Vpc');
const domainProps: es.DomainProps = {
  version: es.ElasticsearchVersion.V7_1,
  removalPolicy: RemovalPolicy.DESTROY,
  vpc,
  // must be enabled since our VPC contains multiple private subnets.
  zoneAwareness: {
    enabled: true,
  },
  capacity: {
    // must be an even number since the default az count is 2.
    dataNodes: 2,
  },
};
new es.Domain(this, 'Domain', domainProps);
python
vpc = ec2.Vpc(self, "Vpc")
domain_props = es.DomainProps(
    version=es.ElasticsearchVersion.V7_1,
    removal_policy=RemovalPolicy.DESTROY,
    vpc=vpc,
    # must be enabled since our VPC contains multiple private subnets.
    zone_awareness=es.ZoneAwarenessConfig(
        enabled=True
    ),
    capacity=es.CapacityConfig(
        # must be an even number since the default az count is 2.
        data_nodes=2
    )
)
es.Domain(self, "Domain", domain_props)
java
Vpc vpc = new Vpc(this, "Vpc");
DomainProps domainProps = DomainProps.builder()
        .version(ElasticsearchVersion.V7_1)
        .removalPolicy(RemovalPolicy.DESTROY)
        .vpc(vpc)
        // must be enabled since our VPC contains multiple private subnets.
        .zoneAwareness(ZoneAwarenessConfig.builder()
                .enabled(true)
                .build())
        .capacity(CapacityConfig.builder()
                // must be an even number since the default az count is 2.
                .dataNodes(2)
                .build())
        .build();
new Domain(this, "Domain", domainProps);
csharp
var vpc = new Vpc(this, "Vpc");
var domainProps = new DomainProps {
    Version = ElasticsearchVersion.V7_1,
    RemovalPolicy = RemovalPolicy.DESTROY,
    Vpc = vpc,
    // must be enabled since our VPC contains multiple private subnets.
    ZoneAwareness = new ZoneAwarenessConfig {
        Enabled = true
    },
    Capacity = new CapacityConfig {
        // must be an even number since the default az count is 2.
        DataNodes = 2
    }
};
new Domain(this, "Domain", domainProps);
go
vpc := ec2.NewVpc(this, jsii.String("Vpc"))
domainProps := &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
	RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
	Vpc: Vpc,
	// must be enabled since our VPC contains multiple private subnets.
	ZoneAwareness: &ZoneAwarenessConfig{
		Enabled: jsii.Boolean(true),
	},
	Capacity: &CapacityConfig{
		// must be an even number since the default az count is 2.
		DataNodes: jsii.Number(2),
	},
}
es.NewDomain(this, jsii.String("Domain"), domainProps)

In addition, you can use the vpcSubnets property to control which specific subnets will be used, and the securityGroups property to control which security groups will be attached to the domain. By default, CDK will select all private subnets in the VPC, and create one dedicated security group.

Metrics ​

Helper methods exist to access common domain metrics for example:

ts
declare const domain: es.Domain;
const freeStorageSpace = domain.metricFreeStorageSpace();
const masterSysMemoryUtilization = domain.metric('MasterSysMemoryUtilization');
python
# domain: es.Domain

free_storage_space = domain.metric_free_storage_space()
master_sys_memory_utilization = domain.metric("MasterSysMemoryUtilization")
java
Domain domain;

Metric freeStorageSpace = domain.metricFreeStorageSpace();
Metric masterSysMemoryUtilization = domain.metric("MasterSysMemoryUtilization");
csharp
Domain domain;

var freeStorageSpace = domain.MetricFreeStorageSpace();
var masterSysMemoryUtilization = domain.Metric("MasterSysMemoryUtilization");
go
var domain Domain

freeStorageSpace := domain.metricFreeStorageSpace()
masterSysMemoryUtilization := domain.metric(jsii.String("MasterSysMemoryUtilization"))

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

Fine grained access control ​

The domain can also be created with a master user configured. The password can be supplied or dynamically created if not supplied.

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
  enforceHttps: true,
  nodeToNodeEncryption: true,
  encryptionAtRest: {
    enabled: true,
  },
  fineGrainedAccessControl: {
    masterUserName: 'master-user',
  },
});

const masterUserPassword = domain.masterUserPassword;
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1,
    enforce_https=True,
    node_to_node_encryption=True,
    encryption_at_rest=es.EncryptionAtRestOptions(
        enabled=True
    ),
    fine_grained_access_control=es.AdvancedSecurityOptions(
        master_user_name="master-user"
    )
)

master_user_password = domain.master_user_password
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .enforceHttps(true)
        .nodeToNodeEncryption(true)
        .encryptionAtRest(EncryptionAtRestOptions.builder()
                .enabled(true)
                .build())
        .fineGrainedAccessControl(AdvancedSecurityOptions.builder()
                .masterUserName("master-user")
                .build())
        .build();

SecretValue masterUserPassword = domain.getMasterUserPassword();
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1,
    EnforceHttps = true,
    NodeToNodeEncryption = true,
    EncryptionAtRest = new EncryptionAtRestOptions {
        Enabled = true
    },
    FineGrainedAccessControl = new AdvancedSecurityOptions {
        MasterUserName = "master-user"
    }
});

var masterUserPassword = domain.MasterUserPassword;
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
	EnforceHttps: jsii.Boolean(true),
	NodeToNodeEncryption: jsii.Boolean(true),
	EncryptionAtRest: &EncryptionAtRestOptions{
		Enabled: jsii.Boolean(true),
	},
	FineGrainedAccessControl: &AdvancedSecurityOptions{
		MasterUserName: jsii.String("master-user"),
	},
})

masterUserPassword := domain.MasterUserPassword

Using unsigned basic auth ​

For convenience, the domain can be configured to allow unsigned HTTP requests that use basic auth. Unless the domain is configured to be part of a VPC this means anyone can access the domain using the configured master username and password.

To enable unsigned basic auth access the domain is configured with an access policy that allows anonymous requests, HTTPS required, node to node encryption, encryption at rest and fine grained access control.

If the above settings are not set they will be configured as part of enabling unsigned basic auth. If they are set with conflicting values, an error will be thrown.

If no master user is configured a default master user is created with the username admin.

If no password is configured a default master user password is created and stored in the AWS Secrets Manager as secret. The secret has the prefix <domain id>MasterUser.

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
  useUnsignedBasicAuth: true,
});

const masterUserPassword = domain.masterUserPassword;
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1,
    use_unsigned_basic_auth=True
)

master_user_password = domain.master_user_password
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .useUnsignedBasicAuth(true)
        .build();

SecretValue masterUserPassword = domain.getMasterUserPassword();
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1,
    UseUnsignedBasicAuth = true
});

var masterUserPassword = domain.MasterUserPassword;
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
	UseUnsignedBasicAuth: jsii.Boolean(true),
})

masterUserPassword := domain.MasterUserPassword

Custom access policies ​

If the domain requires custom access control it can be configured either as a constructor property, or later by means of a helper method.

For simple permissions the accessPolicies constructor may be sufficient:

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
  accessPolicies: [
    new iam.PolicyStatement({
      actions: ['es:*ESHttpPost', 'es:ESHttpPut*'],
      effect: iam.Effect.ALLOW,
      principals: [new iam.AccountPrincipal('123456789012')],
      resources: ['*'],
    }),
  ]
});
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1,
    access_policies=[
        iam.PolicyStatement(
            actions=["es:*ESHttpPost", "es:ESHttpPut*"],
            effect=iam.Effect.ALLOW,
            principals=[iam.AccountPrincipal("123456789012")],
            resources=["*"]
        )
    ]
)
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .accessPolicies(List.of(
            PolicyStatement.Builder.create()
                    .actions(List.of("es:*ESHttpPost", "es:ESHttpPut*"))
                    .effect(Effect.ALLOW)
                    .principals(List.of(new AccountPrincipal("123456789012")))
                    .resources(List.of("*"))
                    .build()))
        .build();
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1,
    AccessPolicies = new [] {
        new PolicyStatement(new PolicyStatementProps {
            Actions = new [] { "es:*ESHttpPost", "es:ESHttpPut*" },
            Effect = Effect.ALLOW,
            Principals = new [] { new AccountPrincipal("123456789012") },
            Resources = new [] { "*" }
        }) }
});
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
	AccessPolicies: []PolicyStatement{
		iam.NewPolicyStatement(&PolicyStatementProps{
			Actions: []*string{
				jsii.String("es:*ESHttpPost"),
				jsii.String("es:ESHttpPut*"),
			},
			Effect: iam.Effect_ALLOW,
			Principals: []IPrincipal{
				iam.NewAccountPrincipal(jsii.String("123456789012")),
			},
			Resources: []*string{
				jsii.String("*"),
			},
		}),
	},
})

For more complex use-cases, for example, to set the domain up to receive data from a cross-account Amazon Data Firehose the addAccessPolicies helper method allows for policies that include the explicit domain ARN.

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
});

domain.addAccessPolicies(
  new iam.PolicyStatement({
    actions: ['es:ESHttpPost', 'es:ESHttpPut'],
    effect: iam.Effect.ALLOW,
    principals: [new iam.AccountPrincipal('123456789012')],
    resources: [domain.domainArn, `${domain.domainArn}/*`],
  }),
  new iam.PolicyStatement({
    actions: ['es:ESHttpGet'],
    effect: iam.Effect.ALLOW,
    principals: [new iam.AccountPrincipal('123456789012')],
    resources: [
      `${domain.domainArn}/_all/_settings`,
      `${domain.domainArn}/_cluster/stats`,
      `${domain.domainArn}/index-name*/_mapping/type-name`,
      `${domain.domainArn}/roletest*/_mapping/roletest`,
      `${domain.domainArn}/_nodes`,
      `${domain.domainArn}/_nodes/stats`,
      `${domain.domainArn}/_nodes/*/stats`,
      `${domain.domainArn}/_stats`,
      `${domain.domainArn}/index-name*/_stats`,
      `${domain.domainArn}/roletest*/_stat`,
    ],
  }),
);
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1
)

domain.add_access_policies(
    iam.PolicyStatement(
        actions=["es:ESHttpPost", "es:ESHttpPut"],
        effect=iam.Effect.ALLOW,
        principals=[iam.AccountPrincipal("123456789012")],
        resources=[domain.domain_arn, f"{domain.domainArn}/*"]
    ),
    iam.PolicyStatement(
        actions=["es:ESHttpGet"],
        effect=iam.Effect.ALLOW,
        principals=[iam.AccountPrincipal("123456789012")],
        resources=[f"{domain.domainArn}/_all/_settings", f"{domain.domainArn}/_cluster/stats", f"{domain.domainArn}/index-name*/_mapping/type-name", f"{domain.domainArn}/roletest*/_mapping/roletest", f"{domain.domainArn}/_nodes", f"{domain.domainArn}/_nodes/stats", f"{domain.domainArn}/_nodes/*/stats", f"{domain.domainArn}/_stats", f"{domain.domainArn}/index-name*/_stats", f"{domain.domainArn}/roletest*/_stat"
        ]
    ))
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .build();

domain.addAccessPolicies(
PolicyStatement.Builder.create()
        .actions(List.of("es:ESHttpPost", "es:ESHttpPut"))
        .effect(Effect.ALLOW)
        .principals(List.of(new AccountPrincipal("123456789012")))
        .resources(List.of(domain.getDomainArn(), String.format("%s/*", domain.getDomainArn())))
        .build(),
PolicyStatement.Builder.create()
        .actions(List.of("es:ESHttpGet"))
        .effect(Effect.ALLOW)
        .principals(List.of(new AccountPrincipal("123456789012")))
        .resources(List.of(String.format("%s/_all/_settings", domain.getDomainArn()), String.format("%s/_cluster/stats", domain.getDomainArn()), String.format("%s/index-name*/_mapping/type-name", domain.getDomainArn()), String.format("%s/roletest*/_mapping/roletest", domain.getDomainArn()), String.format("%s/_nodes", domain.getDomainArn()), String.format("%s/_nodes/stats", domain.getDomainArn()), String.format("%s/_nodes/*/stats", domain.getDomainArn()), String.format("%s/_stats", domain.getDomainArn()), String.format("%s/index-name*/_stats", domain.getDomainArn()), String.format("%s/roletest*/_stat", domain.getDomainArn())))
        .build());
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1
});

domain.AddAccessPolicies(
new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "es:ESHttpPost", "es:ESHttpPut" },
    Effect = Effect.ALLOW,
    Principals = new [] { new AccountPrincipal("123456789012") },
    Resources = new [] { domain.DomainArn, $"{domain.domainArn}/*" }
}),
new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "es:ESHttpGet" },
    Effect = Effect.ALLOW,
    Principals = new [] { new AccountPrincipal("123456789012") },
    Resources = new [] { $"{domain.domainArn}/_all/_settings", $"{domain.domainArn}/_cluster/stats", $"{domain.domainArn}/index-name*/_mapping/type-name", $"{domain.domainArn}/roletest*/_mapping/roletest", $"{domain.domainArn}/_nodes", $"{domain.domainArn}/_nodes/stats", $"{domain.domainArn}/_nodes/*/stats", $"{domain.domainArn}/_stats", $"{domain.domainArn}/index-name*/_stats", $"{domain.domainArn}/roletest*/_stat" }
}));
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
})

domain.AddAccessPolicies(
iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("es:ESHttpPost"),
		jsii.String("es:ESHttpPut"),
	},
	Effect: iam.Effect_ALLOW,
	Principals: []IPrincipal{
		iam.NewAccountPrincipal(jsii.String("123456789012")),
	},
	Resources: []*string{
		domain.domainArn,
		fmt.Sprintf("%v/*", domain.domainArn),
	},
}),
iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("es:ESHttpGet"),
	},
	Effect: iam.Effect_ALLOW,
	Principals: []IPrincipal{
		iam.NewAccountPrincipal(jsii.String("123456789012")),
	},
	Resources: []*string{
		fmt.Sprintf("%v/_all/_settings", domain.domainArn),
		fmt.Sprintf("%v/_cluster/stats", domain.domainArn),
		fmt.Sprintf("%v/index-name*/_mapping/type-name", domain.domainArn),
		fmt.Sprintf("%v/roletest*/_mapping/roletest", domain.domainArn),
		fmt.Sprintf("%v/_nodes", domain.domainArn),
		fmt.Sprintf("%v/_nodes/stats", domain.domainArn),
		fmt.Sprintf("%v/_nodes/*/stats", domain.domainArn),
		fmt.Sprintf("%v/_stats", domain.domainArn),
		fmt.Sprintf("%v/index-name*/_stats", domain.domainArn),
		fmt.Sprintf("%v/roletest*/_stat", domain.domainArn),
	},
}))

Audit logs ​

Audit logs can be enabled for a domain, but only when fine-grained access control is enabled.

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_1,
  enforceHttps: true,
  nodeToNodeEncryption: true,
  encryptionAtRest: {
    enabled: true,
  },
  fineGrainedAccessControl: {
    masterUserName: 'master-user',
  },
  logging: {
    auditLogEnabled: true,
    slowSearchLogEnabled: true,
    appLogEnabled: true,
    slowIndexLogEnabled: true,
  },
});
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_1,
    enforce_https=True,
    node_to_node_encryption=True,
    encryption_at_rest=es.EncryptionAtRestOptions(
        enabled=True
    ),
    fine_grained_access_control=es.AdvancedSecurityOptions(
        master_user_name="master-user"
    ),
    logging=es.LoggingOptions(
        audit_log_enabled=True,
        slow_search_log_enabled=True,
        app_log_enabled=True,
        slow_index_log_enabled=True
    )
)
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_1)
        .enforceHttps(true)
        .nodeToNodeEncryption(true)
        .encryptionAtRest(EncryptionAtRestOptions.builder()
                .enabled(true)
                .build())
        .fineGrainedAccessControl(AdvancedSecurityOptions.builder()
                .masterUserName("master-user")
                .build())
        .logging(LoggingOptions.builder()
                .auditLogEnabled(true)
                .slowSearchLogEnabled(true)
                .appLogEnabled(true)
                .slowIndexLogEnabled(true)
                .build())
        .build();
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_1,
    EnforceHttps = true,
    NodeToNodeEncryption = true,
    EncryptionAtRest = new EncryptionAtRestOptions {
        Enabled = true
    },
    FineGrainedAccessControl = new AdvancedSecurityOptions {
        MasterUserName = "master-user"
    },
    Logging = new LoggingOptions {
        AuditLogEnabled = true,
        SlowSearchLogEnabled = true,
        AppLogEnabled = true,
        SlowIndexLogEnabled = true
    }
});
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_1(),
	EnforceHttps: jsii.Boolean(true),
	NodeToNodeEncryption: jsii.Boolean(true),
	EncryptionAtRest: &EncryptionAtRestOptions{
		Enabled: jsii.Boolean(true),
	},
	FineGrainedAccessControl: &AdvancedSecurityOptions{
		MasterUserName: jsii.String("master-user"),
	},
	Logging: &LoggingOptions{
		AuditLogEnabled: jsii.Boolean(true),
		SlowSearchLogEnabled: jsii.Boolean(true),
		AppLogEnabled: jsii.Boolean(true),
		SlowIndexLogEnabled: jsii.Boolean(true),
	},
})

UltraWarm ​

UltraWarm nodes can be enabled to provide a cost-effective way to store large amounts of read-only data.

ts
const domain = new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_10,
  capacity: {
    masterNodes: 2,
    warmNodes: 2,
    warmInstanceType: 'ultrawarm1.medium.elasticsearch',
  },
});
python
domain = es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_10,
    capacity=es.CapacityConfig(
        master_nodes=2,
        warm_nodes=2,
        warm_instance_type="ultrawarm1.medium.elasticsearch"
    )
)
java
Domain domain = Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_10)
        .capacity(CapacityConfig.builder()
                .masterNodes(2)
                .warmNodes(2)
                .warmInstanceType("ultrawarm1.medium.elasticsearch")
                .build())
        .build();
csharp
var domain = new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_10,
    Capacity = new CapacityConfig {
        MasterNodes = 2,
        WarmNodes = 2,
        WarmInstanceType = "ultrawarm1.medium.elasticsearch"
    }
});
go
domain := es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_10(),
	Capacity: &CapacityConfig{
		MasterNodes: jsii.Number(2),
		WarmNodes: jsii.Number(2),
		WarmInstanceType: jsii.String("ultrawarm1.medium.elasticsearch"),
	},
})

Custom endpoint ​

Custom endpoints can be configured to reach the ES domain under a custom domain name.

ts
new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_7,
  customEndpoint: {
    domainName: 'search.example.com',
  },
});
python
es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_7,
    custom_endpoint=es.CustomEndpointOptions(
        domain_name="search.example.com"
    )
)
java
Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_7)
        .customEndpoint(CustomEndpointOptions.builder()
                .domainName("search.example.com")
                .build())
        .build();
csharp
new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_7,
    CustomEndpoint = new CustomEndpointOptions {
        DomainName = "search.example.com"
    }
});
go
es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_7(),
	CustomEndpoint: &CustomEndpointOptions{
		DomainName: jsii.String("search.example.com"),
	},
})

It is also possible to specify a custom certificate instead of the auto-generated one.

Additionally, an automatic CNAME-Record is created if a hosted zone is provided for the custom endpoint

Advanced options ​

Advanced cluster settings can used to configure additional options.

ts
new es.Domain(this, 'Domain', {
  version: es.ElasticsearchVersion.V7_7,
  advancedOptions: {
    'rest.action.multi.allow_explicit_index': 'false',
    'indices.fielddata.cache.size': '25',
    'indices.query.bool.max_clause_count': '2048',
  },
});
python
es.Domain(self, "Domain",
    version=es.ElasticsearchVersion.V7_7,
    advanced_options={
        "rest.action.multi.allow_explicit_index": "false",
        "indices.fielddata.cache.size": "25",
        "indices.query.bool.max_clause_count": "2048"
    }
)
java
Domain.Builder.create(this, "Domain")
        .version(ElasticsearchVersion.V7_7)
        .advancedOptions(Map.of(
                "rest.action.multi.allow_explicit_index", "false",
                "indices.fielddata.cache.size", "25",
                "indices.query.bool.max_clause_count", "2048"))
        .build();
csharp
new Domain(this, "Domain", new DomainProps {
    Version = ElasticsearchVersion.V7_7,
    AdvancedOptions = new Dictionary<string, string> {
        { "rest.action.multi.allow_explicit_index", "false" },
        { "indices.fielddata.cache.size", "25" },
        { "indices.query.bool.max_clause_count", "2048" }
    }
});
go
es.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: es.ElasticsearchVersion_V7_7(),
	AdvancedOptions: map[string]*string{
		"rest.action.multi.allow_explicit_index": jsii.String("false"),
		"indices.fielddata.cache.size": jsii.String("25"),
		"indices.query.bool.max_clause_count": jsii.String("2048"),
	},
})

Migrating to OpenSearch ​

To migrate from this module (aws-cdk-lib/aws-elasticsearch) to the new aws-cdk-lib/aws-opensearchservice module, you must modify your CDK application to refer to the new module (including some associated changes) and then perform a CloudFormation resource deletion/import.

Necessary CDK Modifications ​

Make the following modifications to your CDK application to migrate to the aws-cdk-lib/aws-opensearchservice module.

  • Rewrite module imports to use 'aws-cdk-lib/aws-opensearchservice to 'aws-cdk-lib/aws-elasticsearch. For example:

    ts
    import * as es from 'aws-cdk-lib/aws-elasticsearch';
    import { Domain } from 'aws-cdk-lib/aws-elasticsearch';
    

    ...becomes...

    ts
    import * as opensearch from 'aws-cdk-lib/aws-opensearchservice';
    import { Domain } from 'aws-cdk-lib/aws-opensearchservice';
    
  • Replace instances of es.ElasticsearchVersion with opensearch.EngineVersion. For example:

    ts
    const version = es.ElasticsearchVersion.V7_1;
    

    ...becomes...

    ts
    const version = opensearch.EngineVersion.ELASTICSEARCH_7_1;
    
  • Replace the cognitoKibanaAuth property of DomainProps with cognitoDashboardsAuth. For example:

    ts
    new es.Domain(this, 'Domain', {
      cognitoKibanaAuth: {
        identityPoolId: 'test-identity-pool-id',
        userPoolId: 'test-user-pool-id',
        role: role,
      },
      version: elasticsearchVersion,
    });
    

    ...becomes...

    ts
    new opensearch.Domain(this, 'Domain', {
      cognitoDashboardsAuth: {
        identityPoolId: 'test-identity-pool-id',
        userPoolId: 'test-user-pool-id',
        role: role,
      },
      version: openSearchVersion,
    });
    
  • Rewrite instance type suffixes from .elasticsearch to .search. For example:

    ts
    new es.Domain(this, 'Domain', {
      capacity: {
        masterNodeInstanceType: 'r5.large.elasticsearch',
      },
      version: elasticsearchVersion,
    });
    

    ...becomes...

    ts
    new opensearch.Domain(this, 'Domain', {
      capacity: {
        masterNodeInstanceType: 'r5.large.search',
      },
      version: openSearchVersion,
    });
    
  • Any CfnInclude'd domains will need to be re-written in their original template in order to be successfully included as a opensearch.CfnDomain

CloudFormation Migration ​

Follow these steps to migrate your application without data loss:

  • Ensure that the removal policy on your domains are set to RemovalPolicy.RETAIN. This is the default for the domain construct, so nothing is required unless you have specifically set the removal policy to some other value.
  • Remove the domain resource from your CloudFormation stacks by manually modifying the synthesized templates used to create the CloudFormation stacks. This may also involve modifying or deleting dependent resources, such as the custom resources that CDK creates to manage the domain's access policy or any other resource you have connected to the domain. You will need to search for references to each domain's logical ID to determine which other resources refer to it and replace or delete those references. Do not remove resources that are dependencies of the domain or you will have to recreate or import them before importing the domain. After modification, deploy the stacks through the AWS Management Console or using the AWS CLI.
  • Migrate your CDK application to use the new aws-cdk-lib/aws-opensearchservice module by applying the necessary modifications listed above. Synthesize your application and obtain the resulting stack templates.
  • Copy just the definition of the domain from the "migrated" templates to the corresponding "stripped" templates that you deployed above. Import the orphaned domains into your CloudFormation stacks using these templates.
  • Synthesize and deploy your CDK application to reconfigure/recreate the modified dependent resources. The CloudFormation stacks should now contain the same resources as existed prior to migration.
  • Proceed with development as normal!

Types ​

NameKindSummary
DomainConstruct (L2)Provides an Elasticsearch domain.
CfnDomainConstruct (L1)The AWS::Elasticsearch::Domain resource creates an Amazon OpenSearch Service domain.
AdvancedSecurityOptionsStructSpecifies options for fine-grained access control.
CapacityConfigStructConfigures the capacity of the cluster such as the instance type and the number of instances.
CfnDomain.AdvancedSecurityOptionsInputPropertyStructSpecifies options for fine-grained access control.
CfnDomain.CognitoOptionsPropertyStructConfigures OpenSearch Service to use Amazon Cognito authentication for OpenSearch Dashboards.
CfnDomain.ColdStorageOptionsPropertyStructSpecifies options for cold storage. For more information, see Cold storage for Amazon Elasticsearch Service .
CfnDomain.DomainEndpointOptionsPropertyStructSpecifies additional options for the domain endpoint, such as whether to require HTTPS for all traffic or whether to use a custom endpoint rather than the default endpoint.
CfnDomain.EBSOptionsPropertyStructThe configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are attached to data nodes in the OpenSearch Service domain.
CfnDomain.ElasticsearchClusterConfigPropertyStructThe cluster configuration for the OpenSearch Service domain.
CfnDomain.EncryptionAtRestOptionsPropertyStructWhether the domain should encrypt data at rest, and if so, the AWS Key Management Service key to use.
CfnDomain.LogPublishingOptionPropertyStruct> The AWS::Elasticsearch::Domain resource is being replaced by the AWS::OpenSearchService::Domain resource. While the legacy Elasticsearch resource and options are still supported, we recommend modifying your existing Cloudformation templates to use the new OpenSearch Service resource, which supports both OpenSearch and Elasticsearch. For more information about the service rename, see New resource types in the Amazon OpenSearch Service Developer Guide .
CfnDomain.MasterUserOptionsPropertyStructSpecifies information about the master user. Required if you enabled the internal user database.
CfnDomain.NodeToNodeEncryptionOptionsPropertyStructSpecifies whether node-to-node encryption is enabled.
CfnDomain.SnapshotOptionsPropertyStruct> The AWS::Elasticsearch::Domain resource is being replaced by the AWS::OpenSearchService::Domain resource. While the legacy Elasticsearch resource and options are still supported, we recommend modifying your existing Cloudformation templates to use the new OpenSearch Service resource, which supports both OpenSearch and Elasticsearch. For more information about the service rename, see New resource types in the Amazon OpenSearch Service Developer Guide .
CfnDomain.VPCOptionsPropertyStructThe virtual private cloud (VPC) configuration for the OpenSearch Service domain.
CfnDomain.ZoneAwarenessConfigPropertyStructSpecifies zone awareness configuration options. Only use if ZoneAwarenessEnabled is true .
CfnDomainPropsStructProperties for defining a CfnDomain.
CognitoOptionsStructConfigures Amazon ES to use Amazon Cognito authentication for Kibana.
CustomEndpointOptionsStructConfigures a custom domain endpoint for the ES domain.
DomainAttributesStructReference to an Elasticsearch domain.
DomainGrantsFacadeCollection of grant methods for a IDomainRef.
DomainPropsStructProperties for an AWS Elasticsearch Domain.
EbsOptionsStructThe configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are attached to data nodes in the Amazon ES domain.
ElasticsearchVersionClassElasticsearch version.
EncryptionAtRestOptionsStructWhether the domain should encrypt data at rest, and if so, the AWS Key Management Service (KMS) key to use.
IDomainInterfaceAn interface that represents an Elasticsearch domain - either created with the CDK, or an existing one.
LoggingOptionsStructConfigures log settings for the domain.
TLSSecurityPolicyEnumThe minimum TLS version required for traffic to the domain.
ZoneAwarenessConfigStructSpecifies zone awareness configuration options.