Skip to content

Instantly share code, notes, and snippets.

@adieuadieu
Last active May 27, 2024 19:07
Show Gist options
  • Save adieuadieu/d5c21d1b73917a92b911592512d299de to your computer and use it in GitHub Desktop.
Save adieuadieu/d5c21d1b73917a92b911592512d299de to your computer and use it in GitHub Desktop.
AWS OpenSearch Cluster with Serverless Framework
const aws4 = require('aws4')
const host = process.env.OPENSEARCH_ENDPOINT
module.exports.default = async function handler(
event,
context,
) {
const fetch = (await import('node-fetch')).default
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,
)
if (result.status === 404) {
return {
statusCode: 404,
body: JSON.stringify({ message: `Index "${indexName}" does not exist.`})
}
}
const body = await result.text()
return { statusCode: 200, body }
}
service: opensearch-howto
provider:
name: aws
runtime: nodejs14.x
functions:
example:
description: An OpenSearch example
handler: handler.default
memorySize: 256
events:
- http: GET /example
environment:
OPENSEARCH_ENDPOINT: !GetAtt OpenSearchDomain.DomainEndpoint
role: LambdaOpenSearchAccessRole
resources:
Resources:
LambdaOpenSearchAccessRole:
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-opensearchservice-domain.html
OpenSearchDomain:
Type: AWS::OpenSearchService::Domain
Properties:
DomainName: 'example'
EngineVersion: 'OpenSearch_1.0'
ClusterConfig:
# DedicatedMasterEnabled: true
InstanceCount: '1'
# ZoneAwarenessEnabled: true
InstanceType: 't3.small.search'
# DedicatedMasterType: 't3.small.search'
# DedicatedMasterCount: '1'
EBSOptions:
EBSEnabled: true
VolumeSize: '20'
VolumeType: 'gp2'
AccessPolicies:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
AWS: !GetAtt LambdaOpenSearchAccessRole.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