如何使用 API 密钥和 python 库正确连接到 Elasticsearch 云?

mic*_*lbn 5 python elasticsearch

在弹性云(托管在 aws 上)下创建 API 密钥。

文档声明应附加正确的身份验证标头:

Authorization: ApiKey $EC_API_KEY
Run Code Online (Sandbox Code Playgroud)

使用curl它的工作原理:

curl -i -H "authorization: ApiKey LONG_KEY_STRING=="  https://12345.us-east-2.aws.elastic-cloud.com:9243/_health

HTTP/2 200 
x-cloud-request-id: 1234abc
content-type: text/plain; charset=utf-8
content-length: 34
date: Thu, 22 Oct 2020 12:36:54 GMT

{
  "ok": true,
  "status": 200
}

Run Code Online (Sandbox Code Playgroud)

但是下面的Python代码( elasticsearch-7.9.1)失败了:

Authorization: ApiKey $EC_API_KEY
Run Code Online (Sandbox Code Playgroud)

有错误:

{
    "errorMessage": "AuthenticationException(401, 'security_exception', 'missing authentication credentials for REST request [/_cluster/health]')",
    "stackTrace": [
        "  File \"/path/venv/lib64/python3.7/site-packages/lambda_local/main.py\", line 153, in execute\n    result = func(event, context._activate())\n",
        "  File \"main.py\", line 35, in handler\n    post_ping_doc(ping, msg[KEY_ID])\n",
        "  File \"main.py\", line 45, in post_ping_doc\n    print(es.cluster.health())\n",
        "  File \"/path/elasticsearch/client/utils.py\", line 152, in _wrapped\n    return func(*args, params=params, headers=headers, **kwargs)\n",
        "  File \"/path/elasticsearch/client/cluster.py\", line 69, in health\n    headers=headers,\n",
        "  File \"/path/elasticsearch/transport.py\", line 392, in perform_request\n    raise e\n",
        "  File \"/path/elasticsearch/transport.py\", line 365, in perform_request\n    timeout=timeout,\n",
        "  File \"/path/elasticsearch/connection/http_urllib3.py\", line 269, in perform_request\n    self._raise_error(response.status, raw_data)\n",
        "  File \"/path/elasticsearch/connection/base.py\", line 301, in _raise_error\n    status_code, error_message, additional_info\n"
    ],
    "errorType": "AuthenticationException"
}
Run Code Online (Sandbox Code Playgroud)

在浏览网络时尝试了其他变体,所有结果都相同。

启动本地ncat -l 1234并将请求重定向到它。请求似乎合法...

GET / HTTP/1.1
Host: 127.0.0.1:1234
Accept-Encoding: identity
connection: keep-alive
content-type: application/json
user-agent: elasticsearch-py/7.9.1 (Python 3.7.5)
authorization: ApiKey LONG_KEY_STRING==
Run Code Online (Sandbox Code Playgroud)

Python 代码确实可以在 docker 上使用本地不安全的 ES(不需要任何密钥)。

目前不知道,任何帮助都是值得赞赏的。

And*_*oll 0

根据文档,您不需要指定主机。我已经尝试过了,它对我有用。

es = Elasticsearch(api_key="LONG_KEY_STRING==")
print(es.cluster.health()) # should print a healthy status!
Run Code Online (Sandbox Code Playgroud)