기본 설정

1.1 기본 OS 설정

– ROOT 암호 설정
– HostName 설정
– 시간설정
– 작업 history 설정

## Amazon Linux 접속 ##
ssh ec2-user@13.125.137.26
## root 암호 설정 ##
[ec2-user@ip-10-200-1-88 ~]$ sudo passwd
Changing password for user root.
New password: root암호
Retype new password: root암호
## hostname 설정 ##
[root@ip-10-200-1-88 ~]# hostnamectl set-hostname comtec-web-test
[root@ip-10-200-1-88 ~]# systemctl restart systemd-logind.service
[root@ip-10-200-1-88 ~]# vi /etc/hosts
127.0.0.1 comtec-web-test
10.200.1.88 comtec-web-test
:wq
[root@ip-10-200-1-88 ~]# exit
## 재 접속 ##
ssh ec2-user@13.125.137.26
[ec2-user@comtec-web-test ~]$
## 업데이트 ##
[root@comtec-web-test ~]# yum update
## 시간 설정 ##
[root@comtec-web-test ~]# date
Thu Jul  1 02:17:03 UTC 2021
[root@comtec-web-test ~]# vi /etc/sysconfig/clock
ZONE="Asia/Seoul"
UTC=true
:wq
[root@comtec-web-test ~]# ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
[root@comtec-web-test ~]# date
Thu Jul  1 11:18:11 KST 2021
## history 양식 및 저장 사이즈변경 ##
[root@comtec-web-test ~]# history
    1  yum update
[root@comtec-web-test ~]# vi /etc/profile # 추가
HISTTIMEFORMAT="%Y-%m-%d [%H:%M:%S]"
export HISTTIMEFORMAT
HISTFILESIZE=10000
HISTSIZE=10000
:wq
[root@comtec-web-test ~]# source /etc/profile
[root@comtec-web-test ~]# history
    1  2021-07-01 [11:12:43] yum update
[root@comtec-web-test ~]# echo $HISTSIZE
10000

1.2 Swap Memory 설정

SWAP은 시스템 메모리가 부족할 경우 하드디스크의 일부 공간을 활용하여 작업을 계속 진행할 수 있도록 도와주는 영역입니다.
SWAP의 크기는 보통 메모리 크기의 2배 또는 그 이상(최소256MB)으로 지정하는 것을 권장하고 있습니다.

[root@comtec-web-test /]# free -m
              total        used        free      shared  buff/cache   available
Mem:            479          73          15           0         390         393
Swap:             0           0           0
[root@comtec-web-test ~]# sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 14.7847 s, 72.6 MB/s
[root@comtec-web-test ~]# ls -lrt /swapfile
-rw-r--r-- 1 root root 1073741824 Jul  1 14:21 /swapfile
[root@comtec-web-test ~]# mkswap /swapfile
mkswap: /swapfile: insecure permissions 0644, 0600 suggested.
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=4076ece8-04f5-4a4b-8f1a-f8a53ceb3f00
[root@comtec-web-test ~]# swapon /swapfile
swapon: /swapfile: insecure permissions 0644, 0600 suggested.
[root@comtec-web-test ~]# chmod 600 /swapfile
[root@comtec-web-test ~]# swapon -s
Filename				Type		Size	Used	Priority
/swapfile                              	file    	1048572	0	-2
[root@comtec-web-test ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:            479          73          14           0         392         393
Swap:          1023           0        1023
[root@comtec-web-test ~]# vi /etc/fstab
/swapfile swap swap defaults 0 0 <- 추가

1.3 사용자 추가 및 삭제

## 추가 ##
[ec2-user@comtec-web-test ~]# sudo adduser comtec
[ec2-user@comtec-web-test ~]# ls -al /home/
total 0
drwxr-xr-x  4 root     root      36 Jul  1 13:09 .
dr-xr-xr-x 18 root     root     257 Jul  1 10:57 ..
drwx------  2 comtec   comtec    62 Jul  1 13:09 comtec
drwx------  3 ec2-user ec2-user 111 Jul  1 11:37 ec2-user
## 삭제 ##
[root@comtec-web-test .ssh]# userdel -r comtec
[root@comtec-web-test .ssh]# ls -lrt /home/
total 0
drwx------ 3 ec2-user ec2-user 111 Jul  1 11:37 ec2-user

1.4 사용자 key 추가(옵션)


## 접속key 생성 ##
[root@comtec-web-test ~]# ssh-keygen -t rsa -f ~/.ssh/comtec
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/comtec):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/comtec.
Your public key has been saved in /root/.ssh/comtec.pub.
The key fingerprint is:
SHA256:qhsWhEPuqkXUyozwYE30Hc2qI3TgnT7F2J0wo9krvOE root@comtec-web-test
The key's randomart image is:
+---[RSA 2048]----+
|  oo   .o        |
| oo+. .+.o       |
|o.*.=.O.* .      |
|oO * B * o       |
|. O = o S        |
| o . X o         |
|. . = B          |
|.. . E           |
|.   o.           |
+----[SHA256]-----+
[root@comtec-web-test .ssh]# ls -lrt
total 12
-rw------- 1 root root  554 Jul  1 10:57 authorized_keys
-rw-r--r-- 1 root root  402 Jul  1 13:18 comtec.pub
-rw------- 1 root root 1679 Jul  1 13:18 comtec
[root@comtec-web-test ~]# mkdir /home/comtec/.ssh
[root@comtec-web-test ~]# chmod 700 /home/comtec/.ssh
[root@comtec-web-test ~]# touch /home/comtec/.ssh/authorized_keys
[root@comtec-web-test ~]# chmod 600 /home/comtec/.ssh/authorized_keys
[root@comtec-web-test ~]# chown comtec.comtec -R /home/comtec/.ssh
[root@comtec-web-test ~]# cat ~/.ssh/comtec.pub >> /home/comtec/.ssh/authorized_keys

2. EBS 볼륨 추가

[root@comtec-web-test ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        230M     0  230M   0% /dev
tmpfs           240M     0  240M   0% /dev/shm
tmpfs           240M  400K  240M   1% /run
tmpfs           240M     0  240M   0% /sys/fs/cgroup
/dev/xvda1      8.0G  2.5G  5.6G  31% /
tmpfs            48M     0   48M   0% /run/user/1000
[root@comtec-web-test ~]# lsblk
NAME    MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda    202:0    0   8G  0 disk
└─xvda1 202:1    0   8G  0 part /
[root@comtec-web-test ~]# aws configure
AWS Access Key ID [None]: xxxx
AWS Secret Access Key [None]: xxx
Default region name [None]: ap-northeast-2
Default output format [None]:
## 1G 볼륨 생성 ##
[root@comtec-web-test ~]# aws ec2 create-volume --volume-type gp3 --size 1 --availability-zone ap-northeast-2a --tag-specifications 'ResourceType=volume,Tags=[{Key=Name,Value=comtec-web-test},{Key=Service,Value=Prod}]'
## 볼륨 인스턴스 연결 ##
[root@comtec-web-test ~]# aws ec2 attach-volume --instance-id i-08b94277de6ec7210 --volume-id vol-02d014ffefae1bf56 --device /dev/sdf
[root@comtec-web-test ~]# lsblk
NAME    MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda    202:0    0   8G  0 disk
└─xvda1 202:1    0   8G  0 part /
xvdf    202:80   0   1G  0 disk
## 폴더 생성 및 마운트 ##
[root@comtec-web-test ~]# mkdir /backup
[root@comtec-web-test ~]# mkfs -t xfs /dev/xvdf
meta-data=/dev/xvdf              isize=512    agcount=4, agsize=65536 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=0
data     =                       bsize=4096   blocks=262144, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal log           bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[root@comtec-web-test ~]# mount /dev/xvdf /backup
[root@comtec-web-test ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1      8.0G  2.5G  5.6G  31% /
/dev/xvdf      1014M   34M  981M   4% /backup
## 재부팅 시 자동연결 설정 ##
[root@comtec-web-test ~]# lsblk -f
NAME    FSTYPE LABEL UUID                                 MOUNTPOINT
xvda
└─xvda1 xfs    /     8562e9fb-f45b-4a09-9778-bde97be4afb3 /
xvdf    xfs          439eaf4c-805d-4fcc-b864-29bdfdfcebb7 /backup
[root@comtec-web-test ~]# vi /etc/fstab
UUID=439eaf4c-805d-4fcc-b864-29bdfdfcebb7  /backup  xfs  defaults,nofail  0  2
:wq

3. CloudWatch Agent 설치(memory 모니터링)

3.1 Cloudwatch 역할 생성 및 할당


IAM -> 역할 -> 역할만들기 -> 일반사용사례 EC2 선택 -> “CloudWatchAgentServerPolicy” 검색 및 선택
-> 역할 이름 : CloudWatchAgentServerRole 선택 후 완료

EC2선택 -> 작업 -> 보안 -> IAM 역할 수정 -> 앞서 생성한 역할 선택 후 저장

3.2 CloudWatch Agent 설치 및 구성

[root@comtec-web-test ~]# yum install amazon-cloudwatch-agent
[root@comtec-web-test ~]# /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
=============================================================
= Welcome to the AWS CloudWatch Agent Configuration Manager =
=============================================================
On which OS are you planning to use the agent?
1. linux
2. windows
3. darwin
default choice: [1]:
1
Trying to fetch the default region based on ec2 metadata...
Are you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:
1
Which user are you planning to run the agent?
1. root
2. cwagent
3. others
default choice: [1]:
Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:
Which port do you want StatsD daemon to listen to?
default choice: [8125]
What is the collect interval for StatsD daemon?
1. 10s
2. 30s
3. 60s
default choice: [1]:
3
What is the aggregation interval for metrics collected by StatsD daemon?
1. Do not aggregate
2. 10s
3. 30s
4. 60s
default choice: [4]:
Do you want to monitor metrics from CollectD?
1. yes
2. no
default choice: [1]:
Do you want to monitor any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:
Do you want to monitor cpu metrics per core? Additional CloudWatch charges may apply.
1. yes
2. no
default choice: [1]:
Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?
1. yes
2. no
default choice: [1]:
Would you like to collect your metrics at high resolution (sub-minute resolution)? This enables sub-minute resolution for all metrics, but you can customize for specific metrics in the output json file.
1. 1s
2. 10s
3. 30s
4. 60s
default choice: [4]:
Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:
Current config as follows:
{
	"agent": {
		"metrics_collection_interval": 60,
		"run_as_user": "root"
	},
	"metrics": {
		"append_dimensions": {
			"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
			"ImageId": "${aws:ImageId}",
			"InstanceId": "${aws:InstanceId}",
			"InstanceType": "${aws:InstanceType}"
		},
		"metrics_collected": {
			"collectd": {
				"metrics_aggregation_interval": 60
			},
			"disk": {
				"measurement": [
					"used_percent"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				]
			},
			"mem": {
				"measurement": [
					"mem_used_percent"
				],
				"metrics_collection_interval": 60
			},
			"statsd": {
				"metrics_aggregation_interval": 60,
				"metrics_collection_interval": 60,
				"service_address": ":8125"
			}
		}
	}
}
Are you satisfied with the above config? Note: it can be manually customized after the wizard completes to add additional items.
1. yes
2. no
default choice: [1]:
Do you have any existing CloudWatch Log Agent (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html) configuration file to import for migration?
1. yes
2. no
default choice: [2]:
2
Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
2
Saved config file to /opt/aws/amazon-cloudwatch-agent/bin/config.json successfully.
Current config as follows:
{
	"agent": {
		"metrics_collection_interval": 60,
		"run_as_user": "root"
	},
	"metrics": {
		"append_dimensions": {
			"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
			"ImageId": "${aws:ImageId}",
			"InstanceId": "${aws:InstanceId}",
			"InstanceType": "${aws:InstanceType}"
		},
		"metrics_collected": {
			"collectd": {
				"metrics_aggregation_interval": 60
			},
			"disk": {
				"measurement": [
					"used_percent"
				],
				"metrics_collection_interval": 60,
				"resources": [
					"*"
				]
			},
			"mem": {
				"measurement": [
					"mem_used_percent"
				],
				"metrics_collection_interval": 60
			},
			"statsd": {
				"metrics_aggregation_interval": 60,
				"metrics_collection_interval": 60,
				"service_address": ":8125"
			}
		}
	}
}
Please check the above content of the config.
The config file is also located at /opt/aws/amazon-cloudwatch-agent/bin/config.json.
Edit it manually if needed.
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:
What parameter store name do you want to use to store your config? (Use 'AmazonCloudWatch-' prefix if you use our managed AWS policy)
default choice: [AmazonCloudWatch-linux]
Trying to fetch the default region based on ec2 metadata...
Which region do you want to store the config in the parameter store?
default choice: [ap-northeast-2]
Which AWS credential should be used to send json config to parameter store?
1. AKIAXOMD5V425NBUTWC7(From SDK)
2. Other
default choice: [1]:
Successfully put config to parameter store AmazonCloudWatch-linux.
Program exits now.
[root@comtec-web-test ~]# sudo mkdir -p /usr/share/collectd/
[root@comtec-web-test ~]# sudo touch /usr/share/collectd/types.db
[root@comtec-web-test ~]# sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json
[root@comtec-web-test ~]# sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a start
[root@comtec-web-test ~]# sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status
{
  "status": "running",
  "starttime": "2021-07-05T02:11:18+0000",
  "configstatus": "configured",
  "cwoc_status": "stopped",
  "cwoc_starttime": "",
  "cwoc_configstatus": "not configured",
  "version": "1.247347.4"
}

3.3 CloudWatch 정보 수집 확인

CloudWatch -> 지표 -> CWAgent 수집 확인