Skip to content

Instantly share code, notes, and snippets.

@adieuadieu
Last active September 6, 2023 21:57
Show Gist options
  • Save adieuadieu/da632b93cd6a214fdbe3ac0f739c622b to your computer and use it in GitHub Desktop.
Save adieuadieu/da632b93cd6a214fdbe3ac0f739c622b to your computer and use it in GitHub Desktop.
AWS Elasticsearch Cluster with Serverless Framework
const aws4 = require('aws4')
const fetch = require('node-fetch')
const host = process.env.ELASTICSEARCH_ENDPOINT
module.exports.default = async function handler(event, context) {
const indexName = 'example'
const options = aws4.sign({
host,
path: '/' + indexName,
method: 'HEAD',
headers: { 'Content-Type': 'application/json' },
})
const result = await fetch(`https://${host}/${indexName}`, options)
const body = await result.text()
return { statusCode: 200, body }
}
service: elasticsearch-howto
provider:
name: aws
runtime: nodejs14.x
functions:
example:
description: An Elasticsearch example
handler: handler.default
memorySize: 256
events:
- http: GET /example
environment:
ELASTICSEARCH_ENDPOINT: !GetAtt ElasticsearchDomain.DomainEndpoint
role: LambdaElasticSearchAccessRole
resources:
Resources:
LambdaElasticSearchAccessRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# Policies:
# - PolicyName: ssm
# PolicyDocument:
# Statement:
# - Effect: Allow
# Action:
# - ssm:GetParametersByPath
# Resource:
# - arn:aws:ssm:*:*:parameter/${self:service}/*
# Documentation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html
ElasticsearchDomain:
Type: AWS::Elasticsearch::Domain
Properties:
DomainName: 'example'
ElasticsearchVersion: '7.10'
ElasticsearchClusterConfig:
# DedicatedMasterEnabled: true
InstanceCount: '1'
# ZoneAwarenessEnabled: true
InstanceType: 't3.small.elasticsearch'
# DedicatedMasterType: 't3.small.elasticsearch'
# DedicatedMasterCount: '1'
EBSOptions:
EBSEnabled: true
VolumeSize: '20'
VolumeType: 'gp2'
AccessPolicies:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
AWS: !GetAtt LambdaElasticSearchAccessRole.Arn
Action: 'es:ESHttp*'
Resource:
- !Sub 'arn:aws:es:${AWS::Region}:${AWS::AccountId}:domain/example/*' # "example" should be the same as your value for DomainName above
AdvancedOptions:
rest.action.multi.allow_explicit_index: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment