Connect to Elasticsearch over SSH tunnel

I want to create a code that connects to Elasticsearch through a SSH tunnel. To do that, I created an EC2 instance where I was able to ssh into it and install Elasticsearch. Then, I created RestHighLevelClient using this code to connect to it:

RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1", 9200));
        builder.setHttpClientConfigCallback(b -> b
                .setProxy(new HttpHost("EC2publicIP", 22, "https"))

        );

        RestHighLevelClient client =  new RestHighLevelClient(builder);
        GetBasicStatusResponse response = client.license().getBasicStatus(RequestOptions.DEFAULT);
        response.isEligibleToStartBasic(); 

However this code is failing and I feel like I am missing to add the public key to connect. Any help please

This is not how you typically connect to Elasticsearch so I would not expect the client to have any special provisions for configuring this. I do not know for sure though as >I am not familiar with this client.

If you can make it transparent to the client it might however work. I would therefore recommend securing your Elasticsearch properly and then make it available without needing to use a SSH tunnel.

I did create a tunnel and this is the code that I wrote, however it fails with a connection error ( ```
java.net.ConnectException: Connection refused

Session session = null;
String sshKeyFile = "/path/testSSH.pem";

    try {
        JSch jsc = new JSch();
        jsc.addIdentity(sshKeyFile);
        session = jsc.getSession("user", "ec2-instance", 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        int i = session.setPortForwardingL(30000, "localhost", 22, null);

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user_name", "pass"));

        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200));
        builder.setHttpClientConfigCallback(a -> a.setDefaultCredentialsProvider(credentialsProvider));
        RestHighLevelClient client = new RestHighLevelClient(builder);
        GetBasicStatusResponse response = client.license().getBasicStatus(RequestOptions.DEFAULT);
        response.isEligibleToStartBasic();
        System.out.println(response.toString());

    } catch (JSchException e) {
        e.printStackTrace();
    }

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.