Elasticsearch API keys provide per-application credentials that can be restricted and rotated without sharing a user password. Limiting each automation workflow to a dedicated key reduces blast radius when credentials leak or access needs to be revoked.
API keys are created by calling the /_security/api_key endpoint with an optional role_descriptors block and an optional expiration. If role_descriptors is omitted, the API key inherits the creating principal’s effective privileges at creation time. The response includes an id, a secret api_key, and an encoded value (base64 of id:api_key) intended for the Authorization: ApiKey header.
API key creation requires security features to be enabled and a principal with manage_own_api_key, manage_api_key, or manage_security cluster privileges. The secret key material is returned only once at creation time, so the encoded value should be stored like a password and rotated when access requirements change. TLS-enabled clusters typically require https:// endpoints and a trusted CA configured for curl, and command examples assume a POSIX shell.
Steps to create an API key in Elasticsearch:
- Create an API key with scoped privileges.
$ curl --silent --show-error --fail --user elastic:password --cacert /etc/elasticsearch/certs/http_ca.crt --header "Content-Type: application/json" --request POST "https://localhost:9200/_security/api_key?pretty" --data '{ "name": "logs-writer", "expiration": "30d", "role_descriptors": { "logs_writer": { "cluster": ["monitor"], "index": [ { "names": ["logs-*"], "privileges": ["write", "create_index"] } ] } } }' { "id" : "INcfk5sB0mIpdsK-KNcM", "name" : "logs-writer", "expiration" : 1770291851303, "api_key" : "_88kAr5uS9SGLYRRp8tw3A", "encoded" : "SU5jZms1c0IwbUlwZHNLLUtOY006Xzg4a0FyNXVTOVNHTFlSUnA4dHczQQ==" }The encoded field is the value for the Authorization: ApiKey header. Use --user elastic to prompt for a password instead of placing it on the command line.
- Export the encoded value as an environment variable for test requests.
$ export ES_API_KEY="SU5jZms1c0IwbUlwZHNLLUtOY006Xzg4a0FyNXVTOVNHTFlSUnA4dHczQQ=="
Treat $ES_API_KEY as a password. The secret API key value cannot be retrieved again after creation.
- Verify the API key against the cluster health endpoint.
$ curl --silent --show-error --fail --cacert /etc/elasticsearch/certs/http_ca.crt --header "Authorization: ApiKey $ES_API_KEY" "https://localhost:9200/_cluster/health?pretty" { "cluster_name" : "search-cluster", "status" : "green", "timed_out" : false, "number_of_nodes" : 1, "active_primary_shards" : 1, ##### snipped ##### }A successful response confirms the key is accepted and that the assigned cluster privileges allow monitor calls.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
