Skip to content

Commit fab4aec

Browse files
satishpandeypivovarit
authored andcommitted
Instance profile credentials example. (eugenp#3401)
* Instance profile credentials example. * InstanceProfile CloudFormation template included to provision AWS environment. * Included java package installation under Yaml script. * Using SpringApplication reference to prepare application context. * Introducing SpringCloudS3Service to handle all S3 operations.
1 parent 5d6c477 commit fab4aec

6 files changed

Lines changed: 222 additions & 0 deletions

File tree

‎spring-cloud/spring-cloud-aws/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,8 @@ to write the following in `application.properties`:
1919
cloud.aws.rds.spring-cloud-test-db
2020
cloud.aws.rds.spring-cloud-test-db.password=se3retpass
2121
```
22+
Multiple application classes are available under this project. To launch InstanceProfileAwsApplication application, replace `start-class` under `pom.xml`:
23+
24+
```
25+
<start-class>com.baeldung.spring.cloud.aws.InstanceProfileAwsApplication</start-class>
26+
```

‎spring-cloud/spring-cloud-aws/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
</parent>
2020

2121
<properties>
22+
<start-class>com.baeldung.spring.cloud.aws.SpringCloudAwsApplication</start-class>
2223
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
2324
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
2425
<java.version>1.8</java.version>
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.spring.cloud.aws;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.nio.file.Files;
6+
import java.nio.file.Paths;
7+
import java.util.UUID;
8+
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
import org.springframework.boot.SpringApplication;
12+
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
13+
import org.springframework.boot.builder.SpringApplicationBuilder;
14+
import org.springframework.context.ConfigurableApplicationContext;
15+
import org.springframework.context.annotation.ComponentScan;
16+
import org.springframework.context.annotation.Configuration;
17+
18+
import com.baeldung.spring.cloud.aws.s3.SpringCloudS3Service;
19+
20+
@Configuration
21+
@EnableAutoConfiguration
22+
@ComponentScan("com.baeldung.spring.cloud.aws.s3")
23+
public class InstanceProfileAwsApplication {
24+
25+
private static final Logger logger = LoggerFactory.getLogger(InstanceProfileAwsApplication.class);
26+
private static final String applicationConfig = "spring.config.name:application-instance-profile";
27+
28+
private static String bucketName;
29+
private static String fileName = "sample-file.txt";
30+
31+
private static void setupResources() {
32+
bucketName = "baeldung-test-" + UUID.randomUUID()
33+
.toString();
34+
try {
35+
Files.write(Paths.get(fileName), "Hello World!".getBytes());
36+
} catch (IOException e) {
37+
logger.error(e.getMessage(), e);
38+
}
39+
}
40+
41+
public static void main(String[] args) {
42+
setupResources();
43+
if (!new File(fileName).exists()) {
44+
logger.warn("Not able to create {} file. Check your folder permissions.", fileName);
45+
System.exit(1);
46+
}
47+
48+
SpringApplication application = new SpringApplicationBuilder(InstanceProfileAwsApplication.class).properties(applicationConfig)
49+
.build();
50+
ConfigurableApplicationContext context = application.run(args);
51+
SpringCloudS3Service service = context.getBean(SpringCloudS3Service.class);
52+
53+
// S3 bucket operations
54+
service.createBucket(bucketName);
55+
service.uploadObject(bucketName, fileName);
56+
service.downloadObject(bucketName, fileName);
57+
service.deleteBucket(bucketName);
58+
}
59+
60+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.spring.cloud.aws.s3;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.stereotype.Component;
10+
11+
import com.amazonaws.services.s3.AmazonS3;
12+
import com.amazonaws.services.s3.model.ListObjectsV2Result;
13+
import com.amazonaws.services.s3.model.S3ObjectSummary;
14+
15+
@Component
16+
public class SpringCloudS3Service {
17+
18+
private static final Logger logger = LoggerFactory.getLogger(SpringCloudS3Service.class);
19+
20+
@Autowired
21+
AmazonS3 amazonS3;
22+
23+
@Autowired
24+
SpringCloudS3 springCloudS3;
25+
26+
public void createBucket(String bucketName) {
27+
logger.debug("Creating S3 bucket: {}", bucketName);
28+
amazonS3.createBucket(bucketName);
29+
logger.info("{} bucket created successfully", bucketName);
30+
}
31+
32+
public void downloadObject(String bucketName, String objectName) {
33+
String s3Url = "s3://" + bucketName + "/" + objectName;
34+
try {
35+
springCloudS3.downloadS3Object(s3Url);
36+
logger.info("{} file download result: {}", objectName, new File(objectName).exists());
37+
} catch (IOException e) {
38+
logger.error(e.getMessage(), e);
39+
}
40+
}
41+
42+
public void uploadObject(String bucketName, String objectName) {
43+
String s3Url = "s3://" + bucketName + "/" + objectName;
44+
File file = new File(objectName);
45+
try {
46+
springCloudS3.uploadFileToS3(file, s3Url);
47+
logger.info("{} file uploaded to S3", objectName);
48+
} catch (IOException e) {
49+
logger.error(e.getMessage(), e);
50+
}
51+
}
52+
53+
public void deleteBucket(String bucketName) {
54+
logger.trace("Deleting S3 objects under {} bucket...", bucketName);
55+
ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName);
56+
for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) {
57+
logger.info("Deleting S3 object: {}", objectSummary.getKey());
58+
amazonS3.deleteObject(bucketName, objectSummary.getKey());
59+
}
60+
logger.info("Deleting S3 bucket: {}", bucketName);
61+
amazonS3.deleteBucket(bucketName);
62+
}
63+
64+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
AWSTemplateFormatVersion: 2010-09-09
2+
Metadata:
3+
'AWS::CloudFormation::Designer':
4+
157e7d5f-5cb3-4a23-a50c-97e7f6c57173:
5+
size:
6+
width: 60
7+
height: 60
8+
position:
9+
x: 450
10+
'y': 90
11+
z: 0
12+
embeds: []
13+
9bbaaa55-9cba-4555-a7c6-fb6ac248fd3a:
14+
size:
15+
width: 60
16+
height: 60
17+
position:
18+
x: 260
19+
'y': 90
20+
z: 0
21+
embeds: []
22+
isassociatedwith:
23+
- 157e7d5f-5cb3-4a23-a50c-97e7f6c57173
24+
a7348729-a594-4dca-9b0a-e1c8d777dc3b:
25+
size:
26+
width: 60
27+
height: 60
28+
position:
29+
x: 70
30+
'y': 90
31+
z: 0
32+
embeds: []
33+
Resources:
34+
IAMRoleBaeldung:
35+
Type: 'AWS::IAM::Role'
36+
Properties:
37+
AssumeRolePolicyDocument:
38+
Version: 2012-10-17
39+
Statement:
40+
- Effect: Allow
41+
Principal:
42+
Service:
43+
- ec2.amazonaws.com
44+
Action:
45+
- 'sts:AssumeRole'
46+
ManagedPolicyArns:
47+
- 'arn:aws:iam::aws:policy/AmazonS3FullAccess'
48+
Metadata:
49+
'AWS::CloudFormation::Designer':
50+
id: 157e7d5f-5cb3-4a23-a50c-97e7f6c57173
51+
InstanceProfileBaeldung:
52+
Type: 'AWS::IAM::InstanceProfile'
53+
Properties:
54+
Roles:
55+
- !Ref IAMRoleBaeldung
56+
Metadata:
57+
'AWS::CloudFormation::Designer':
58+
id: 9bbaaa55-9cba-4555-a7c6-fb6ac248fd3a
59+
EC2Instance:
60+
Type: 'AWS::EC2::Instance'
61+
Properties:
62+
ImageId: ami-2581aa40
63+
InstanceType: t2.micro
64+
IamInstanceProfile: !Ref InstanceProfileBaeldung
65+
KeyName: Satish-Ohio
66+
UserData: !Base64
67+
'Fn::Join':
68+
- ''
69+
- - |
70+
#!/bin/bash
71+
- |
72+
apt -y install openjdk-8-jre-headless
73+
Metadata:
74+
'AWS::CloudFormation::Designer':
75+
id: a7348729-a594-4dca-9b0a-e1c8d777dc3b
76+
DependsOn:
77+
- InstanceProfileBaeldung
78+
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Don't try to create DataSouce when running tests which don't need a DataSource
2+
spring.autoconfigure.exclude=\
3+
org.springframework.cloud.aws.autoconfigure.jdbc.AmazonRdsDatabaseAutoConfiguration,\
4+
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
5+
cloud.aws.region.auto=true
6+
7+
# Load instance profile credentials
8+
cloud.aws.credentials.instanceProfile=true
9+
10+
# Disable auto cloud formation
11+
cloud.aws.stack.auto=false
12+
13+
# Disable web environment
14+
spring.main.web-environment=false

0 commit comments

Comments
 (0)