[AWS] EC2 SDK

당당·2023년 6월 15일
0

AWS

목록 보기
16/24

📔설명

SDKSoftware Development Kit로 AWS를 프로그래밍적으로 제어하기 편리하도록 제공하는 라이브러리들을 뜻한다.

https://aws.amazon.com/ko/developer/tools/

위의 링크에서 언어별 SDK를 확인할 수 있다.


📠PHP를 위한 AWS SDK

👓php 실습환경 구축

Apache, PHP, MySQL이 동작하는 환경을 구축하는 방법을 알아보자.

먼저 EC2php를 설치할 것인데, 이를 위해서 우분투운영체제인 EC2 인스턴스를 하나 생성해주도록 하자.

생성했다. 이제 서버로 접속하자!

$sudo apt-get update;

로 apt의 상태를 최신상태로 업데이트해주자.

그 다음 제일 먼저 웹서버를 설치할 것이다.

$sudo apt-get install apahce2

명령어를 이용해서 apache 웹서버를 설치해주자.

이제 잘 설치가 되었는지 확인하기 위해서, 퍼블릭 도메인으로 접속하자.

인스턴스를 클릭하면 나오는 퍼블릭 DNS로 접속하면 된다.

접속해보면, 성공적으로 작동한다고 알려준다.

이제는 php를 설치해보자.

$sudo apt-get install php

알아서 설치가 된다! 강의 영상에서는 뒤에 5를 적어줬지만, 이제는 지원하지 않는 것 같다.

php가 설치됐는지 확인하기 위해 /var/www/html경로로 cd를 통해 이동해보자.

이 디렉터리에 이제 php파일을 만들어보자.

$sudo nano phpinfo.php
<?php
phpinfo();
?>

안에 위의 내용을 입력해주고 저장해주자.

phpinfo.php가 생성된 것을 볼 수 있다.

이제 생성한 파일에 접근해보자!
주소창에 아까 퍼블릭 dns 뒤에 /phpinfo.php를 추가해주면 된다.

이렇게 뜨고 밑에 각각의 버전 등 php에 관한 정보가 출력된다면 성공한 것이다.

$ sudo rm phpinfo.php

위의 파일은 노출되면 안되기 때문에 명령어를 통해 지워주자!

phpmysql과 같이 쓰니까, mysql도 설치해보자.

$sudo apt-get install mysql-server

그러면 설치가 된다.

$sudo mysql -u root

명령어로 mysql에 접속해주고 비밀번호를 설정해주자.

use mysql;

alter user 'root'@'localhost' identified with mysql_native_password by '원하는 패스워드';

flush privileges;

exit;

명령어를 차례대로 입력해주면

$sudo mysql -u root -p

명령어로 비밀번호를 입력하고 DB에 접속할 수 있다.

mysql 서버에 데이터를 저장 및 수정하려면 mysql monitor라는 프로그램이 필요하다.

$sudo apt-get install mysql-client

이제부터 mysql이라는 명령을 통해서 모니터 프로그램을 사용하여 mysql 서버에 접속할 수 있다.

$mysql -u root -p명령어로 접속해보자.

먼저 데이터베이스를 만들자.

create database o2;

이후 만든 database를 사용하려면

use o2;

를 이용한다.

CREATE TABLE `topic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `author` varchar(30) NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

위 코드를 입력하자!

생성이 잘 됐는지 확인해보면 잘 되어있다!

INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(1, 'About JavaScript', '<h3>Desctiption</h3>\r\n<p>JavaScript  is a dynamic computer programming language. It is most commonly used as part of web browsers, whose implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.</p>\r\n<p>\r\nDespite some naming, syntactic, and standard library similarities, JavaScript and Java are otherwise unrelated and have very different semantics. The syntax of JavaScript is actually derived from C, while the semantics and design are influenced by the Self and Scheme programming languages.\r\n</p>\r\n<h3>See Also</h3>\r\n<ul>\r\n  <li><a href="http://en.wikipedia.org/wiki/Dynamic_HTML">Dynamic HTML and Ajax (programming)</a></li>\r\n  <li><a href="http://en.wikipedia.org/wiki/Web_interoperability">Web interoperability</a></li>\r\n  <li><a href="http://en.wikipedia.org/wiki/Web_accessibility">Web accessibility</a></li>\r\n</ul>\r\n', 'egoing', '2015-03-31 12:14:00');
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(2, 'Variable and Constant', '<h3>Desciption</h3>\r\n\r\nIn computer programming, a variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity or information referred to as a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution.\r\n\r\n<h3>See Also</h3>\r\n<ul>\r\n<li>Non-local variable</li>\r\n<li>Variable interpolation</li>\r\n</ul>\r\n', 'k8805', '2015-05-14 10:04:00');
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(3, 'Opeartor', '<h2>Operator</h2>\r\n<h3>Description</h3>\r\n<p>Programming languages typically support a set of operators: constructs which behave generally like functions, but which differ syntactically or semantically from usual functions</p>\r\n<p>Common simple examples include arithmetic (addition with +, comparison with >) and logical operations (such as AND or &&). </p>\r\n', 'egoing', '2015-06-18 05:00:00');
INSERT INTO `topic` (`id`, `title`, `description`, `author`, `created`) VALUES(4, 'Conditional', '<h3>Description</h3>\r\n<p>In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.</p>\r\n<p>In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.</p>\r\n<h3>See Also</h3>\r\n<ul>\r\n<li><a href="http://en.wikipedia.org/wiki/Branch_(computer_science)" title="Branch (computer science)">Branch (computer science)</a></li>\r\n<li><a href="http://en.wikipedia.org/wiki/Conditional_compilation" title="Conditional compilation">Conditional compilation</a></li>\r\n<li><a href="http://en.wikipedia.org/wiki/Dynamic_dispatch" title="Dynamic dispatch">Dynamic dispatch</a> for another way to make execution choices</li>\r\n<li><a href="http://en.wikipedia.org/wiki/McCarthy_Formalism" title="McCarthy Formalism">McCarthy Formalism</a> for history and historical references</li>\r\n<li><a href="http://en.wikipedia.org/wiki/Named_condition" title="Named condition" class="mw-redirect">Named condition</a></li>\r\n<li><a href="http://en.wikipedia.org/wiki/Test_(Unix)" title="Test (Unix)">Test (Unix)</a></li>\r\n<li><a href="http://en.wikipedia.org/wiki/Yoda_conditions" title="Yoda conditions">Yoda conditions</a></li>\r\n</ul>', 'c2', '2015-07-25 00:00:00');

위의 코드로 데이터를 삽입하자!

잘 입력된 것을 확인할 수 있다!

이제 exit;으로 빠져나가서 php코드를 작성해보자.

먼저, php와 mysql을 연동해야 한다.

$sudo apt-get install php-mysql

연동을 했으면, 아파치를 껐다 켜야한다.

$sudo service apache2 restart

mysql과 연동되는 php를 하나 만들어보자.

$sudo nano index.php
<?php
$conn = mysqli_connect('localhost', 'root', '비밀번호', 'o2');
$result = mysqli_query($conn, 'SELECT * FROM topic WHERE id=1');
$row = mysqli_fetch_assoc($result);
var_dump($row['title']);
?>

id=1인 것의 title을 출력하는 것이다.

우리의 퍼블릭 dns 뒤에 /index.php를 붙이면 위 처럼 출력된다.

🎨시작하기

php를 이용해서 aws의 인프라를 제어하는 방법을 알아보자.
AWS SDK for PHP라는 소프트웨어가 필요하다.

https://aws.amazon.com/ko/sdk-for-php/

시작하기 부분을 눌러보자.

이것은 우리가 sdk를 설치하기 위한 방법이 나와있다.

여기서 Composer이란 php로 웹 개발을 할 때 다른 사람이 만든 여러가지 소프트웨어들을 사용하는데, 그 소스코드를 다운받고 다운받은 것을 어딘가에 풀어놓고 그것을 사용하는 것이 원래 방법이었다면 최근에는 패키지 매니저를 이용하여 라이브러리들을 표준화된 방식으로 사용할 수 있도록 해주는 것이다. 즉, 컴포저를 사용하면 명령어 한 줄만 입력하면 컴포저가 알아서 다운받아준다.

먼저, 컴포저를 사용하려면 다운을 받아야한다.

https://getcomposer.org/download/

위 사이트로 접속해서 composer를 설치하자.

생성한 인스턴스(우분투)로 접속하자.

$cd /var/www/html

웹 애플리케이션이 위치하는 디렉터리로 이동을 하자.

$sudo php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
$sudo php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
$sudo php composer-setup.php
$sudo php -r "unlink('composer-setup.php');"

위의 명령어를 입력하자.

그러면 설치가 된다.

잘 설치된 것도 확인할 수 있다! 이제 저 프로그램을 이용해보자!

$php -d memory_limit=-1 composer.phar require aws/aws-sdk-php

aws sdk for php를 설치하는 명령어이다.

확인해보면 아까 없던 파일들이 생겨져있다.

<?php
   require 'vendor/autoload.php';
?>

위의 소스코드를

$vi ec2.php

라고 명령어를 친 후 그곳에 붙여넣기를 해준다.

위의 내용을 입력하고 esc를 눌러준 후 ZZ를 눌러 밖으로 나가주자.

👝코딩하기

아까 본 메뉴얼 페이지를 확인해보자.

sdk를 사용하는 사례들을 보여주는 것이다.

하지만, 우리는 인증과 같은 부분을 해결해야 하기 때문에,

Configuration부분을 눌러보자. 그 중 Credentials를 누르자.

왼쪽에 인증받는 방법이 여러개 있는데, 처음은 환경변수를 이용하는 것이다.

가장 권장되는 방법은 두번째 방법인 IAM을 사용하는 것이다.

그 다음은 aws에서 지정해둔 디렉터리에 특정한 파일명으로 만들면 sdk가 알아서 파일이 있는지 체크하는 방법도 있다.

마지막으로 하드코딩 하는 방법이 있다.

여기서 세번째 방법으로 해보자!

IAM을 클릭하고,

User로 들어가자.

새로운 사용자를 추가하도록 하자!

여기서 계속 다음을 누른 후,

액세스 키 만들기를 해서 cli를 선택한다. 이 창은 유저를 생성한 후, 유저 이름을 클릭해서 보안메뉴로 들어가면 볼 수 있다.

그러면 액세스 키와 비밀 액세스 키가 생성이 된다.

우리 인스턴스의 홈 디렉터리로 이동하자.

$mkdir .aws

aws라는 디렉터리를 생성해주자.

그 후 cd명령어로 aws에 들어가자.

$ vi credentials

파일을 만들자.

[default]
aws_access_key_id = IAM id
aws_secret_access_key = IAM password

여기에 아까 위에서 발급받은 아이디와 비밀번호를 입력하자.

그다음 저장하고 나와주자!

다시 /var/www/html 로 이동하자.

그리고 ec2.php파일을 다시 편집하자! (vi)사용

<?php
require 'vendor/autoload.php';

위의 코드를 사용하면 된다.

php를 통해서 프로그래밍적으로 목록을 출력하는 코드를 작성할 것이다.

https://docs.aws.amazon.com/sdk-for-php/index.html

그전에 위의 사이트에 들어가서, API Reference라는 것에 들어가자.

우리의 관심사는 EC2 이므로 ec2를 누르자.

여기에 있는 Aws\Ec2\Ec2Client를 복사해서 객체를 만들것이다.

<?php
require 'vendor/autoload.php';
$param = Array();
$Aws = new Aws\Ec2\Ec2Client($param);
var_dump($Aws);

파일의 내용은 이렇게 된다.

저장하고 나오자!

그 다음

$php ec2.php

명령어를 입력하면,

버전과 리전에 대한 정보가 반드시 있어야 된다고 적혀있다.
ap-northeast-2를 복사해주고

<?php
require 'vendor/autoload.php';
$param = Array('region'=>'ap-northeast-2');
$Aws = new Aws\Ec2\Ec2Client($param);
var_dump($Aws);

param의 뒤에 작성해주자.

다시 한번 php ec2.php를 실행해보면 이제 region은 빠져있고 version만 나온다.

그리고 지금 보니 내가 사용하는 버전은 2016-11-15이다.

다시 vi편집기로 ec2.php를 편집하자.

<?php
require 'vendor/autoload.php';
$param = Array('region'=>'ap-northeast-2', 'version'=>'2016-11-15','profile'=>'dafulat');
$Aws = new Aws\Ec2\Ec2Client($param);
var_dump($Aws);

최종적으로 진짜 최종으로 이렇게 된다.

profile부분을 추가 안해주어서 오류가 발생했었다.

https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#describeinstances

이젠 DescribeInstances라는 메소드를 사용하는 방법이 나온다.

다시 vi 편집기로 ec2.php파일을 편집하자.

<?php
require 'vendor/autoload.php';
$param = Array('region'=>'ap-northeast-2', 'version'=>'2016-11-15','profile'=>'default');
$ec2 = new Aws\Ec2\Ec2Client($param);
$instances=$ec2->describeInstances([]);
print($instances);
?>

위처럼 내용을 바꿔주자.

그러면 에러가 뜨는데, 우리가 만든 유저의 권한을 셋팅해주자.

먼저 그룹을 사용해주고 그룹에 권한을 부여한 후, 그 그룹을 사용자에게 부여하면 된다.

$sudo apt install php-xml

위의 명령어를 실행시켜 php-xml을 설치해준 후,
$php ec2.php명령어를 실행하면, 잘 출력이 된다.

<?php
require 'vendor/autoload.php';
$param = Array('region'=>'ap-northeast-2', 'version'=>'2016-11-15','profile'=>'default');
$ec2 = new Aws\Ec2\Ec2Client($param);
$instances=$ec2->describeInstances([]);
print($instances['Reservations'][0]['Instances'][0]['NetworkInterfaces'][0]['Association']['PublicIp']);
?>

이제 원하는 정보만 출력해보자.

실행시키면 pulbic ip만을 출력하는것을 확인할 수 있다.


🍕nodejs를 위한 AWS SDK

🍔nodejs 실습환경 구축

먼저, nodejs를 설치해야 한다.

https://nodejs.org/ko/download

위의 사이트에서 다운받을 수 있는데, 우리는 ubuntu를 사용하니

위의 패키지 관리자를 통한 node.js 설치를 할 것이다.

우리는 밑줄 친 것을 설치할 것이다.

https://github.com/nodesource/distributions

그러면 위와 같은 깃허브 주소가 있다.

README.md에서 설치하는 방법에 대한 것이 나와있다.

먼저, 우리의 ec2 인스턴스에 접속하고, 설치하자!

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - &&\
sudo apt-get install -y nodejs

전체를 복사해서 붙여넣기 하면, 뭔가 촤라락 설치가 된다.

그 다음 분홍색 창이 뜨면 그냥 계속 엔터만 쳐주자.

node -v명령어로 nodejs가 잘 설치된 것을 알 수 있다!

간단히 nodejs 애플리케이션을 만들어보자.

$cd /opt

/opt디렉토리로 이동하자.

$ sudo mkdir o2
$ cd o2

o2라는 디렉터리를 생성하고, 그 디렉터리로 이동하자!

$ sudo chown ubuntu .

현재 디렉터리의 오너를 ubuntu사용자로 변경한다.

$ npm init

위의 명령어로 npm의 기본 셋팅을 해주자. 계속 엔터를 치면 된다.

package.json이란 파일이 생겼는데, 우리가 진행할 프로젝트에 대한 기본적인 정보가 들어가있는 상태이다.

일반적으로 nodejs로 웹애플리케이션 구축을 한다면, 가장 잘 사용하는 것이 express이다.

npm install express

express를 설치해주자.

그러면 node_modules라는 것이 생성되어있다.

한번 웹 애플리케이션을 만들어보자.

$ vi app.js
var express=require('express');
var app=express();
app.get('/',function(req,res){
        res.send('Hello world');
});
app.listen(80, function(){
        console.log('Connected 80 port');
});

app.get('/',function(){})는 app안에서 get을 해서, /로 최상위 디렉터리에 접근하는 요청을 처리하는 코드를 만드는 것이다.

누군가가 우리의 nodejs 프로젝트 앱에 접속했을 때, /로 바로 접근을 했다면, function안의 코드가 실행이 되도록 약속이 된다.

function의 첫 번째 인자는 req로 요청에 대한 정보를 담는 객체이고,
두 번째는 응답을 할 때 시스템에게 보내주는 res객체이다.

그리고 res.send();는 사용자가 root로 들어왔을 때, hello world를 출력해주는 것이다.

그리고, 우리가 만드는 nodejs가 웹서버로도 작동하게 하려면,
app.listen(80, 을 통해 사용자가 80번 포트로 접속하면, 반응하도록 해준다.

그 다음 저장을 해주고 나가자!

$node app.js

를 실행해주자!
그러면, 에러가 난다..

왜냐하면 1024번 포트 이하의 포트는 root권한으로만 사용할 수 있기 때문이다.

그리고 이전까지 다 따라온 사람이라면, $ sudo node app.js 명령어를 실행해도 에러가 날 것이다. 이미 80번 포트가 실행되고 있기 때문이다.

이를 해결하기 위해서 80번 포트를 죽인다.

$ sudo apt install net-tools
$ netstat -nap|grep 80
$ sudo kill $(sudo lsof -t -i:80)
$sudo node app.js

이제 잘 연결되는 것을 확인할 수 있다.

잘 동작하는지 확인하기 위해서 ec2의 public dns로 접속하자.

잘 출력이 된다!

🍳시작하기

먼저, 검색을 하나 해보자.

제일 위 사이트를 눌러서

https://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html

로 접속하자.

그리고, 오른쪽의 1단계로 이동하면,

nodejs에서 aws-sdk를 사용하기 위한 준비작업이 있다.

npm install aws-sdk --save

위의 명령어를 먼저 /opt/o2에서 실행시켜보자.

--save라고 하면 package.json에 기록을 하는 것이다.

그리고

npm install uuid --save

uuid도 설치해주자.

var AWS = require("aws-sdk");

aws의 라이브러리를 가지고 와서 사용할 수 있는 AWS 변수를 얻게 된다.

sudo vi app.js로 app.js를 수정하자.

var express=require('express');
var app=express();
var AWS = require("aws-sdk");
app.get('/',function(req,res){
        res.send('Hello world');
});
app.listen(80, function(){
        console.log('Connected 80 port');
});

AWS라는 변수를 통해서 aws의 인프라를 제어할 수 있는 기본적인 준비를 끝낸 것이다.

오른쪽 2단계를 눌러보면, 위처럼 나온다.

위의 php 때 처럼 ~/.aws/credentails을 이용해서 사용해보자.

mkdir ~/.aws

이미 나는 aws 파일이 생성되어있다.

vi ~/.aws/credentials

를 통해 편집기로 열면, 이전에 php때문에 했던 것이 남아있다.

[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

위의 내용을 먼저 붙여넣기 하자.

이 다음 IAM서비스에 들어가자.

그다음

사용자로 들어가서 새로운 사용자를 추가할 것이다.

nodejs로 이름을 정하고, 다음을 누르자.

그다음, 만들어둔 사용자를 클릭하면

위처럼 액세스 키를 생성할 수 있는 곳이 있다.
생성하자!

CLI를 선택하고 다음을 누르면 된다.

그러면 3단계에서 액세스 키비밀 액세스 키를 알려준다.
이것을 아까 credentials에 입력하는 것이다.

AWS.config.region='ap-northeast-2';

위의 내용을 복사해서 app.js에 붙여넣도록 하자.

var express=require('express');
var app=express();
var AWS = require("aws-sdk");
AWS.config.region='ap-northeast-2';
app.get('/',function(req,res){
        res.send('Hello world');
});
app.listen(80, function(){
        console.log('Connected 80 port');
});

ec2를 제어할 때는 AWS.EC2()를 이용하는 것을 알 수 있다.
그러니,

var ec2=new AWS.EC2();

위의 내용을 app.js에 붙여넣자.

var express=require('express');
var app=express();
var AWS = require("aws-sdk");
AWS.config.region='ap-northeast-2';
var ec2=new AWS.EC2();
app.get('/',function(req,res){
        res.send('Hello world');
});
app.listen(80, function(){
        console.log('Connected 80 port');
});

현재, 우리가 생성한 인스턴스들의 목록을 알아보도록 하자.

그럴려면 describeInstances 메소드를 이용하면 된다.
위의 예제를 보면서 차근차근 따라해보도록 하자!

var express=require('express');
var app=express();
var AWS = require("aws-sdk");
AWS.config.region='ap-northeast-2';
var ec2=new AWS.EC2();
ec2.describeInstances({},function(err,data){
        console.log(data);
});
app.get('/',function(req,res){
        res.send('Hello world');
});
//app.listen(80, function(){
//      console.log('Connected 80 port');
//});

위의 명령어로 ec2객체를 만들어주자.

$node app.js

실행하면, null이 뜨는데, 그 이유를 알기 위해
console.log(data)위에 console.log(err)를 추가해주자.

그러면, 우리가 아까 생성한 유저는 권한이 없는 사용자만 만든 것이므로,

AmazonEC2FullAccess를 그룹에 추가해주면 된다.

그리고 나서, $node app.js를 실행해주면

위처럼 뜬다.
이것을 웹을 통해서 출력한다고 해보자.

var express=require('express');
var app=express();
var AWS = require("aws-sdk");
AWS.config.update({region: 'ap-northeast-2'});
var ec2=new AWS.EC2({apiVersion: '2016-11-15'});
app.get('/',function(req,res){
        res.send('Hello world');
});
app.get('/ec2',function(req,res){
        ec2.describeInstances({},function(err,data){
                res.json(data);
        });
});
app.listen(80, function(){
        console.log('Connected 80 port');
});

그러면, 아까 app.js에 주석처리 한 부분을 제거해주고,
사용자가 /ec2로 접속하면 data에 담긴 instance들의 목록을 바로
웹을 통해서 출력하도록 하는 것이다.

$ node app.js

위의 명령어를 친 다음 public dns로 접속해주자!

그러면 엄청 많은 무언가가 출력된다.

그러면 성공한것이다!! 끝!

profile
MySQL DBA 신입 지원

0개의 댓글