Skip to content

Commit

Permalink
Add withPassword(String) method to secure Elasticsearch
Browse files Browse the repository at this point in the history
Instead of providing env settings manually, we can simplify the usage of Elasticsearch in the context of TestContainers by just asking a password.
Behind the scene, we do provide the needed env settings.
  • Loading branch information
dadoonet committed Feb 3, 2020
1 parent 991057c commit d987545
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
5 changes: 2 additions & 3 deletions docs/modules/elasticsearch.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,11 @@ or set `client.transport.ignore_cluster_name` to `true`.
## Secure your Elasticsearch cluster

The default distribution of Elasticsearch comes with the basic license which contains security feature.
You can turn on security by providing some extra environment settings:
You can turn on security by providing a password:

```java
ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:7.5.2")
.withEnv("ELASTIC_PASSWORD", "changeme")
.withEnv("xpack.security.enabled", "true");
.withPassword("changeme");
```

In which case you can create the Client like this:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ public ElasticsearchContainer(String dockerImageName) {
.withStartupTimeout(Duration.ofMinutes(2)));
}

public ElasticsearchContainer withPassword(String password) {
withEnv("ELASTIC_PASSWORD", password);
withEnv("xpack.security.enabled", "true");
return this;
}

public String getHttpHostAddress() {
return getContainerIpAddress() + ":" + getMappedPort(ELASTICSEARCH_DEFAULT_PORT);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,7 @@ public void elasticsearchDefaultTest() throws IOException {

@Test
public void elasticsearchSecuredTest() throws IOException {
try (ElasticsearchContainer container = new ElasticsearchContainer()
.withEnv("ELASTIC_PASSWORD", ELASTICSEARCH_PASSWORD)
.withEnv("xpack.security.enabled", "true")
) {
try (ElasticsearchContainer container = new ElasticsearchContainer().withPassword(ELASTICSEARCH_PASSWORD)) {
container.start();

// The cluster should be secured so it must fail when we try to access / without credentials
Expand Down

0 comments on commit d987545

Please sign in to comment.