AWS CLI ,SDK, IAM roles

CLI

CLI

Setup

AWS CLI 를 window에서 사용하는 법은 간단하다. 여기서 https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-windows.html aws에서 MSI installer 로 설치하면 된다.

그 후 cmd에서 aws –version 하면 이렇게 뜬다.

CLI_setup

CLI installation Troubleshooting

aws:command not found the aws executable 이 PATH env variable에 없다. (PATH 는 너의 aws 실행파일이 어디있는지 시스템에게 알려주는 역할을 한다.)

AWS CLI configuration

  • 개인컴일 때

IAM 서비스에서 users => security credentials 가서 create access key.

createAccessKey

download .csv file 한다. 이 파일은 super secret임.

download

주의 ! 절대 ec2 머신에서 하지 말것. ec2 머신에 personal credentials 넣는거 안좋다.

command line 에서 aws configure 치면, 다음을 차례로 입력해 주면 된다.

$ aws configure
AWS Access Key ID [None] : [여기 access key 입력]
AWS secret Access Key ID [None] : [여기 secret access key 입력]
Default region name [None] : [여기 region 입력]
  • EC2 instance 일 때

앞서 한 것 처럼하면 아주 큰일 난다. EC2 Instance에 이런 중요한 정보 업로드하면 안된다. 대신, IAM ROLE을 이용한다.

ec2 머신에 ssh 접속한다. aws configure

AWS Access Key ID [None] : [엔터]
AWS secret Access Key ID [None] : [엔터]
Default region name [None] : [여기 region 입력]

IAM 롤에 가서 , create role 한다. aws service => ec2 => policy 찾는다.

iam role

내가 만약 이 ec2 instance에 s3 에 접속 권한을 주고 싶으면, AmazonS3ReadOnlyAccess를 선택하고 role name과 description 써준다. 그리고 next 누르면 끝.

Policy 생성해서 role에 부착한다. 그 role을 ec2에 부착한다.

policyRole

EC2 management 콘솔에 가서 instance setting, attach/replace IAM role 에서 내가 방금 만든 role을 attach 해준다.

iam role

그럼 해결~~~

IAM Roles & Policies 실습

inline policy : 그냥 그 역할을 위해 사용한다. 다른 객체한테 부착불가. 추천하지 않는다.

AWS Simulator 검색해서 들어가면, policy simulator 에서 권한 확인 가능 https://policysim.aws.amazon.com/home/index.jsp

Dry Run

 aws ec2 run-instances --dry-run --image-id [ami-아이디입력] --instance-type t2.micro

dryrun

ec2에서 내 계정이랑 연결을 안해서 오류가 났다.

admin role을 attach 해주고 돌리면 제대로 된다.

STS decoding

https://docs.aws.amazon.com/cli/latest/reference/sts/decode-authorization-message.html

  decode-authorization-message
--encoded-message <value>
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]

이걸 사용하기 위해서 STS decode 권한을 부여해야한다. Policy에서 설정한 후, 이 policy를 내 ec2 instance에 붙어있는 role에 추가한다.

sts폴리시

add

권한 설정을 마쳤으면, 다음과 같이 돌리면 된다.

aws sts decode-authorization-message --encoded-message

STS에러메세지 decode

JSON 형식으로 정보가 DECODE된다.

AWS EC2 Instance Metadata

http://169.254.169.254/latest/meta-data/ 이 url로 접속하면, EC2 INFO를 볼 수 있다.

EC2 instance에 접속해서,

 curl http://169.254.169.254/latest/meta-data/ 

을 하면

meta

다음과 같이 많은 정보를 확인할 수 있다.

주의

  • metadata의 IAM role은 확인 가능하지만, policy는 확인할 수 없다.
  • Metadata 는 Info about the EC2 instance
  • Userdata 는 launch script of the EC2 instance

managing multiple AWS accounts

ec2 instance에 계정을 두개 이상 연결하고 싶을 때는 어떻게 해야할까? cat credentials 을 하면 현재 AWS accounts 나온다.

이럴때는 새로운 profile 만들면 된다.

ex) my-other-ID 프로필 생성 과정

aws configure --profile my-other-ID 
AWS Access key ID [None] : 여기에 입력
AWS Secret Access key [None] : 여기에 입력

그 후 몇가지 정보 더 입력해주면 끝. cat credentials 하면 이제 현재 계정 뿐 아니라, 프로필에 추가된 계정도 함께 나온다.

MFA(Multi Factor Authentication) with CLI

이것을 이용하기 위해서는 STS GetSessionToken API call 이 필요하다.

STS GetSessionToken API call

aws sts get-session-token --serial-number arn-of-the-mfa-device --tokencode code-from-token --duration-seconds 3600

arn-of-the-mfa-device는 계정에서 MFA 등록하면 나오고, code-from-token – 는 내 auth 앱에서 실시간으로 받은 코드다.

IAM => Security credential Assign => MFA device => virtual MFA device setup 간다. 두개의 MFA code 로 인증. 이렇게 등록이 끝나면, Security credential 의 Assigned MFA device 에 있는 arn을 복사한다.

aws sts get-session-token --serial-number [arn-of-the-mfa-device] --tokencode [code-from-token]

위 STS GetSessionToken 을 돌리면, access key, secret key, session token 정보가 나온다.

aws configure --profile mfa 
AWS Access key ID [None] : 여기에 입력
AWS Secret Access key [None] : 여기에 입력

cat ~/.aws/credentials
//후 credential 파일에 aws session token 정보 입력
aws_session_token = 토큰 정보 (긴거) 입력

AWS SDK

내 앱에서 AWS를 바로 이용하려면, SDK(Software development kit)사용.

ex) java, python, go , ruby,PHP 등등이 SDK이다.

AWS CLI는 PYTHON SDK 이용 (BOTO3)

AWS Limits (Quotas)

  • API Rate Limits
    • ec2에서 DescribeInstances API 1초에 100 calls로 제한
    • S3에서 GetObject는 1초에 5500 GET 제한
    • 간헐적 에러 : Exponential Backoff
    • 지속적인 에러 : API throttling limit increase(CALL 한도 늘리는 느낌)
  • Service Quotas (Service Limits)
  • Running On-Demand Standard Instances: 1152 vCPU
  • ticket? 으로 service limit 증가 시킬 수 있다.
  • Service Quotas AP를 사용해 service quota를 증가시킬 수 있다.

Exponential Backoff

throttlingException, retry mechaism, Service Ouatas(service limits)

내 account 에서 리밋에 도달하면 , exponential backoff.

API call을 retry할 때마다 시간이 두배씩 늘어난다. 1초 기다릴거, 한번 리트라이 해서 2초, 4초,8초… 이렇게 시간을 벌면 limit 이 풀려서 정상 작동하게 된다.

AWS CLI credentials provider chain

CLI는 다음과 같은 우선순위로 credential 을 찾는다.

  1. Command line options (– region, –output, –profile)
  2. Env var (AWS_ACCESS_ID..)
  3. CLI credentials file (–aws configure)
  4. CLI configuration file (–aws configure)
  5. Container credentials (for ECS tasks)
  6. Instance profile credentials (for ec2 instance profile)

AWS SDK(JAVA)는 다음과 같은 우선순위로 credential 을 찾는다.

  1. Environment variables – AWS_ACCESS_KEY_ID , AWS_SECRET_ACCESS_KEY
  2. Java system properties – aws.accessKeyId, aws.secretKey
  3. The default credential profiles file – ex at: ~/.aws/credentials, shared by many SDK
  4. Amazon ECS container credentials – for ECS containers
  5. Instance profile credentials– used on EC2 instances

AWS Credentials Scenario

EC2에 배포된 APP이 IAM user로 부터 S3 API를 부를 때 env var에 있는 credentials 을 사용한다.

IAM user은 S3FullAccess permissions을 가지고 있는데, 이 APP은 한 S3 Bucket만 ACCESS 한다.

  • best practices:

    • 이 EC2 Instance를 위한 IAM Role & EC2 Instance Profile을 만든다.(한 s3 bucket에만 access를 할 수 있는 롤을 붙인다.)

      ==> 하지만, IAM Instance Profile이 EC2 instance에 할당됐음에도, 모든 s3 버켓에 접속이 가능하다. 왜냐면 credentials chain 이 env var를 먼저 체크하기 때문이다. instance profile credentials은 맨 마지막에 체크한다.

      ==> 따라서, credential 관련 env var를 unset 하면 된다.

AWS SDK Default credentials provider chain

  1. Environment variables (AWS_ACCESS_KEY_ID…)
  2. JAVA system properties (aws.accessKeyId)
  3. the default credential profiles file
  4. Amazon ECS container credentials (for ECS containers)
  5. Instance profile credentials( used on EC2 instances)

SIGV4

HTTP가 전송한 AWS 요청에 인증 정보를 추가하는 프로세스

Your requests to AWS are signed using your credentials, and so you are authenticated against AWS

Any API Calls done in AWS needs to be signed with your credentials.


© 2018. All rights reserved.

Powered by Hydejack v8.5.2