diff --git a/README.md b/README.md index a406f394..1143785d 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ elasticsearch_exporter --help | es.client-cert | 1.0.2 | Path to PEM file that contains the corresponding cert for the private key to connect to Elasticsearch. | | | es.clusterinfo.interval | 1.1.0rc1 | Cluster info update interval for the cluster label | 5m | | es.ssl-skip-verify | 1.0.4rc1 | Skip SSL verification when connecting to Elasticsearch. | false | +| es.apiKey | unreleased | API Key to use for authenticating against Elasticsearch. | | | web.listen-address | 1.0.2 | Address to listen on for web interface and telemetry. | :9114 | | web.telemetry-path | 1.0.2 | Path under which to expose metrics. | /metrics | | version | 1.0.2 | Show version info on stdout and exit. | | diff --git a/main.go b/main.go index 878fa23e..97799688 100644 --- a/main.go +++ b/main.go @@ -14,6 +14,7 @@ package main import ( + "fmt" "net/http" "net/url" "os" @@ -31,6 +32,16 @@ import ( "gopkg.in/alecthomas/kingpin.v2" ) +type transportWithApiKey struct { + underlyingTransport http.RoundTripper + apiKey string +} + +func (t *transportWithApiKey) RoundTrip(req *http.Request) (*http.Response, error) { + req.Header.Add("Authorization", fmt.Sprintf("ApiKey %s", t.apiKey)) + return t.underlyingTransport.RoundTrip(req) +} + func main() { var ( Name = "elasticsearch_exporter" @@ -85,6 +96,9 @@ func main() { esInsecureSkipVerify = kingpin.Flag("es.ssl-skip-verify", "Skip SSL verification when connecting to Elasticsearch."). Default("false").Envar("ES_SSL_SKIP_VERIFY").Bool() + esApiKey = kingpin.Flag("es.apiKey", + "API Key to use for authenticating against Elasticsearch"). + Default("").Envar("ES_API_KEY").String() logLevel = kingpin.Flag("log.level", "Sets the loglevel. Valid levels are debug, info, warn, error"). Default("info").Envar("LOG_LEVEL").String() @@ -114,12 +128,25 @@ func main() { // returns nil if not provided and falls back to simple TCP. tlsConfig := createTLSConfig(*esCA, *esClientCert, *esClientPrivateKey, *esInsecureSkipVerify) + var httpTransport http.RoundTripper + + httpTransport = &http.Transport{ + TLSClientConfig: tlsConfig, + Proxy: http.ProxyFromEnvironment, + } + + if *esApiKey != "" { + apiKey := *esApiKey + + httpTransport = &transportWithApiKey{ + underlyingTransport: httpTransport, + apiKey: apiKey, + } + } + httpClient := &http.Client{ - Timeout: *esTimeout, - Transport: &http.Transport{ - TLSClientConfig: tlsConfig, - Proxy: http.ProxyFromEnvironment, - }, + Timeout: *esTimeout, + Transport: httpTransport, } // version metric