Skip to content

Instantly share code, notes, and snippets.

@mbklein
Last active March 16, 2019 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbklein/1b8c7e5d5ca935f2f7969090ab17bf2e to your computer and use it in GitHub Desktop.
Save mbklein/1b8c7e5d5ca935f2f7969090ab17bf2e to your computer and use it in GitHub Desktop.
AWS ElasticSearch Snapshots
class ElasticSnapshot
attr_accessor :host, :repository, :region
def initialize(host:, repository:, region: 'us-east-1')
@host = host
@repository = repository
@region = region
end
def list_repositories
execute(:Get, '_all')
end
def create_repository(bucket:, role_arn:)
document = {
type: 's3',
settings: {
bucket: bucket,
region: region,
role_arn: role_arn
}
}
execute(:Put, repository, document)
end
def delete_repository
execute(:Delete, repository)
end
def list_snapshots
execute(:Get, "#{repository}/_all")
end
def take_snapshot(name:)
execute(:Put, "#{repository}/#{name}")
end
def restore_snapshot(name:, indices: '*')
document = { indices: indices }
execute(:Post, "#{repository}/#{name}/_restore", document)
end
def delete_snapshot(name:)
execute(:Delete, "#{repository}/#{name}")
end
def make_request(method, uri, body, signature)
Net::HTTP.const_get(method).new(uri).tap do |request|
request.body = body
request['Host'] = signature.headers['host']
request['X-Amz-Date'] = signature.headers['x-amz-date']
request['X-Amz-Security-Token'] = signature.headers['x-amz-security-token']
request['X-Amz-Content-Sha256']= signature.headers['x-amz-content-sha256']
request['Authorization'] = signature.headers['authorization']
request['Content-Type'] = 'application/json'
end
end
def send(method, uri, document)
body = document.to_json
service = 'es'
credentials = Aws::InstanceProfileCredentials.new
signer = Aws::Sigv4::Signer.new(service: service, region: region, credentials_provider: credentials)
signature = signer.sign_request(
http_method: method.to_s.upcase,
url: uri.to_s,
body: body
)
warn "#{method.to_s.upcase} #{uri.to_s} [Content-Length: #{body.length}]"
Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
http.request make_request(method, uri, body, signature)
end
end
def execute(method, path, document = {})
uri = URI("https://#{host}/_snapshot/#{path}")
send(method, uri, document)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment