AWSCDK::Elasticsearch

17 types

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:

dev_domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
})

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

dev_domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_10,
    enable_version_upgrade: true,
})

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

prod_domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
    capacity: {
        master_nodes: 5,
        data_nodes: 20,
    },
    ebs: {
        volume_size: 20,
    },
    zone_awareness: {
        availability_zone_count: 3,
    },
    logging: {
        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 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:

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:

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:

slr = AWSCDK::IAM::CfnServiceLinkedRole.new(self, "ElasticSLR", {
    aws_service_name: "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:

domain_endpoint = "https://my-domain-jcjotrt6f7otem4sqcwbch3c4u.us-east-1.es.amazonaws.com"
domain = AWSCDK::Elasticsearch::Domain.from_domain_endpoint(self, "ImportedDomain", domain_endpoint)

Permissions

IAM

Helper methods also exist for managing access to the domain.

fn = nil # AWSCDK::Lambda::Function
domain = nil # AWSCDK::Elasticsearch::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)

Encryption

The domain can also be created with encryption enabled:

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_4,
    ebs: {
        volume_size: 100,
        volume_type: AWSCDK::EC2::EbsDeviceVolumeType::GENERAL_PURPOSE_SSD,
    },
    node_to_node_encryption: true,
    encryption_at_rest: {
        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 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.

vpc = AWSCDK::EC2::VPC.new(self, "Vpc")
domain_props = {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
    removal_policy: AWSCDK::RemovalPolicy::DESTROY,
    vpc: vpc,
    # must be enabled since our VPC contains multiple private subnets.
    zone_awareness: {
        enabled: true,
    },
    capacity: {
        # must be an even number since the default az count is 2.
        data_nodes: 2,
    },
}
AWSCDK::Elasticsearch::Domain.new(self, "Domain", domain_props)

In addition, you can use the vpc_subnets property to control which specific subnets will be used, and the security_groups 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:

domain = nil # AWSCDK::Elasticsearch::Domain

free_storage_space = domain.metric_free_storage_space
master_sys_memory_utilization = domain.metric("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.

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
    enforce_https: true,
    node_to_node_encryption: true,
    encryption_at_rest: {
        enabled: true,
    },
    fine_grained_access_control: {
        master_user_name: "master-user",
    },
})

master_user_password = domain.master_user_password

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.

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
    use_unsigned_basic_auth: true,
})

master_user_password = domain.master_user_password

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 access_policies constructor may be sufficient:

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
    access_policies: [
        AWSCDK::IAM::PolicyStatement.new({
            actions: ["es:*ESHttpPost", "es:ESHttpPut*"],
            effect: AWSCDK::IAM::Effect::ALLOW,
            principals: [AWSCDK::IAM::AccountPrincipal.new("123456789012")],
            resources: ["*"],
        }),
    ],
})

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

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
})

domain.add_access_policies(
AWSCDK::IAM::PolicyStatement.new({
    actions: ["es:ESHttpPost", "es:ESHttpPut"],
    effect: AWSCDK::IAM::Effect::ALLOW,
    principals: [AWSCDK::IAM::AccountPrincipal.new("123456789012")],
    resources: [domain.domain_arn, "#{domain.domain_arn}/*"],
}),
AWSCDK::IAM::PolicyStatement.new({
    actions: ["es:ESHttpGet"],
    effect: AWSCDK::IAM::Effect::ALLOW,
    principals: [AWSCDK::IAM::AccountPrincipal.new("123456789012")],
    resources: [
        "#{domain.domain_arn}/_all/_settings",
        "#{domain.domain_arn}/_cluster/stats",
        "#{domain.domain_arn}/index-name*/_mapping/type-name",
        "#{domain.domain_arn}/roletest*/_mapping/roletest",
        "#{domain.domain_arn}/_nodes",
        "#{domain.domain_arn}/_nodes/stats",
        "#{domain.domain_arn}/_nodes/*/stats",
        "#{domain.domain_arn}/_stats",
        "#{domain.domain_arn}/index-name*/_stats",
        "#{domain.domain_arn}/roletest*/_stat",
    ],
}))

Audit logs

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

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1,
    enforce_https: true,
    node_to_node_encryption: true,
    encryption_at_rest: {
        enabled: true,
    },
    fine_grained_access_control: {
        master_user_name: "master-user",
    },
    logging: {
        audit_log_enabled: true,
        slow_search_log_enabled: true,
        app_log_enabled: true,
        slow_index_log_enabled: true,
    },
})

UltraWarm

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

domain = AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_10,
    capacity: {
        master_nodes: 2,
        warm_nodes: 2,
        warm_instance_type: "ultrawarm1.medium.elasticsearch",
    },
})

Custom endpoint

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

AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::ElasticsearchVersion.V7_7,
    custom_endpoint: {
        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 endpoint

Advanced options

Advanced cluster settings can used to configure additional options.

AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
    version: AWSCDK::Elasticsearch::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 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.

  require 'aws-cdk-lib'

...becomes...

  require 'aws-cdk-lib'
  version = AWSCDK::Elasticsearch::ElasticsearchVersion.V7_1

...becomes...

  version = AWSCDK::OpenSearchService::EngineVersion.ELASTICSEARCH_7_1
  AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
      cognito_kibana_auth: {
          identity_pool_id: "test-identity-pool-id",
          user_pool_id: "test-user-pool-id",
          role: role,
      },
      version: elasticsearch_version,
  })

...becomes...

  AWSCDK::OpenSearchService::Domain.new(self, "Domain", {
      cognito_dashboards_auth: {
          identity_pool_id: "test-identity-pool-id",
          user_pool_id: "test-user-pool-id",
          role: role,
      },
      version: open_search_version,
  })
  AWSCDK::Elasticsearch::Domain.new(self, "Domain", {
      capacity: {
          master_node_instance_type: "r5.large.elasticsearch",
      },
      version: elasticsearch_version,
  })

...becomes...

  AWSCDK::OpenSearchService::Domain.new(self, "Domain", {
      capacity: {
          master_node_instance_type: "r5.large.search",
      },
      version: open_search_version,
  })

CloudFormation Migration

Follow these steps to migrate your application without data loss:

API Reference

Classes 4

CfnDomainThe AWS::Elasticsearch::Domain resource creates an Amazon OpenSearch Service domain. DomainProvides an Elasticsearch domain. DomainGrantsCollection of grant methods for a IDomainRef. ElasticsearchVersionElasticsearch version.

Interfaces 12

AdvancedSecurityOptionsSpecifies options for fine-grained access control. CapacityConfigConfigures the capacity of the cluster such as the instance type and the number of instanc CfnDomainPropsProperties for defining a `CfnDomain`. CognitoOptionsConfigures Amazon ES to use Amazon Cognito authentication for Kibana. CustomEndpointOptionsConfigures a custom domain endpoint for the ES domain. DomainAttributesReference to an Elasticsearch domain. DomainPropsProperties for an AWS Elasticsearch Domain. EbsOptionsThe configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are attached to EncryptionAtRestOptionsWhether the domain should encrypt data at rest, and if so, the AWS Key Management Service IDomainAn interface that represents an Elasticsearch domain - either created with the CDK, or an LoggingOptionsConfigures log settings for the domain. ZoneAwarenessConfigSpecifies zone awareness configuration options.

Enums 1

TLSSecurityPolicyThe minimum TLS version required for traffic to the domain.