hyeonga_code

Project_AWS_S3_IAM 사용자 생성, S3 설정 본문

Project_WEATHERWEAR

Project_AWS_S3_IAM 사용자 생성, S3 설정

hyeonga 2024. 1. 3. 06:59
반응형

- S3 를 사용하기 위해서는 엑세스 권한을 가진 IAM 사용자가 있어야 합니다.

 

1. AWS에서 IAM 선택

2. 엑세스 관리 > 사용자에서 사용자 생성

 

 

3. 권한 설정

> 직접 정책 연결

> "AmazonS3FullAccess" 선택

> 다음

 

 

4. 태그 추가 건너뛰기

 

 

 

5. 엑세스 키 생성하기

 

 

 

6. CLI 선택

 

 

 

7. 엑세스 키/비밀 엑세스 키 확인 >>> 꼭 저장해두기

엑세스 키 : 

비밀 엑세스 키 :

 

 

 

완료

 

 

 

 

 

===========================================

S3 설정하기 

1. AWS 접속 > S3 선택 > 버킷 생성

 

추가 : >>> ACL 활성화를 선택해야 추후에 ACL 편집이 가능합니다.

 

 

2. 버킷의 퍼블릭 엑세스 차단 해제

 

 

3. 버킷 만들기

 

 

 

4. 상세 정보 보기

 

 

5. 권한 설정하기

> 권한 > 버킷 정책 > 편집

- 버킷 ARN 복사해두기 : arn:aws:s3:::hyeongabucket

 

 

6. AWS Policy Generator 

Step1 : Select Policy Type : S3 Bucket Policy

Step2 : 

    - Principal : *

    - AWS Service : Amazon S3

    - Actions : All Actions('*') 체크하기

    - Amazon Resource Name(ARN) : 복사한 ARN 값 입력

> Add Statement

 

 

 

 

7. 정책 생성하기 

 

8. 생성된 정책

{
  "Id": "Policy1700392337795",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1700392308143",
      "Action": "s3:*",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::버킷이름",
      "Principal": "*"
    }
  ]
}

 

 

9. 정책 수정하기

    - Resource 경로 마지막에 /* 추가하여 버킷 내의 모든 하위 경로를 전부 추적합니다.

{
  "Id": "Policy1700392337795",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1700392308143",
      "Action": "s3:*",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::버킷이름/*",
      "Principal": "*"
    }
  ]
}

 

 

10. 변경 사항 저장

 

 

11. ACL 편집

 

 

12. 모든사람 읽기 체크

 

 

13. 최종 상태
AmazonS3 > 버킷

- 퍼블릭으로 표시되면 완료된 것입니다.

 

 

 

 

=========

테스트하기

 

1. 버킷 선택하기 > 업로드 

 

 

2. 파일 추가

 

 

3. 업로드하기 

 

 

 

4. 상세 보기에서 객체 URL 브라우저에 검색하기

 

5. 결과

 

 

 

 

=========================

Java에서 파일 업로드하기

 

1. pom.xml에 라이브러리 추가하기

<!-- AWS S3에 파일 업로드 라이브러리 시작 -->
		<dependency>
			<groupId>com.amazonaws</groupId>
			<artifactId>aws-java-sdk-s3</artifactId>
			<version>1.11.901</version>
		</dependency>
<!-- AWS S3에 파일 업로드 라이브러리 끝 -->

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.basic</groupId>
    <artifactId>json</artifactId>
    <name>s3Project</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>11</java-version>
        <org.springframework-version>5.3.27</org.springframework-version>
        <org.aspectj-version>1.9.19</org.aspectj-version>
        <org.slf4j-version>2.0.7</org.slf4j-version>
    </properties>
    <dependencies>
<!-- AWS S3에 파일 업로드 라이브러리 시작 -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.901</version>
        </dependency>
<!-- AWS S3에 파일 업로드 라이브러리 끝 -->
    
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
                
        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>    
        
        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>
 
        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
                
        
        <!-- Servlet -->
<!-- Servlet : 기본값
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
-->
<!-- javax.servlet-api : servlet-api 대신 사용 -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
        
<!-- javax.servlet.jsp-api : jsp-api 대신 사용 -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>       
    <!-- project 기본 설정 끝 -->
         
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
 
<!-- maven-compiler-plugin : 버전 변경 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            
<!-- exec-maven-plugin : 버전 변경 -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
 
cs

 

 

2. 클래스 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.basic.aws;
 
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
 
public class AwsS3 {
 
    private AmazonS3 s3Client;
    final private String ACCESSKEY = "IAM에서 만든 엑세스 키";
    final private String SECRETKEY = "IAM 에서 받은 시크릿 키 엑세스";
    
    private Regions clientRegion = Regions.AP_NORTHEAST_2;
    private String bucket = "생성한 버킷 이름";
    
    private AwsS3() {
        createS3Client();
    }
    
    static private AwsS3 instance = null;
    
    public static AwsS3 getInstance() {
        if(instance == null) {
            return new AwsS3();
        } else {
            return instance;
        }
    }
    
    // aws S3 Client 생성
    private void createS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(ACCESSKEY, SECRETKEY);
        
        this.s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(clientRegion).build();
    }
}
 
cs

 

 

 

3. 업로드 메소드 생성

	// 파일 하나 업로드
	public void upload(File file, String key) {
		uploadToS3(new PutObjectRequest(this.bucket, key, file));
	}
	
	// 여러 파일 업로드
	public void upload(InputStream is, String key, String contentType, long contentLength) {
		ObjectMetadata objectMetadata = new ObjectMetadata();
		
		objectMetadata.setContentType(contentType);
		objectMetadata.setContentLength(contentLength);
		
		uploadToS3(new PutObjectRequest(this.bucket, key, is, objectMetadata));
	}
	
	public void uploadToS3(PutObjectRequest putObjectRequest) {
		try {
			this.s3Client.putObject(putObjectRequest);
			System.out.println(String.format("[%s] upload complete", putObjectRequest.getKey()));
		} catch (AmazonServiceException e) {
			e.printStackTrace();
		} catch (SdkClientException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.basic.aws;
 
import java.io.File;
import java.io.InputStream;
 
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
 
public class AwsS3 {
 
    private AmazonS3 s3Client;
    final private String ACCESSKEY = "IAM에서 만든 엑세스 키";
    final private String SECRETKEY = "IAM 에서 받은 시크릿 키 엑세스";
    
    private Regions clientRegion = Regions.AP_NORTHEAST_2;
    private String bucket = "hyeongabucket";
    
    private AwsS3() {
        createS3Client();
    }
    
    static private AwsS3 instance = null;
    
    public static AwsS3 getInstance() {
        if(instance == null) {
            return new AwsS3();
        } else {
            return instance;
        }
    }
    
    // aws S3 Client 생성
    private void createS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(ACCESSKEY, SECRETKEY);
        
        this.s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(clientRegion).build();
    }
    
    public void upload(File file, String key) {
        uploadToS3(new PutObjectRequest(this.bucket, key, file));
    }
    
    public void upload(InputStream is, String key, String contentType, long contentLength) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        
        objectMetadata.setContentType(contentType);
        objectMetadata.setContentLength(contentLength);
        
        uploadToS3(new PutObjectRequest(this.bucket, key, is, objectMetadata));
    }
    
    public void uploadToS3(PutObjectRequest putObjectRequest) {
        try {
            this.s3Client.putObject(putObjectRequest);
            System.out.println(String.format("[%s] upload complete", putObjectRequest.getKey()));
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

 

4. Main 메소드 작성하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.w2.client;
 
import java.io.File;
 
import com.w2.aws.AwsS3;
 
public class FileMain {
    public AwsS3 awsS3 = AwsS3.getInstance();
    
    public static void main(String[] args) {
        FileMain main = new FileMain();
        
        File file = new File("H:\\TeamProject\\PPT\\logo.png");
        String key = "image/mainLogo.png";
        String copyKey = "image/copyLogo.png";
        
        main.upload(file, key);
    }
    
    public void upload(File file, String key) {
        awsS3.upload(file, key);
    }
}
 
cs

 

 

 

5. 실행하기

 

 

6. 확인하기

 

7. 이미지 확인

 

 

 

이미지 경로

https:// [ 버킷 이름 ] . s3.ap-northeast-2.amazonaws.com/  [버킷 내 경로 ] / [ 저장되는 이름 . 확장자 ]

 

 

 

 

반응형