Access Denied for ElasticBeanstalk DescribeConfigurationSettings API method - java

I tried to run the DescribeConfigurationSettings API method for the ElasticBeanstalk as follow:
AWSElasticBeanstalk ebs = AWSElasticBeanstalkClientBuilder.standard().withRegion(Regions.EU_CENTRAL_1).withCredentials(new AWSStaticCredentialsProvider(credentials)).build();
for(ApplicationDescription ad : ebs.describeApplications().getApplications()){
System.out.println(ad);
for(EnvironmentDescription ed : ebs.describeEnvironments(new DescribeEnvironmentsRequest().withApplicationName(ad.getApplicationName())).getEnvironments()) {
System.out.println(ebs.describeConfigurationSettings(new DescribeConfigurationSettingsRequest().withApplicationName(ad.getApplicationName()).withEnvironmentName(ed.getEnvironmentName())).getConfigurationSettings());
}
}
However, I got the exception of Access Denied with the following message:
Exception in thread "main"
com.amazonaws.services.elasticbeanstalk.model.AWSElasticBeanstalkException:
Access Denied: S3Bucket=elasticbeanstalk-env-resources-eu-central-1,
S3Key=eb_patching_resources/instance_patch_extension.linux (Service:
Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID:
NB44V0RXQG2WHH4T; Proxy: null) (Service: AWSElasticBeanstalk; Status
Code: 400; Error Code: InvalidParameterValue; Request ID:
b058aa54-fc9c-4879-9502-5cb5818bc64a; Proxy: null)
How can I resolve this issue?

Based on the error you get, it seems that you are missing some IAM permissions. I would start by adding AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy Managed policy to your user.
This policy is probably more permissive than what you actually need, but it would be difficult to pinpoint exactly, which permissions are necessary.

Amazon recommends using AWS SDK for Java V2.
Updated Code
Here is the Java V2 code for this use case.
package com.aws.example;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient;
import software.amazon.awssdk.services.elasticbeanstalk.model.*;
import java.util.List;
public class DescribeApplications {
public static void main(String[] args) {
Region region = Region.US_EAST_1;
ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder()
.region(region)
.build();
DescribeApplicationsResponse applicationsResponse = beanstalkClient.describeApplications();
List<ApplicationDescription> apps = applicationsResponse.applications();
for (ApplicationDescription app: apps) {
System.out.println("The application name is "+app.applicationName());
DescribeEnvironmentsRequest desRequest = DescribeEnvironmentsRequest.builder()
.applicationName(app.applicationName())
.build();
DescribeEnvironmentsResponse res = beanstalkClient.describeEnvironments(desRequest) ;
List<EnvironmentDescription> envDesc = res.environments();
for (EnvironmentDescription desc: envDesc) {
System.out.println("The Environment ARN is "+desc.environmentArn());
}
}
}
}
Output here:

Related

JAVA aws s3client : throwing exception : java.lang.BootstrapMethodError: bootstrap method initialization exception

I am trying to connect to my s3 bucket ( already created and I am able to test by listing using s3cmd ) and list the contest of it.
Not seeing any error message when trying to create the connection. However, when trying to list the the content of my bucket, I am getting the exception :
java.lang.BootstrapMethodError: bootstrap method initialization exception
I am using the dependency ( in gradle) :
implementation "software.amazon.awssdk:s3:2.7.10"
Here the code snippet (I am getting the above error from : adapterSmsS3Client.listBuckets())
import software.amazon.awssdk.services.s3.S3Client;
....
private static final String BASE_URL = "https://s3.us-west-2.amazonaws.com";
private static final String BUCKET_NAME = "adapter-stream/dev";
....
S3Client adapterSmsS3Client = S3Client.builder()
.region(Region.US_WEST_2)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("access-key","secret-key")))
.endpointOverride(URI.create(BASE_URL))
.build();
System.out.println("====Checking connection: " +adapterSmsS3Client.listBuckets());
Any insight on what I am missing ?

Trouble connecting sam local api to secrets manager

I'm trying to set up AWS SAM locally so I don't have to deploy every time I make a code change. But I'm having trouble getting the secrets out of Secrets Manager. I've created a new SAM project using sam init --runtime java
I then created a new secret in Secret Manager, and changed the code in the HelloWorldFunction to try to retrieve the secret.
package helloworld;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder;
import com.amazonaws.services.secretsmanager.model.*;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<Object, Object> {
public Object handleRequest(final Object input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
try {
String secretName = "testsecret";
String region = "us-west-2";
// Create a Secrets Manager client
AWSSecretsManager client = AWSSecretsManagerClientBuilder.standard()
.withRegion(region)
.build();
String secret, decodedBinarySecret;
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest()
.withSecretId(secretName);
GetSecretValueResult getSecretValueResult = null;
try {
getSecretValueResult = client.getSecretValue(getSecretValueRequest);
} catch (DecryptionFailureException e) {
// Secrets Manager can't decrypt the protected secret text using the provided KMS key.
// Deal with the exception here, and/or rethrow at your discretion.
throw e;
} catch (InternalServiceErrorException e) {
// An error occurred on the server side.
// Deal with the exception here, and/or rethrow at your discretion.
throw e;
} catch (InvalidParameterException e) {
// You provided an invalid value for a parameter.
// Deal with the exception here, and/or rethrow at your discretion.
throw e;
} catch (InvalidRequestException e) {
// You provided a parameter value that is not valid for the current state of the resource.
// Deal with the exception here, and/or rethrow at your discretion.
throw e;
} catch (ResourceNotFoundException e) {
System.out.println(e.getMessage());
StringWriter outError = new StringWriter();
e.printStackTrace(new PrintWriter(outError));
System.out.println(outError.toString());
// We can't find the resource that you asked for.
// Deal with the exception here, and/or rethrow at your discretion.
throw e;
}
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if (getSecretValueResult.getSecretString() != null) {
secret = getSecretValueResult.getSecretString();
return new GatewayResponse(secret, headers, 200);
}
else {
decodedBinarySecret = new String(Base64.getDecoder().decode(getSecretValueResult.getSecretBinary()).array());
return new GatewayResponse(decodedBinarySecret, headers, 200);
}
} catch (Exception e) {
return new GatewayResponse("{}", headers, 500);
}
}
}
When I run sam local start-api and navigate to http://127.0.0.1:3000/hello, I get this error:
Secrets Manager can’t find the specified secret. (Service: AWSSecretsManager; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: 6881467f-d968-4f4e-ae60-7e3128124cc5)
com.amazonaws.services.secretsmanager.model.ResourceNotFoundException: Secrets Manager can’t find the specified secret. (Service: AWSSecretsManager; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: 6881467f-d968-4f4e-ae60-7e3128124cc5)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1632)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1058)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.doInvoke(AWSSecretsManagerClient.java:2024)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.invoke(AWSSecretsManagerClient.java:2000)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.executeGetSecretValue(AWSSecretsManagerClient.java:878)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.getSecretValue(AWSSecretsManagerClient.java:853)
at helloworld.App.handleRequest(App.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at lambdainternal.EventHandlerLoader$PojoMethodRequestHandler.handleRequest(EventHandlerLoader.java:259)
at lambdainternal.EventHandlerLoader$PojoHandlerAsStreamHandler.handleRequest(EventHandlerLoader.java:178)
at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:888)
at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:293)
at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:64)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:114)
But, it's the same code to get the secret that was given in the secrets manager. Is it not possible to connect to real AWS services from sam local? I had a similar issue with DynamoDB, but was able to get it working with by using DynamoDB Local.
Any suggestions on how to either connect to the real secrets manager or to fake it locally somehow?
When you run DynamoDB Local, it is actually running a mock DDB server in a thread (or as a local process depending on how you start it) within you running test process. Unfortunately, Secrets Manager and other AWS services do not offer an equivalent testing solution.
However, if you are getting back ResourceNotFoundException it seems likely that you were able to successfully connect to Secrets Manager. It may be possible that the connection to secrets manager is using a different account than the one in which you stored the secret. One way you can check which credentials the code is using is to use the STS get caller identity call.

Angular2 HttpClient to consume Rest API

Using Angular2, I have developed the example given in the tutorial (The Hero Editor).
https://angular.io/tutorial/toh-pt6
By default, it calls a self-in-memory-store with the data that is accessible through the Http Client created in the same example.
All this run perfectly in localhost:3000 (the port given by default).
Now I have developed a rest api server in Java which runs perfectly in localhost:8080 using this tutorial:
http://spring.io/guides/gs/rest-service/
Nevertheless, when I switch the URL where Angular service has to get the data from, I get the following error:
ERROR Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:8080/heroes
at resolvePromise (zone.js:769)
at resolvePromise (zone.js:740)
at zone.js:817
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (ng_zone.ts:253)
at ZoneDelegate.invokeTask (zone.js:423)
at Zone.runTask (zone.js:191)
at drainMicroTaskQueue (zone.js:584)
at XMLHttpRequest.ZoneTask.invoke (zone.js:490)
Complete http Response:
But I check the url and it works perfectly.
Do I have to tell anything else to the Service?
This is the point where all should be done.
//private heroesUrl = 'api/heroes'; // Old URL (to get the own data storage)
private heroesUrl = `http://localhost:8080/heroes`; // New URL to get the data from working local Rest API running in other port.
constructor (private http: Http) { }
getHeroes(): Promise<Hero[]> {
//return Promise.resolve(HEROES);
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError)
} // stub
Edit: answering a comment, I show below the app module code. By the way, it is an exact copy of the app.module.ts from the Hero Editor Angular tutorial I linked at the beginning of the question.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppRoutingModule } from './app-routing.module';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { DashboardComponent} from './dashboard.component'
import { HeroDetailComponent } from './hero-detail.component';
import { HeroSearchComponent } from './hero-search.component';
import { HeroesComponent } from './heroes.component';
import { HeroService } from './hero.service';
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
AppRoutingModule
],
declarations: [
AppComponent,
HeroDetailComponent,
HeroesComponent,
DashboardComponent,
HeroSearchComponent
],
providers: [ HeroService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Any idea anyone? I have seen some examples where they are adding some more information to the headers. Is that necessary? Any issue about security?
I got the solution.
#AJT_82 gave me the main clue.
As It was said in the app module (app.module.js) file, my app was taking the data from an InMemory storage system.
When I commented this line:
//InMemoryWebApiModule.forRoot(InMemoryDataService)
it just started to get the data from the URL provided to the localhost:8080/heroes Rest API.
Sorry for making you waste your time.

AWS SDK for JAVA with IAM service in Eucalyptus

I‘m trying to use Amazon AWS SDK for developing Eucalyptus,but II am always getting access denied for that:public class App {
public static AmazonEC2 ec2;
public static AmazonS3 s3;
public static AmazonIdentityManagement identityManagement;
private static String ACCESS_KEY;
private static String SECRET_KEY;
private static String IDENTITY_END_POINT;
public static void init(){
ACCESS_KEY="myaccesskey";
SECRET_KEY="mysecretkey";
IDENTITY_END_POINT="http://192.168.1.101:8773/services/Euare";
AWSCredentials myCredential = new BasicAWSCredentials(ACCESS_KEY,SECRET_KEY);
//ec2 = new AmazonEC2Client(myCredential);
s3 = new AmazonS3Client(myCredential);
//ec2.setEndpoint(EC2_END_POINT);
s3.setEndpoint(Walrus_END_POINT);
identityManagement=new AmazonIdentityManagementClient(myCredential);
identityManagement.setEndpoint(IDENTITY_END_POINT);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
init();
List<Bucket> buckets = s3.listBuckets();
System.out.println("List of all buckets in your cloud:\n");
for (Bucket bucket : buckets) {
System.out.println(bucket.getName()+"\n");
}
CreateUserRequest createUserRequest=new CreateUserRequest().withPath("/").withUserName("summer");
CreateUserResult createUserResult=identityManagement.createUser(createUserRequest);
}
}
That is the error I get:
Exception in thread "main" Status Code: 404, AWS Service: AmazonIdentityManagement, AWS Request ID: null, AWS Error Code: null, AWS Error Message: null
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:614)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:312)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:165)
at com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient.invoke(AmazonIdentityManagementClient.java:3130)
at com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient.getUser(AmazonIdentityManagementClient.java:1201)
at com.test2.Group.main(Group.java:107)
I'm not sure what would cause a 404 when using the IAM API, the code you posted does not seem to match the posted exception.
You don't say which versions of Eucalyptus and the AWS Java SDK you are using, but with some versions it is necessary to add a / to the endpoint URL so that the AWS Java SDK calculates the signature correctly, e.g. for IAM:
"http://$EXAMLE:8773/services/Euare/"
I do not think this would cause the 404 issue however.
You can find details on using the AWS Java SDK with Eucalyptus here:
https://github.com/eucalyptus/eucalyptus/wiki/HOWTO-Use-AWS-Java-SDK-with-Eucalyptus
Unit tests for the AWS Java SDK with Eucalyptus are here:
https://github.com/eucalyptus/eutester/tree/testing/eutester4j/com/eucalyptus/tests/awssdk
This includes some coverage for IAM/STS services.

JavaAgent in Lotus Notes 6.5 using axis api gives Exception "No implementation defined for org.apache.commons.logging.LogFactory"

I needed to write a JavaAgent in a Lotus Notes 6.5 DB to access a web service. I used Axis Apache API for this purpose. I created A Java agent and added the jar files of axis in the agent by using Edit Project button.
Below is the agent code:
import lotus.domino.*;
import javax.xml.*;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;
import java.net.URL;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
String endpoint = "http://ws.apache.org:5049/axis/services/echo";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new java.net.URL(endpoint) );
call.setOperationName(new QName("http://soapinterop.org/", "echoString"));
String ret = (String) call.invoke( new Object[] { "Hello!" } );
System.out.println("Sent 'Hello!', got '" + ret + "'");
} catch(Exception e) {
e.printStackTrace();
}
}
}
And below is the exception thrown:
java.lang.ExceptionInInitializerError: org.apache.commons.discovery.DiscoveryException: No implementation defined for org.apache.commons.logging.LogFactory
at org.apache.commons.discovery.tools.SPInterface.newInstance(SPInterface.java:197)
at org.apache.commons.discovery.tools.DiscoverClass.newInstance(DiscoverClass.java:579)
at org.apache.commons.discovery.tools.DiscoverSingleton.find(DiscoverSingleton.java:418)
at org.apache.commons.discovery.tools.DiscoverSingleton.find(DiscoverSingleton.java:378)
at org.apache.axis.components.logger.LogFactory$1.run(LogFactory.java:84)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.axis.components.logger.LogFactory.getLogFactory(LogFactory.java:80)
at org.apache.axis.components.logger.LogFactory.<clinit>(LogFactory.java:72)
at org.apache.axis.configuration.EngineConfigurationFactoryFinder.<clinit>(EngineConfigurationFactoryFinder.java:94)
at org.apache.axis.client.Service.<init>(Service.java:111)
at JavaAgent.NotesMain(JavaAgent.java:17)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(NotesThread.java:218)
I thried to follow some links on the internet like, But i was not able to get exactly what it was asking to do. eg: http://www-10.lotus.com/ldd/nd6forum.nsf/55c38d716d632d9b8525689b005ba1c0/40d033fba3897f4d85256cd30034026a?OpenDocument
Any help will be great. All i wanted to do is write an agent so that i can access a web service, say temperature conversion web service on w3schools. http://www.w3schools.com/webservices/tempconvert.asmx?op=FahrenheitToCelsius
I googled with your error message and this is the first hit:
http://croarkin.blogspot.fi/2010/08/commons-logging-headaches-with-axis.html
It suggests using a commons-logging.properties file with:
org.apache.commons.logging.Log = org.apache.commons.logging.impl.Log4JLogger
org.apache.commons.logging.LogFactory = org.apache.commons.logging.impl.LogFactoryImpl
or putting this to your code:
#BeforeClass
public static void beforeClass() {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
}
Probably you've already tried this because it's the first hit with google but just in case...

Categories

Resources