I am trying to connect to opensearch which is deployed on aws EC2 instance. I’ve created an IAM roles and using that to access OS.
I am trying to make a connection to opensearch which is deployed on AWS. I’ve created an IAM role that is to be used for the authentication when i send any request to opensearch. When I try to execute any query through jestclient, i get an error unauthorized 401, don’t know where I am going wrong. Please look into it and let me know what can I do to fix it. Also let me know if you need any other details.
Also sharing the bit of code and logs for you all to analyze.
@Configuration
public class OpenSearchConfig {
private static final Logger logger = LoggerFactory.getLogger(OpenSearchService.class);
private static final String SERVICE_NAME = "es"; // Elasticsearch service name for AWS
private static final String REGION = "XXXX"; // Replace with your OpenSearch region
private static final String OPEN_SEARCH_ENDPOINT = "END_POINT URL"; // Replace with your OpenSearch endpoint
@Bean
public JestClient jestClient() {
// Create a signer
AWS4Signer signer = new AWS4Signer();
signer.setServiceName(SERVICE_NAME);
signer.setRegionName(REGION);
// Interceptor for signing requests
HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(SERVICE_NAME, signer, new DefaultAWSCredentialsProviderChain());
// Jest client configuration
HttpClientConfig clientConfig = new HttpClientConfig.Builder(OPEN_SEARCH_ENDPOINT)
.multiThreaded(true)
.build();
// Jest client factory
JestClientFactory factory = new JestClientFactory() {
@Override
protected HttpAsyncClientBuilder configureHttpClient(HttpAsyncClientBuilder builder) {
return builder.addInterceptorLast(interceptor);
}
};
factory.setHttpClientConfig(clientConfig);
logger.info("connection successful");
return factory.getObject();
}
}
public class OpensearchApplication implements CommandLineRunner {
@Autowired
private JestClient jestClient;
private static final Logger logger = LoggerFactory.getLogger(OpensearchApplication.class);
public static void main(String[] args) {
SpringApplication.run(OpensearchApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Search search = new Search.Builder(query)
.addIndex(index)
.build();
try {
SearchResult result = jestClient.execute(search);
logger.info("Search response: {}", result.getJsonString());
if (!result.isSucceeded()) {
logger.error("Search failed: {}", result.getErrorMessage());
}
System.out.println(result.getJsonString());
} catch (IOException e) {
logger.error("Search request failed", e);
}
}
Aditya Priyam iGTB is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.