자료구조&알고리즘

알고리즘 스터디 8회- AWS EC2 instance start 코드 만들기

초코쨔응 2019. 1. 3. 11:00

01/02


오늘의 목표: AWS EC2를 직접 로그인하지 않고도 instance start 코드를 만들어서 사용자에게 exe 파일로 제공하기!

 

시도하면서 시행착오를 겪은 과정순으로 정리하였습니다.

 

# 0. AWS 에서 제공하는 예시 코드

https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/APIReference/API_StartInstances.html

이 사이트를 참고하면 다음과 같이 작성하라고 나와있다.

 

https://ec2.amazonaws.com/?Action=StartInstances &InstanceId.1=i-1234567890abcdef0 &AUTHPARAMS

 

 

# 1. Python requests 모듈 사용

하지만 requests를 이용해서 위의 정보를 넘겨도 파일이 넘어오지 않아서, 인터넷에서 사용자들이 직접 작성한 코드를 검색하였다.

 

 

# 2. AWS Data Pipeline
AWS Data Pipeline을 사용한 방식이 있지만, 어떻게 시작하는지 알기 어려워서 시도해보지 못했다.

https://aws.amazon.com/ko/premiumsupport/knowledge-center/stop-start-ec2-instances/

 


 

# 3. Python boto 모듈 사용

boto를 사용한 코드는 다음과 같다. (https://stackoverflow.com/questions/2413029/auto-shutdown-and-start-amazon-ec2-instance) 키까지 찾아서 넣었으나, 계속해서 접근이 거부되었다.

 

 

#!/usr/bin/python
#
# Auto-start and stop EC2 instances
#


import boto, datetime, sys
from time import gmtime, strftime, sleep

 

# AWS credentials
aws_key = "AKIAxxx"
aws_secret = "abcd"

 

# The instances that we want to auto-start/stop
instances = [
    # You can have tuples in this format:
    # [instance-id, name/description, startHour, stopHour, ipAddress]
    ["i-12345678", "Description", "00", "12", "1.2.3.4"]
]

# --------------------------------------------

# If its the weekend, then quit
# If you don't care about the weekend, remove these three
# lines of code below.
weekday = datetime.datetime.today().weekday()
if (weekday == 5) or (weekday == 6):
    sys.exit()

 

# Connect to EC2
conn = boto.connect_ec2(aws_key, aws_secret)

 

# Get current hour
hh = strftime("%H", gmtime())

 

# For each instance
for (instance, description, start, stop, ip) in instances:
    # If this is the hour of starting it...
    if (hh == start):
        # Start the instance
        conn.start_instances(instance_ids=[instance])
        # Sleep for a few seconds to ensure starting
        sleep(10)

        # Associate the Elastic IP with instance
        if ip:
            conn.associate_address(instance, ip)
    # If this is the hour of stopping it...
    if (hh == stop):
        # Stop the instance
        conn.stop_instances(instance_ids=[instance])

 

 

# 4. Python boto3 모듈 사용 - 성공!

그러나 boto3 코드로 작성하였더니, 정상적으로 instance를 시작하고 종료할 수 있었다. (https://stackoverflow.com/questions/48600798/how-to-start-all-the-ec2-instances-using-python-by-configuring-boto3-libraries-i)

 

 

#Basic import boto3 libraries
import boto3
import sys

 

 

#provided Access Credentialsaccess_key
access_key = ""
secret_key = ""

count=0


#Establish a connection to EC2 resource using credentials and region_name
conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name='us-west-1')
print("Argument length: ",len(sys.argv))

 

if len(sys.argv)>2:
    Keyname = sys.argv[1]
    value = sys.argv[2]
    instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped'],'Name': 'tag:'+Keyname,'Values': [value]}])
    print("Arguments passed\nKey: "+Keyname+"\nValue: "+value)
else:
    instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])

for instance in instances:
    #instance.start(instance.id)
    count+=1
    print(instance.id,",",instance.state["Name"])

print("Total number of EC2 instances are stopped on cloud: ",count)

 

 

# 5. Python 파일을 exe 실행파일로 만드는 방법 탐색

1) cx_freeze

2) py2exe

3) pyinstaller

 

 

# 6. Python의 pyinstaller를 이용해 exe 실행 파일로 만들기

pyinstaller를 사용했을 때, library not found 오류가 나는데, (빨간 글씨로 나지는 않지만 변환 과정 중 메세지가 엄청나게 많이 뜬다)

Window 10 SDK를 설치하라는 문제라는 의견이 많아서 설치하였지만 여전히 오류가 났다. (https://winterj.me/pyinstaller/)

exe 파일이 생기기는 하지만, 외부 컴퓨터에서 exe를 돌려봤을 때 config parser가 없다는 오류가 나면서 동작하지 않았다.

 

 

# 7. auto-py-to-exe 프로그램으로 python을 exe 실행 파일로 만들기

대신 auto-py-to-exe 라는 프로그램을 사용하였다. (https://pypi.org/project/auto-py-to-exe/) 그러나, 역시 외부 컴퓨터에서 exe를 돌려봤을 때 config parser가 없다는 오류가 나면서 동작하지 않았다.

 

 

# 8. Python의 cx_freeze를 이용해 exe 실행 파일로 만들기

다음은 cx_freeze를 시도하였는데, module 이 같이 빌드되지 않았다. https://cx-freeze.readthedocs.io/en/latest/distutils.html

해결 방법!! packages에 html.parser, configparser, boto3 를 꼭 넣어줘야 한다.

 

 

import sys
from cx_Freeze import setup, Executable

 

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["html.parser","configparser","boto3"]}

 

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(name = "PL_study_start_instance",
      version = "0.1",
      description="My study",
      options = {"build_exe": build_exe_options},
      executables = [Executable("PL_study_start_instance.py", base=base)])

 

 

위 코드에 name, version, description은 원하는 내용으로 아무거나 써주면 되고, executables에 내가 exe로 만들고 싶은 python 파일 이름을 적어준다. 이 코드와 같은 위치에 존재해야한다. 위 코드는 setup.py로 저장한 후에, cmd에 가서 setup.py가 있는 위치로 이동한다. python setup.py build 라고 cmd에 명령어로 쳐주면 build라는 폴더에 exe파일이 생겨난다!

 

=> 최종적으로 exe 파일만 말고, 이 폴더 전체를 (모듈째로 줘야하기 때문에) 이용자에게 넘겨주면, exe가 작동되게 할 수 있다.

 

cf) 위의 패키지들 중에 configparser는 python2에서 python3로 넘어오면서 이름이 바뀌어서 오류가 많이 난다. 꼭 포함시켜 줄 것!

 

 

cf) 모듈 설치를 하기 위한 python pip 가 안 되는 문제

-> 내 컴퓨터에 python이 35버전과 37버전이 둘다 깔려있었다. 단순히 두 개가 깔린 것 뿐만 아니라 환경 변수에서 둘다 path에 잡혀있었다! 그렇더라도 다음과 같은 명령어는 실행이 된다. python -m pip install XXX

참고(https://stackoverflow.com/questions/24627525/fatal-error-in-launcher-unable-to-create-process-using-c-program-files-x86)

 

 

 

 

01/02

목표: 접속 중 다른 사용자가 동시 접속했을 때 알려주는 코드 작성하기 (shell script 사용하기)
1) vi .bashrc 를 눌러서 .bashrc 파일에 들어간다. 

2) 맨 아랫줄에 와서 키보드의 i 키를 눌러서 wall "Hi I am `whoami`" 를 적는다.

3) esc를 하고, :wq!로 vi창을 나온다.

4) source .bashrc를 치면 바로 적용이 된다.

=> 이런 식으로 로그인하고 한 번만 실행하고 싶은 내용이 있으면 .bashrc에 저장한다.

 

cf) 스크립트에 잘못 쓴 내용을 지우고 싶을 때는 esc + dd 명령어를 치면 된다.

cf) `는 외부 스크립트를 실행하고 싶을 때 사용할 수 있다.
cf) bashprofile도 아마 그렇게 실행될 것이다.

 

반응형