[AWS] 보유중인 route53 호스트 정보를 기반으로 레코드 정보 읽어오기

AWS 에서, ELB 나 클라우드프론트 등 제공되는 서비스의 영역에서,

고정된 EIP가 아닌 경우 해당 호스트에 매핑되어 있는, 아이피 정보는 생각보다 빈번하게 변경됩니다.

 

관련하여, 아래와 같이 보유중인 호스트존 정보를 읽고, 해당 레코드 타입의 도메인의 아이피를 업데이트 할 수 있는 방법을 정리합니다.

해당 스크립트는 awscli를 이용합니다.

코드 관련 에디터툴을 적절한 것을 아직 찾지 못해 보기가 불편한점 양해부탁드립니다. ^^;;;

#!/bin/bash

# SCL python27 project enable

source /opt/rh/python27/enable

 

#qury all HOSTZONEID

ZONEIDS=`aws –profile dnsview route53 list-hosted-zones-by-name –query “HostedZones[].Id” –output text`

 

for ZONEID in ${ZONEIDS[@]}

do

if [ “$ZONEID” != “/hostedzone/Z2NKR4123123123” ];

then

#============ QUERY FOR ALL HOSTZONE ID in OUR ACCOUNT ===================

#A record domain query

afqdn=`aws –profile dnsview route53 list-resource-record-sets –hosted-zone-id ${ZONEID} –output text –query “ResourceRecordSets[?Type==’A’].Name”`

for domain in ${afqdn[@]}

do

ips=`dig +short $domain`;

echo -e “$domain \t(Type A)”;

for ip in ${ips[@]}

do

echo -e “\t$ip”;

done

done

#CNAME record domain query

cfqdn=`aws –profile dnsview route53 list-resource-record-sets –hosted-zone-id ${ZONEID} –output text –query “ResourceRecordSets[?Type==’CNAME’].Name”`

# Unset Variable

unset domain;

unset ips;

unset ip;

for domain in ${cfqdn[@]}

do

ips=`dig +short $domain`;

echo -e “$domain \t(Type CNAME)”;

for ip in ${ips[@]}

do

echo -e “\t$ip”;

done

done

#============ QUERY FOR ALL HOSTZONE ID in OUR ACCOUNT ===================

else

echo -e “\n”;

fi

done

AWS S3 bucket Explorer

%ec%8a%a4%ed%81%ac%eb%a6%b0%ec%83%b7-2016-10-21-%ec%98%a4%ed%9b%84-5-38-15

 

git 저장소 : https://github.com/awslabs/aws-js-s3-explorer

S3 내용을 보기 좋게 변환하여, 리스트 형식으로 보여줄 수 있다. 매우 좋은 기능

백업 용도로 S3많이 이용하는데. 누군가에게 보기좋게 가이드하기 편한 방법인 것 같다.

 

해당 깃 프로젝트로 가면 설정방법이 상세하게 있다.

이중 권한 및 cors 설정을 해주면 된다.

방법은 아래와 같다.

 

퍼미션

{

“Version”: “2012-10-17”,

“Statement”: [

{

“Sid”: “PublicListGet”,

“Effect”: “Allow”,

“Principal”: “*”,

“Action”: [

“s3:List*”,

“s3:Get*”

],

“Resource”: [

“arn:aws:s3:::BUCKET-NAME”,

“arn:aws:s3:::BUCKET-NAME/*”

]

}

]

}

 

 

CORS 설정

<CORSConfiguration xmlns=”http://s3.amazonaws.com/doc/2006-03-01/”>  <CORSRule>    <AllowedOrigin>http://BUCKET-NAME.s3.amazonaws.com</AllowedOrigin>    <AllowedMethod>HEAD</AllowedMethod>    <AllowedMethod>GET</AllowedMethod>    <AllowedHeader>*</AllowedHeader>    <ExposeHeader>ETag</ExposeHeader>    <ExposeHeader>x-amz-meta-custom-header</ExposeHeader>  </CORSRule></CORSConfiguration>

 

AWS EIP 서브넷별 고정할당

아마존을 운영하다보면 상태 유지를 위한 오토스케일링으로 desire & Min/Max 수치를 고정하여,

해당 서버를 유지해야 할 필요가 있다.

 

이런 경우, Nat가 아닌 해당 서버의 고정아이피를 할당하는 방법이 필요하게 되어 아래와 같이 스크립트를 진행하게 되었다.

 

상황은 두개의 AZ 에 각각 서버가 위치하고, 인스턴스 헬스체크가 실패하는 경우 신규 인스턴스로 교체 되며, 기존에 사용하던 EIP를 고정적으로 할당하는 방법에 대한 설명이다.

 

#!/bin/bash -ex
## made by hong

# Enable AWS account
export AWS_ACCESS_KEY_ID=”아마존 엑세스 키”
export AWS_SECRET_ACCESS_KEY=”아마존 시크릿 키”

# Availability Zone Elastic IP Azone Bzone DEFINE
EIPA=”서브넷 A에 할당할  EIP아이디 (eipalloc-xxxx1234)”
EIPB=”서브넷 B에 할당할  EIP아이디 (eipalloc-xxxx5678)”

# Get Self Instance infomation
INSTANCEID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e ‘s/.$//’)
AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)

if [ “$AZ” == “ap-northeast-1a” ]
then
    aws –region ${REGION} ec2 associate-address –instance-id ${INSTANCEID} –allocation-id ${EIPA}
elif [“$AZ” == “ap-northeast-1b” ]
then
    aws –region ${REGION} ec2 associate-address –instance-id ${INSTANCEID} –allocation-id ${EIPB}
else 
    echo “no define AZ your zone is ${AZ}”
    exit 2
fi

exit 0

 

위와 같은 스크립트가, POST로 실행되도록 설정을 해놓는다.

서버가 배포되면서 해당 스크립트가 실행되면 기존에 제거된 인스턴스에서 반환된 EIP를 다시 고정적으로 받아오게 된다.

[aws] AWS CLI를 이용해서 EC2 정보 query 하기

# Security groups that contain 0.0.0.0/0 rules

aws ec2 describe-security-groups –filters Name=ip-permission.cidr,Values=0.0.0.0/0 –output=text | grep SECURITYGROUPS

# Security groups for ElasticSearch

aws ec2 describe-security-groups –filters Name=ip-permission.from-port,Values=9200 –output=text | grep SECURITYGROUPS

# Search last 10,000/1MB of CloudTrail logs for ‘AccessDenied’ (removed AWS account number from stream name)

aws logs get-log-events –log-group-name CloudTrail/DefaultLogGroup –log-stream-name 000000000000_CloudTrail_eu-west-1 | grep AccessDenied

# Get number of AWS API calls in time period (assumes a Cloudwatch Logs ‘catch-all’ filter and metric has been created against CloudTrail logs)

aws cloudwatch get-metric-statistics –namespace LogMetrics –metric-name AllApiCallsCount –period 60 –statistics Sum –start-time 2015-04-15T13:40:00 –end-time 2015-04-15T13:55:00

# Security groups with particular name

aws ec2 describe-security-groups –filters Name=group-name,Values=*external* –output=text | grep SECURITYGROUPS

# Instance IDs on known subnet ranges

aws ec2 describe-instances –filters Name=“private-ip-address”,Values=“10.100.1.*”,“10.100.2.*” –query “Reservations[*].Instances[*].InstanceId”

# Count instance types

aws ec2 describe-instances –query ‘Reservations[*].Instances[*].InstanceType’ –output=text | sort | uniq -c | sort -r

# ELB summaries

aws elb describe-load-balancers –query ‘LoadBalancerDescriptions[*].{Name:DNSName,Instances:Instances[*],SecurityGroups:SecurityGroups[*],Listeners:ListenerDescriptions[*].Listener.LoadBalancerPort}’

# Elastic IP summaries

aws ec2 describe-addresses –query “Addresses[*].{PublicIp:PublicIp,InstanceId:InstanceId}”

# Show scheduled events

aws ec2 describe-instance-status –filters Name=event.code,Values=instance-reboot,system-reboot,system-maintenance,instance-retirement,instance-stop –query “InstanceStatuses[*].{InstanceId:InstanceId,Event:[Events[*].Code,Events[*].NotBefore,Events[*].Description]}”

# Show last 10 security group ingress changes

aws cloudtrail lookup-events –lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress –max-results 10

# Show IDs and names of instances in specified subnets

aws ec2 describe-instances –filters Name=“subnet-id”,Values=“subnet-<id>”,“subnet-<id>” \

–query “Reservations[*].Instances[*].{InstanceId:InstanceId,SubnetId:SubnetId,Tags:[Tags[*].Value],PrivateIpAddress:PrivateIpAddress,\

PublicIpAddress:PublicIpAddress,SecurityGroupNames:[SecurityGroups[*].GroupName],SecurityGroupIds:[SecurityGroups[*].GroupId]}”

[aws] s3 CORS bucket policy

S3 origin bucket 의 CORS 설정을 아래와 같이 진행하였습니다.

예) 특정 도메인에 모든 메소드 허용 그외 도메인은 겟,헤드만 허용  버킷 폴리시

// *.hongstalk.com 에서 메소드 허용, 그외 GET / HEAD만 허용

// 변경시 적용은 거의 딜레이없이 즉시 적용됨.

<?xml version=”1.0” encoding=”UTF-8”?>

<CORSConfiguration xmlns=”http://s3.amazonaws.com/doc/2006-03-01/“>

<CORSRule>

<AllowedOrigin>*.hongstalk.com</AllowedOrigin>

<AllowedMethod>GET</AllowedMethod>

<AllowedMethod>PUT</AllowedMethod>

<AllowedMethod>POST</AllowedMethod>

<AllowedMethod>DELETE</AllowedMethod>

<AllowedMethod>HEAD</AllowedMethod>

<MaxAgeSeconds>3000</MaxAgeSeconds>

<AllowedHeader>*</AllowedHeader>

</CORSRule>

<CORSRule>

<AllowedOrigin>*</AllowedOrigin>

<AllowedMethod>GET</AllowedMethod>

<AllowedMethod>HEAD</AllowedMethod>

</CORSRule>

</CORSConfiguration>

 

 

적용 여부 확인 방법

// request header 에 origin 이 설정되지 않는 경우 허용하지 않음.

// CURL을 통해서 임의로 header를 origin: 값을 추가하고 확인 필요함.

// 참고 : 위 설정과 같이 *.hongstalk.com 인경우 hongstalk.com은 예외로 봄.

[aws] S3 버킷 접근 제한 (IAM – policy 이용)

아래와 같이 폴리시를 생성하여 유저에 attach 시킴

{

    “Version”: “2012-10-17”,

    “Statement”: [

        {

            “Effect”: “Allow”,

            “Action”: “s3:*”,

            “Resource”: [

                “arn:aws:s3:::버킷1”,

                “arn:aws:s3:::버킷1/*”,

                “arn:aws:s3:::버킷2”,

                “arn:aws:s3:::버킷2/*”

            ]

        }

        ]

}

위 예제에 사용되는 형태는 Json type이며, 버킷1 과 버킷2 의 접근을 허용함

[aws] sriov (enhanced network enable)

aws –profile sungho ec2 modify-instance-attribute –instance-id i-ab1234cd –sriov-net-support simple

 

 

aws ec2 describe-instance-attribute –instance-id i-ab1234cd –attribute sriovNetSupport

——————————

|  DescribeInstanceAttribute |

+————-+————–+

|  InstanceId |  i-ab1234cd  |

+————-+————–+

aws ec2 modify-instance-attribute –instance-id i-ab1234cd –sriov-net-support simple

###      적용 시 아무 메시지도 나타나지 않는다!    ###

aws ec2 describe-instance-attribute –instance-id i-ab1234cd –attribute sriovNetSupport

——————————

|  DescribeInstanceAttribute |

+————-+————–+

|  InstanceId |  i-ab1234cd  |

+————-+————–+

||      SriovNetSupport     ||

|+———–+————–+|

||  Value    |  simple      ||

|+———–+————–+|

[root@ip-10-11-20-10 temp_aws_scripts_make_instance]#

 

 

 

 

해당 이미지를 통해 생성한 AMI에서는 아래와 같은 명령어를 통해서 적용 여부를 확인할 수 있다.

aws ec2 describe-image-attribute –image-id ami-ab1234cd –attribute sriovNetSupport

—————————–

|  DescribeImageAttribute   |

+———-+—————-+

|  ImageId |  ami-ab1234cd  |

+———-+—————-+

||     SriovNetSupport     ||

|+———–+————-+|

||  Value    |  simple     ||

|+———–+————-+|

 

[aws] elb

ELB에서 사용하는 SSL Offloading 방식인 인증서 추가 과정을 기술한다.

wild.hongstalk.com 를 이용하기 위해 다음과 같은 사전 작업이 필요하다.

) ELB에서 SSL 인증서 등록시 PEM 방식만을 지원합니다.

전달받은 iam0.co.kr 인증서를 가지고 PEM 전환하는법

에쎌!

1

2

3

4

5

6

7

8

9

10

11

12

# public key PEM 변경

openssl x509 –in cert.pem -out cert_pem.pem -outform PEM

# bundle-ca PEM 변경 

openssl x509 –in True\ Business-intermediate.pem -out bundle_pem.pem -outform PEM

# private key 암호 제거 

openssl rsa –in key.pem -out nopasswd_key.pem

..

Enter pass phrase for key.pem : ********

writing RSA key

그후 ELB 생성 시 해당 PEM 파일의 내용을 복사 붙여넣기 하여 입력하면 인증서가 등록된다.!

AWS cloudfront

아마존 클라우드프론트는 설정 및 사용(비용)의 편의성이 좋다.

 

 

다만 컨텐츠의 캐싱타임이 최소1시간에서 최대 24시간을 필요로 하는점과 

이미 각 엣지에 distribution 된 (캐싱된) 데이터를 다시 재활용하기 위해서는 

 

해당 컨텐츠를 invailidations 해줘야 하는 것이 불편하다.

 

추가로 invalidation 을 해줄수 있는 objects 는 한달에 최대 1000개이며, 이를 넘길 시 

하나의 object 당 0.005 USD 가 과금된다.