[Flutter] AWS Amplify 사용하기

NoeG·2022년 5월 25일
0

개발

목록 보기
2/3

작업환경 IntelliJ IDEA / Flutter
요구 사항
AWS 가입 계정
NPM 설치 (권장 방법)
Node.js 설치

AWS 시작하기 : AWS에서 Flutter 애플리케이션 구축

AWS를 사용하며 느낀 최고의 장점은 Document가 굉장히 친절하다는 것이다.

위 링크의 AWS Document에서는 Flutter를 통해 AWS를 사용하는 튜토리얼을 제공하는데 사실상 필수 기능은 모두 구현해볼 수 있다.

다음과 같은 4가지 기능이 튜토리얼로 구현되어 있다.
1. AWS Amplify CLI를 사용하여 서버리스 클라우드 백엔드 관리
2. Amazon Cognito를 사용하여 사용자 인증
3. Amazon S3에서 파일 업로드 및 다운로드
4. Amazon Pinpoint에 분석 이벤트 기록

본 포스팅에서는 이 중 Amplify CLI를 이용하여 개발 환경 구축을 다루고 이후 하나씩 추가 포스팅을 할 예정이다.

Amplify CLI 개발 환경 구축하기

Amplify CLI (Node.js 필요)
터미널을 사용하여 Local에서 AWS를 생성, 관리, 제거 등의 명령을 수행할 수 있도록 하는 서비스

1. Amplify-Flutter 개발자 프리뷰 버전 설치

npm을 활용하여 설치

$ npm install -g @aws-amplify/cli@flutter-preview

NPM & Node.js 설치 혹은 기타 설치 방법 안내

2. Amplify 설치 확인

$ amplify --version

성공적으로 설치 시 아래와 같은 결과를 확인할 수 있다.

7.7.0-flutter-preview.2

3. Amplify 구성하기

$ amplify configure

1) AWS Console로 안내

Follow these steps to set up access to your AWS account:

Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

Enter를 눌러 다음 설정으로 이동하면 된다.

2) Region 설정

Specify the AWS Region
? region:  
  eu-west-3 
  eu-central-1 
  ap-northeast-1 
❯ ap-northeast-2 
  ap-southeast-1 
  ap-southeast-2 
  ap-south-1 

한국에서 제공할 서비스의 경우
ap-northeast-2 Asia Pacific (Seoul)
를 선택해서 설정해주면 된다.

기타 지역은 아래 AWS Document에서 확인 후 사용하면 된다.
AWS Doc - 사용 가능한 리전

3) User 생성

AWS에는 두 가지 계정이 있는데
그 중에 권한을 부여하여 생성할 수 있는 IAM 유저를 생성하는 과정이다.

Specify the username of the new IAM user:
? user name:  # User name for Amplify IAM user
Complete the user creation using the AWS console

Username을 입력하고 발급받은 accessKeyId와 secretAccessKey를 입력하면 된다.

Specify the username of the new IAM user:
? user name:  username
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=ap-northeast-2#/users$new?step=final&accessKey&userNames=rjsgy0815&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue

Enter the access key of the newly created user:
? accessKeyId:  발급받은 accessKeyId 입력
? secretAccessKey:  발급받은 secretAccessKey 입력
This would update/create the AWS Profile in your local machine
? Profile Name:  username

Successfully set up the new user.

IAM 계정은 다음과 같은 절차로 생성할 수 있다.

AWS Doc - User 생성

참고로 AWS에서는 새로운 개발 환경마다 개별로 관리를 하기 위하여 기존의 IAM 계정을 사용하는 것이 아닌 개별 IAM 계정을 사용할 것을 권장하고 있다.

It is recommended to create a new IAM user for every device that installs the Amplify CLI, rather than attempt to use an existing IAM user used on another device. Having a distinct user for each machine provides the best level of visibility and control without breaking the deployment of your app, allowing for the quick deactivation of an individual machine if needed.

Amplify 초기화하기

프로젝트의 Root Directory (최상위 디렉토리)에서 실행해야 한다.

1. Amplify Init

$ amplify init

정상적으로 수행되면 아래와 같은 결과를 확인할 수 있다.

? Do you want to use an existing environment? Yes
? Choose the environment you would like to use: dev

첫 번째 질문에 Yes를 답하여 Default 설정을 사용하면 다음과 같은 결과를 확인할 수 있다. No를 선택하면 Default 값이 아닌 사용자 설정 값을 사용할 수 있다.

Using default provider  awscloudformation
✔ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
~~

Amplify 초기화가 성공하면 아래와 같은 결과를 확인할 수 있다.

1) 루트 디렉토리에 amplify 폴더 생성
2) /lib 내에 amplifyconfiguration.dart 파일 생성

2. 프로젝트에 종속성 추가

amplify_core 패키지 종속성 추가

$ flutter pub add amplify_core

참고로 IOS에서도 사용을 하기 위해서는 /ios/Podfile 에서 platform을 11.0 이상으로 수정해야한다.

# Uncomment this line to define a global platform for your project
platform :ios, '11.0'

Project 에 적용하기

###0. Amplify 인스턴스 추가하기

... // class _MyAppState extends State<MyApp> {

final _amplify = Amplify();

... // final _authService = AuthService();

튜토리얼에서는 main.dart 의 State class에 넣었으나 굳이 그럴 필요는 없으며 필요한 위치에서 인스턴스를 추가하면 된다.

###1. Amplify 구성 함수 추가

  try {
    await Amplify.configure(amplifyconfig);
    print('Successfully configured Amplify 🎉');
  } on AmplifyAlreadyConfiguredException {
    print("Amplify was already configured. Looks like app restarted on android.");
  } catch (e) {
    print('Could not configure Amplify ☠️');
  }

해당 함수는 amplifyconfiguration.dart의 amplifyconfig를 전달하고 필요한 플러그인을 사용하여 Amplify 객체를 구성하는 함수이다.
이를 초기화 함수에 넣고 사용하면 된다.
실제로 Amplify 구성이 성공적으로 이루어지면 로그에 아래의 메시지가 출력된다.

flutter: Successfully configured Amplify 🎉

여기까지 완료되었다면 Amplify를 사용할 준비가 된 것이다.

profile
아이디어를 세상에 꽃 피워보기

0개의 댓글