클라우드 컴퓨팅 (AWS) - AWS 서비스 프로그래밍으로 제어하기

6. AWS 서비스 프로그래밍으로 제어하기

6.1. AWS CLI

  • pip install aws-shell
  • Go to My Account -> Security Credentials (not AWS Management Console)
  • aws-shell
    • aws ec2 get-console-output --instance-id instance_id
- sudo /home/ubuntu/anaconda3/bin/pip install boto3
- mkdir ~/.aws
- vi ~/.aws/credentials

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

- Check Availability zone in EC2 (AWS Management Console)
  - ap-northeast-2  (remove a!)
- vi ~/.aws/config

[default]
region=ap-northeast-2

6.2. 파이썬 프로그래밍으로 서버(EC2) 확인하기

import boto3

client = boto3.client('ec2')
print(client)
# response = client.describe_instances()
# print(response)

ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
    print (instance.id, instance.state)

6.3. 파이썬 프로그래밍으로 S3 리스트 확인하기

import boto3
import botocore

s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
    print(bucket.name)
    for item in bucket.objects.all():
        # s3.Bucket(bucket.name).download_file(item.key, item.key)
        print(item.key)

6.4 파이썬 프로그래밍으로 S3 object 다운로드하기

import boto3
import botocore

BUCKET_NAME = "funcoding"
KEY = "data/test.jpg"

s3 = boto3.resource('s3')

try:
    s3.Bucket(BUCKET_NAME).download_file(KEY, 'test.jpg')
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == '404':
        print("The object does not exist")
    else:
        raise

9.4 RDS 확인

import boto3

rds = boto3.client('rds')
try:
    # get all of the db instances
    dbs = rds.describe_db_instances()
    for db in dbs['DBInstances']:
        print(db['MasterUsername'])
        print(db['Endpoint']['Address'])
        print(db['Endpoint']['Port'])
        print(db['DBInstanceStatus'])
except Exception as error:
    print (error)