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

이해하기 쉽고, 장황하지 않은 자료를 기반으로 강의를 진행합니다.
잔재미코딩 소식 공유
좀더 제약없이, IT 컨텐츠를 공유하고자, 자체 온라인 사이트와, 다음 두 채널도 오픈하였습니다
응원해주시면, 곧 좋은 컨텐츠를 만들어서 공유하겠습니다
●  잔재미코딩 뉴스레터 오픈 [구독해보기]
●  잔재미코딩 유투브 오픈 [구독해보기]

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) 확인하기

In [2]:
!pip install boto3
Collecting boto3
  Downloading boto3-1.20.24-py3-none-any.whl (131 kB)
     |████████████████████████████████| 131 kB 10.6 MB/s eta 0:00:01
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /Users/davelee/opt/anaconda3/lib/python3.8/site-packages (from boto3) (0.10.0)
Requirement already satisfied: s3transfer<0.6.0,>=0.5.0 in /Users/davelee/opt/anaconda3/lib/python3.8/site-packages (from boto3) (0.5.0)
Requirement already satisfied: botocore<1.24.0,>=1.23.24 in /Users/davelee/opt/anaconda3/lib/python3.8/site-packages (from boto3) (1.23.24)
Requirement already satisfied: urllib3<1.27,>=1.25.4 in /Users/davelee/opt/anaconda3/lib/python3.8/site-packages (from botocore<1.24.0,>=1.23.24->boto3) (1.25.11)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /Users/davelee/opt/anaconda3/lib/python3.8/site-packages (from botocore<1.24.0,>=1.23.24->boto3) (2.8.1)
Requirement already satisfied: six>=1.5 in /Users/davelee/opt/anaconda3/lib/python3.8/site-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.24.0,>=1.23.24->boto3) (1.15.0)
Installing collected packages: boto3
Successfully installed boto3-1.20.24
In [4]:
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)
    print (dir(instance))
<botocore.client.EC2 object at 0x7fe9b427c490>
i-0f8ed7ff013c42c95 {'Code': 16, 'Name': 'running'}
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_id', 'ami_launch_index', 'architecture', 'attach_classic_link_vpc', 'attach_volume', 'block_device_mappings', 'boot_mode', 'capacity_reservation_id', 'capacity_reservation_specification', 'classic_address', 'client_token', 'console_output', 'cpu_options', 'create_image', 'create_tags', 'delete_tags', 'describe_attribute', 'detach_classic_link_vpc', 'detach_volume', 'ebs_optimized', 'elastic_gpu_associations', 'elastic_inference_accelerator_associations', 'ena_support', 'enclave_options', 'get_available_subresources', 'hibernation_options', 'hypervisor', 'iam_instance_profile', 'id', 'image', 'image_id', 'instance_id', 'instance_lifecycle', 'instance_type', 'ipv6_address', 'kernel_id', 'key_name', 'key_pair', 'launch_time', 'licenses', 'load', 'meta', 'metadata_options', 'modify_attribute', 'monitor', 'monitoring', 'network_interfaces', 'network_interfaces_attribute', 'outpost_arn', 'password_data', 'placement', 'placement_group', 'platform', 'platform_details', 'private_dns_name', 'private_dns_name_options', 'private_ip_address', 'product_codes', 'public_dns_name', 'public_ip_address', 'ramdisk_id', 'reboot', 'reload', 'report_status', 'reset_attribute', 'reset_kernel', 'reset_ramdisk', 'reset_source_dest_check', 'root_device_name', 'root_device_type', 'security_groups', 'source_dest_check', 'spot_instance_request_id', 'sriov_net_support', 'start', 'state', 'state_reason', 'state_transition_reason', 'stop', 'subnet', 'subnet_id', 'tags', 'terminate', 'unmonitor', 'usage_operation', 'usage_operation_update_time', 'virtualization_type', 'volumes', 'vpc', 'vpc_addresses', 'vpc_id', 'wait_until_exists', 'wait_until_running', 'wait_until_stopped', 'wait_until_terminated']
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다
In [ ]:
 

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

In [ ]:
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 다운로드하기

In [ ]:
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
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다

9.4 RDS 확인

In [ ]:
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)
In [ ]: