Package: aws-cdk.aws-elasticsearch
Amazon OpenSearch Service Construct Library---This API may emit warnings. Backward compatibility is not guaranteed.Instead of this module, we recommend using the@aws-cdk/aws-opensearchservicemodule. SeeAmazon OpenSearch Service FAQsfor details. SeeMigrating to OpenSearchfor migration instructions.Quick startCreate a development cluster by simply specifying the version:dev_domain=es.Domain(self,"Domain",version=es.ElasticsearchVersion.V7_1)To perform version upgrades without replacing the entire domain, specify theenableVersionUpgradeproperty.dev_domain=es.Domain(self,"Domain",version=es.ElasticsearchVersion.V7_10,enable_version_upgrade=True)Create a production grade cluster by also specifying things like capacity and az distributionprod_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))This creates an Elasticsearch cluster and automatically sets up log groups for
logging the domain logs and slow search logs.A note about SLRSome cluster configurations (e.g VPC access) require the existence of theAWSServiceRoleForAmazonElasticsearchServiceservice-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 simlar to:Before you can proceed, you must enable a service-linked role to give Amazon ES...To resolve this, you need tocreatethe SLR. We recommend using the AWS CLI:aws iam create-service-linked-role --aws-service-name es.amazonaws.comYou can also create it using the CDK,but note that only the first application deploying this will succeed:slr=iam.CfnServiceLinkedRole(self,"ElasticSLR",aws_service_name="es.amazonaws.com")Importing existing domainsTo import an existing domain into your CDK application, use theDomain.fromDomainEndpointfactory method.
This method accepts a domain endpoint of an already existing domain:domain_endpoint="https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com"domain=es.Domain.from_domain_endpoint(self,"ImportedDomain",domain_endpoint)PermissionsIAMHelper methods also exist for managing access to the domain.# fn: lambda.Function# domain: es.Domain# Grant write access to the app-search indexdomain.grant_index_write("app-search",fn)# Grant read access to the 'app-search/_search' pathdomain.grant_path_read("app-search/_search",fn)EncryptionThe domain can also be created with encryption enabled: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))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 SupportElasticsearch 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.SeeLaunching your Amazon OpenSearch Service domains within a VPCfor more details.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)In addition, you can use thevpcSubnetsproperty to control which specific subnets will be used, and thesecurityGroupsproperty to control
which security groups will be attached to the domain. By default, CDK will select allprivatesubnets in the VPC, and create one dedicated security group.MetricsHelper methods exist to access common domain metrics for example:# domain: es.Domainfree_storage_space=domain.metric_free_storage_space()master_sys_memory_utilization=domain.metric("MasterSysMemoryUtilization")This module is part of theAWS Cloud Development Kitproject.Fine grained access controlThe domain can also be created with a master user configured. The password can
be supplied or dynamically created if not supplied.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_passwordUsing unsigned basic authFor 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 anyonmous 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
usernameadmin.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.domain=es.Domain(self,"Domain",version=es.ElasticsearchVersion.V7_1,use_unsigned_basic_auth=True)master_user_password=domain.master_user_passwordCustom access policiesIf 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 theaccessPoliciesconstructor may be sufficient: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=["*"])])For more complex use-cases, for example, to set the domain up to receive data from across-account Kinesis FirehosetheaddAccessPolicieshelper method
allows for policies that include the explicit domain ARN.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"]))Audit logsAudit logs can be enabled for a domain, but only when fine-grained access control is enabled.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))UltraWarmUltraWarm nodes can be enabled to provide a cost-effective way to store large amounts of read-only data.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"))Custom endpointCustom endpoints can be configured to reach the ES domain under a custom domain name.es.Domain(self,"Domain",version=es.ElasticsearchVersion.V7_7,custom_endpoint=es.CustomEndpointOptions(domain_name="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 endpointAdvanced optionsAdvanced cluster settingscan used to configure additional options.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"})Migrating to OpenSearchTo migrate from this module (@aws-cdk/aws-elasticsearch) to the new@aws-cdk/aws-opensearchservicemodule, 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 ModificationsMake the following modifications to your CDK application to migrate to the@aws-cdk/aws-opensearchservicemodule.Rewrite module imports to use'@aws-cdk/aws-opensearchserviceto'@aws-cdk/aws-elasticsearch.
For example:importaws_cdk.aws_elasticsearchasesfromaws_cdk.aws_elasticsearchimportDomain...becomes...importaws_cdk.aws_opensearchserviceasopensearchfromaws_cdk.aws_opensearchserviceimportDomainReplace instances ofes.ElasticsearchVersionwithopensearch.EngineVersion.
For example:version=es.ElasticsearchVersion.V7_1...becomes...version=opensearch.EngineVersion.ELASTICSEARCH_7_1Replace thecognitoKibanaAuthproperty ofDomainPropswithcognitoDashboardsAuth.
For example:es.Domain(self,"Domain",cognito_kibana_auth=es.CognitoOptions(identity_pool_id="test-identity-pool-id",user_pool_id="test-user-pool-id",role=role),version=elasticsearch_version)...becomes...opensearch.Domain(self,"Domain",cognito_dashboards_auth=opensearch.CognitoOptions(identity_pool_id="test-identity-pool-id",user_pool_id="test-user-pool-id",role=role),version=open_search_version)Rewrite instance type suffixes from.elasticsearchto.search.
For example:es.Domain(self,"Domain",capacity=es.CapacityConfig(master_node_instance_type="r5.large.elasticsearch"),version=elasticsearch_version)...becomes...opensearch.Domain(self,"Domain",capacity=opensearch.CapacityConfig(master_node_instance_type="r5.large.search"),version=open_search_version)AnyCfnInclude'd domains will need to be re-written in their original template in
order to be successfully included as aopensearch.CfnDomainCloudFormation MigrationFollow these steps to migrate your application without data loss:Ensure that theremoval policyon your domains are set toRemovalPolicy.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/aws-opensearchservicemodule 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.Importthe 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!