'Cloud&Container'에 해당되는 글 30건

  1. 2020.03.19 [Docker] 컨테이너/이미지 삭제, 로그 보기
  2. 2020.03.19 [Docker] gitlab, redmine, jenkins 설치 하기
  3. 2020.03.18 [Docker] 초보자를 위한 Container 실행/접속/재시작/User변경
  4. 2020.03.16 [AWS] EC2 인스턴스 백업 하기
  5. 2020.03.13 [AWS] aws cli 사용 시 --query 알아보기
  6. 2020.03.13 [AWS] aws iot/iot-data 등등
  7. 2020.03.12 [AWS] 아마존 리눅스 & 우분투 타임존 변경
  8. 2020.03.04 [AWS] ..user is not authorized to perform: iam:PassRole on resource.. 에러 시
  9. 2020.03.03 [AWS IoT] CA 인증서 등록
  10. 2020.02.25 [AWS] VPC 부터 EC2 생성해서 SSH 연결해보기

[Docker] 컨테이너/이미지 삭제, 로그 보기

Cloud&Container/IaC 2020. 3. 19. 11:56

# 컨테이너 삭제 (docker ps)

$ docker stop ${CONTAINER ID} or ${CONTAINER NAME}
$ docker rm ${CONTAINER ID} or ${CONTAINER NAME}
또는
$ docker rm -f ${CONTAINER ID} or ${CONTAINER NAME}



# 컨테이너 이미지 삭제 (docker images)

$ docker rmi ${IMAGE ID}



# 컨테이너 로그 보기

$ docker logs -f ${CONTAINER ID} or ${CONTAINER NAME}

 

:

[Docker] gitlab, redmine, jenkins 설치 하기

Cloud&Container/IaC 2020. 3. 19. 11:48

 

환경)

- AWS

- Ubuntu 18.04 LTS

- Python 3.8.2

- Pip 3

 

Step 1) docker 를 설치 합니다.

$ sudo apt update
$ sudo apt upgrade
$ sudo apt-get install curl apt-transport-https ca-certificates software-properties-common
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
$ sudo apt update
$ sudo apt install docker-ce
$ sudo systemctl status docker
$ sudo docker run hello-world

$ docker ps
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/create?fromImage=gitlab%2Fgitlab-ee&tag=latest: dial unix /var/run/docker.sock: connect: permission denied

$ sudo usermod -a -G docker ubuntu
또는
$ sudo chmod 666 /var/run/docker.sock
$ sudo service docker restart

 

Step 2) docker compose 를 설치 합니다.

https://docs.docker.com/compose/compose-file/compose-versioning/#version-3

$ sudo curl -L "https://github.com/docker/compose/releases/download/1.25.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose
$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
$ docker-compose --version

# uninstall
$ sudo rm /usr/local/bin/docker-compose

 

# 도커 허브를 통해서 개별 컨테이너에 대한 정보를 확인해서 docker-compose.yml 파일을 만들면 됩니다.

https://hub.docker.com/

 

Step 3) gitlab 을 설치 합니다.

$ mkdir -p docker/gitlab
$ cd docker/gitlab
$ vi docker-compose.yml
version: '3.1'

services:
  web:
    image: 'gitlab/gitlab-ee:12.8.1-ee.0'
    restart: always
    hostname: 'xxxxx.compute.amazonaws.com'
    environment:
      TZ: "Asia/Seoul"
      GITLAB_OMNIBUS_CONFIG: |
        external_url 'https://xxxxx.compute.amazonaws.com'
        letsencrypt['enable'] = false
        nginx['redirect_http_to_https'] = false
        nginx['listen_https'] = false
        nginx['listen_port'] = 8929
        gitlab_rails['gitlab_shell_ssh_port'] = 2224
    ports:
      - '8929:8929'
      - '2224:22'
    volumes:
      - '/home/ubuntu/docker/gitlab/config:/etc/gitlab'
      - '/home/ubuntu/docker/gitlab/logs:/var/log/gitlab'
      - '/home/ubuntu/docker/gitlab/data:/var/opt/gitlab'

$ docker-compse up -d

- port 정보는 환경에 맞게 수정 하면 됩니다.

- docker compose 의 version 에 따라 yml syntax 가 다를 수 있으니 아래 문서에서 확인 하시면 됩니다.

https://docs.docker.com/compose/compose-file/ 

 

Step 4) redmine 을 설치 합니다.

$ mkdir -p docker/redmine
$ cd docker/redmine
$ vi docker-compose.yml
version: '3.3'

services:
  redmine:
    depends_on:
      - mysql
    image: redmine:4.1.0
    restart: always
    container_name: redmine
    ports:
      - 9292:3000
    environment:
      TZ: "Asia/Seoul"
      REDMINE_DB_MYSQL: mysql
      REDMINE_DB_USERNAME: root
      REDMINE_DB_PASSWORD: ROOT-PASSWORD
      REDMINE_DB_DATABASE: redmine_default
      REDMINE_DB_ENCODING: utf8
      #REDMINE_NO_DB_MIGRATE: true
    volumes:
      - ./data:/usr/src/redmine/files
      - ./plugins:/usr/src/redmine/plugins
      - ./themes:/usr/src/redmine/public/themes
  mysql:
    image: mysql:5.7.29
    container_name: mysql
    ports:
      - 3306:3306
    command:
      - --default-authentication-plugin=mysql_native_password
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
    restart: always
    environment:
      TZ: "Asia/Seoul"
      MYSQL_ROOT_PASSWORD: 'ROOT-PASSWORD'
      MYSQL_DATABASE: 'redmine_default'
    volumes:
      - ./data:/var/lib/mysql

# redmine 에서 사용할 DB 계정 정보는 mysql 을 먼저 구성 한 후 등록 하고 redmine 을 실행 시켜 줘야 정상적으로 동작 합니다.
# 이와 같이 하지 않을 경우 connection 이 안되거나 redmine 용 database 가 없다고 오류를 발생 시킵니다.

- redmine 설치 이전에 mysql 이 먼저 구성이 되어야 합니다.

- redmine 의 mysql 사용자를 별도로 만들어 주는 것이 좋기 때문에 필요 하다면 아래와 같이 수정 하면 됩니다.

services:
    mysql:
        image: mysql
...중략...
		volumes:
            - ./sql/init-redmine.sql:/docker-entrypoint-initdb.d/init-redmine.sql
...중략...


# init-redmine.sql
INSERT INTO `user` (`Host`, `User`, `Select_priv`, `Insert_priv`, `Update_priv`, 
`Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, 
`Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, 
`Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, 
`Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, 
`Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, 
`Create_user_priv`, `Event_priv`, `Trigger_priv`, `Create_tablespace_priv`, 
`ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, 
`max_updates`, `max_connections`, `max_user_connections`, `plugin`, 
`authentication_string`, `password_expired`, `password_last_changed`, 
`password_lifetime`, `account_locked`) 
VALUES ('%','redmine','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y',
'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','',
0,0,0,0,'mysql_native_password',password('redmine'),'N',NOW(),NULL,'N')

FLUSH PRIVILEGES;

또는

CREATE USER 'redmine'@'%' IDENTIFIED BY 'redmine';
GRANT ALL PRIVILIEGS ON redmine_default.* TO 'redmine'@'%'

FLUSH PRIVILEGES;

- MySQL 문법 가볍게 한번 보고 넘어 가겠습니다.

CREATE USER '유저아이디'@'접속호스트' IDENTIFIED BY '유저암호';

# 로컬 호스트에서 접속을 허용
CREATE USER '유저아이디'@'localhost' IDENTIFIED BY '유저암호';

# 모든 호스트에서 접속을 허용
CREATE USER '유저아이디'@'%' IDENTIFIED BY '유저암호';

GRANT ALL ON 데이터베이스명.테이블명 TO '유저아이디'@'접속호스트';

# 모든 데이터베이스의 모든 테이블에 대해 로컬호스트로 접속한 유저에게 허용
GRANT ALL ON *.* TO '유저아이디'@'localhost';

# 모든 데이터베이스의 모든 테이블에 대해 모든 호스트로 접속한 유저에게 허용
GRANT ALL ON *.* TO '유저아이디'@'%';

 

Step 5) jenkins 를 설치 합니다.

# python 3.8 최신 버전을 설치 합니다.
# source 로 설치 하는 내용입니다.
$ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev \
    libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev libffi-dev zlib1g-dev
 
$ cd /opt
$ sudo wget https://www.python.org/ftp/python/3.8.2/Python-3.8.2.tgz
$ sudo tar xzf Python-3.8.2.tgz

$ cd Python-3.8.2
$ sudo ./configure --enable-optimizations
$ sudo make altinstall
$ sudo apt-get install python3-pip 

# 패키지로 설치 하는 내용입니다.
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.8

# 기본에 3.6.9 와 같이 다른 python3.x 가 설치 되어 있는 경우 설치 하지 않습니다.
$ sudo apt-get install python3.8-dev
$ sudo apt-get install python3.8-distutils

$ sudo apt-get install python3-pip

# virtualenv 가 필요 하다면,
$ pip3 install virtualenv virtualenvwrapper

# Jenkins 설치
$ mkdir -p docker/jenkins
$ cd docker/jenkins
$ vi docker-compose.yml
version: '2'

services:
  jenkins:
    image: 'jenkins/jenkins:lts'
    container_name: 'jenkins'
    restart: always
    ports:
      - '8080:8080'
    volumes:
      - './jenkins_home:/var/jenkins_home'
      - '/home/ubuntu/.ssh:/var/jenkins_home/.ssh'
      - '/home/ubuntu/.aws:/var/jenkins_home/.aws'
    environment:
      TZ: "Asia/Seoul"

$ docker-compose up -d

# 에러 발생
touch: cannot touch '/var/jenkins_home/copy_reference_file.log': Permission denied

$ sudo chown -R 1000:1000 jenkins_home

# Jenkins 에서 awscli 와 boto3 를 사용하기 위한 설치
$ sudo apt install awscli
$ pip3 install boto3

# Jenkins 에서 aws sdk 사용 하기 위한 설정
# host 에 aws configure 설정을 하고 mount 시킵니다.
$ aws configure
$ sudo chmod 666 .aws/config
$ sudo chmod 666 .aws/credentials
$ docker restart jenkins

이제 기본적인 설치는 끝났습니다.

응용은 이제 각자 알아서 해보시기 바랍니다.

:

[Docker] 초보자를 위한 Container 실행/접속/재시작/User변경

Cloud&Container/IaC 2020. 3. 18. 16:55

아주 기본적인 것도 자주 사용하지 않으면 기억이 나지 않습니다.

 

Docker Reference)

https://docs.docker.com/reference/

 

# Container 실행 (-d 데몬으로 실행)

$ docker-compose up -d


# Process 확인

$ docker ps


# Container 에 접속,  Default 가 생성한 도커파일에 user 가 jenkins 로정의 되어 있음

$ docker exec -it ${CONTAINER ID} 또는 ${CONTAINER NAME}
$ docker exec -it 9fbf1f1df70c /bin/bash
$ docker exec -it -u root 9fbf1f1df70c /bin/bash
jenkins@9fbf1f1df70c:/$


# Container 재시작

$ docker start ${CONTAINER ID} 또는 ${CONTAINER NAME}
$ dcoker stop ${CONTAINER ID} 또는 ${CONTAINER NAME}
$ docker restart ${CONTAINER ID} 또는 ${CONTAINER NAME}


# Container 접속 시 user 변경

$ docker exec -it -u root 9fbf1f1df70c /bin/bash

 

:

[AWS] EC2 인스턴스 백업 하기

Cloud&Container/AWS 2020. 3. 16. 17:03

내부에서 사용하는 EC2 인스턴스의 경우 HA 구성까지는 너무 오버라고 생각될 때 최소한의 Backup 정책 정도는 만들어 놓는게 좋습니다.

 

Case 1) 임의 수동 Snapshot 생성

Backup 하고자 하는 Instance 에서 우클릭 후 Snapshot 생성 을 선택 하시면 됩니다.

Selected Instance -> Right Click -> Image -> Create Image

이와 같이 하면 IMAGES 매뉴에서 AMIs  에 생성된 이미지를 보실 수 있습니다.

 

Case 2) 주기적인 자동 Snapshot 생성 (EBS)

EC2 화면에서 수명 주기 관리자(Lifecycle Manager)

Create Snapshot Lifecycle Policy 를 선택해서 필요한 Scheduler 를 만듭니다.

자세한 내용이 궁금한 분들은 공홈 문서를 보시면 좋을 것 같습니다.

https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html

https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/ebs-creating-snapshot.html

:

[AWS] aws cli 사용 시 --query 알아보기

Cloud&Container/AWS 2020. 3. 13. 21:46

알아 보기라고 하기에는 그냥 약간의 예제와 학습 해야 하는 문서 링크 입니다.

 

https://jmespath.org/specification.html#filter-expressions

$ aws iot list-thing-types --query 'thingTypes[].[thingTypeName, thingTypeName==`1584075120782`]'
$ aws iot list-thing-types --query "thingTypes[].[thingTypeName, starts_with(thingTypeName, '15840')]"

 

JMES 가 이거 만든 사람 이름의 약어 인것 같은데, 맞는지 모르겠네요.

© Copyright 2014-2015, James Saryerwinnie.

 

그리고 이 분 AWS 직원인 것 같습니다. :)

:

[AWS] aws iot/iot-data 등등

Cloud&Container/AWS 2020. 3. 13. 16:58

개발 진행을 하다 보면 대 부분 레퍼런스 문서와 API 문서를 안 볼 수가 없습니다.

더군다나 제공 하는 모든 API 를 다 기억 할 수도 없구요.

그래서 그냥 한 눈에 보기 편하게 모아 두었습니다.

 

[aws iot cli command]

https://docs.aws.amazon.com/cli/latest/reference/iot/index.html

accept-certificate-transfer              | add-thing-to-billing-group
add-thing-to-thing-group                 | associate-targets-with-job
attach-policy                            | attach-principal-policy
attach-security-profile                  | attach-thing-principal
cancel-audit-mitigation-actions-task     | cancel-audit-task
cancel-certificate-transfer              | cancel-job
cancel-job-execution                     | clear-default-authorizer
confirm-topic-rule-destination           | create-authorizer
create-billing-group                     | create-certificate-from-csr
create-domain-configuration              | create-dynamic-thing-group
create-job                               | create-keys-and-certificate
create-mitigation-action                 | create-ota-update
create-policy                            | create-policy-version
create-provisioning-claim                | create-provisioning-template
create-provisioning-template-version     | create-role-alias
create-scheduled-audit                   | create-security-profile
create-stream                            | create-thing
create-thing-group                       | create-thing-type
create-topic-rule                        | create-topic-rule-destination
delete-account-audit-configuration       | delete-authorizer
delete-billing-group                     | delete-ca-certificate
delete-certificate                       | delete-domain-configuration
delete-dynamic-thing-group               | delete-job
delete-job-execution                     | delete-mitigation-action
delete-ota-update                        | delete-policy
delete-policy-version                    | delete-provisioning-template
delete-provisioning-template-version     | delete-registration-code
delete-role-alias                        | delete-scheduled-audit
delete-security-profile                  | delete-stream
delete-thing                             | delete-thing-group
delete-thing-type                        | delete-topic-rule
delete-topic-rule-destination            | delete-v2-logging-level
deprecate-thing-type                     | describe-account-audit-configuration
describe-audit-finding                   | describe-audit-mitigation-actions-task
describe-audit-task                      | describe-authorizer
describe-billing-group                   | describe-ca-certificate
describe-certificate                     | describe-default-authorizer
describe-domain-configuration            | describe-endpoint
describe-event-configurations            | describe-index
describe-job                             | describe-job-execution
describe-mitigation-action               | describe-provisioning-template
describe-provisioning-template-version   | describe-role-alias
describe-scheduled-audit                 | describe-security-profile
describe-stream                          | describe-thing
describe-thing-group                     | describe-thing-registration-task
describe-thing-type                      | detach-policy
detach-principal-policy                  | detach-security-profile
detach-thing-principal                   | disable-topic-rule
enable-topic-rule                        | get-cardinality
get-effective-policies                   | get-indexing-configuration
get-job-document                         | get-logging-options
get-ota-update                           | get-percentiles
get-policy                               | get-policy-version
get-registration-code                    | get-statistics
get-topic-rule                           | get-topic-rule-destination
get-v2-logging-options                   | list-active-violations
list-attached-policies                   | list-audit-findings
list-audit-mitigation-actions-executions | list-audit-mitigation-actions-tasks
list-audit-tasks                         | list-authorizers
list-billing-groups                      | list-ca-certificates
list-certificates                        | list-certificates-by-ca
list-domain-configurations               | list-indices
list-job-executions-for-job              | list-job-executions-for-thing
list-jobs                                | list-mitigation-actions
list-ota-updates                         | list-outgoing-certificates
list-policies                            | list-policy-principals
list-policy-versions                     | list-principal-policies
list-principal-things                    | list-provisioning-template-versions
list-provisioning-templates              | list-role-aliases
list-scheduled-audits                    | list-security-profiles
list-security-profiles-for-target        | list-streams
list-tags-for-resource                   | list-targets-for-policy
list-targets-for-security-profile        | list-thing-groups
list-thing-groups-for-thing              | list-thing-principals
list-thing-registration-task-reports     | list-thing-registration-tasks
list-thing-types                         | list-things
list-things-in-billing-group             | list-things-in-thing-group
list-topic-rule-destinations             | list-topic-rules
list-v2-logging-levels                   | list-violation-events
register-ca-certificate                  | register-certificate
register-thing                           | reject-certificate-transfer
remove-thing-from-billing-group          | remove-thing-from-thing-group
replace-topic-rule                       | search-index
set-default-authorizer                   | set-default-policy-version
set-logging-options                      | set-v2-logging-level
set-v2-logging-options                   | start-audit-mitigation-actions-task
start-on-demand-audit-task               | start-thing-registration-task
stop-thing-registration-task             | tag-resource
test-authorization                       | test-invoke-authorizer
transfer-certificate                     | untag-resource
update-account-audit-configuration       | update-authorizer
update-billing-group                     | update-ca-certificate
update-certificate                       | update-domain-configuration
update-dynamic-thing-group               | update-event-configurations
update-indexing-configuration            | update-job
update-mitigation-action                 | update-provisioning-template
update-role-alias                        | update-scheduled-audit
update-security-profile                  | update-stream
update-thing                             | update-thing-group
update-thing-groups-for-thing            | update-topic-rule-destination
validate-security-profile-behaviors      | help

 

[aws iot-data cli command]

https://docs.aws.amazon.com/cli/latest/reference/iot-data/index.html

delete-thing-shadow                      | get-thing-shadow
publish                                  | update-thing-shadow
help

 

[aws iot-jobs-data cli command]

https://docs.aws.amazon.com/cli/latest/reference/iot-jobs-data/index.html

describe-job-execution                   | get-pending-job-executions
start-next-pending-job-execution         | update-job-execution

 

[aws iot1click-devices cli command]

https://docs.aws.amazon.com/cli/latest/reference/iot1click-devices/index.html

claim-devices-by-claim-code              | describe-device
finalize-device-claim                    | get-device-methods
initiate-device-claim                    | invoke-device-method
list-device-events                       | list-devices
list-tags-for-resource                   | tag-resource
unclaim-device                           | untag-resource
update-device-state                      | help

 

[aws iot1click-projects cli command]

https://docs.aws.amazon.com/cli/latest/reference/iot1click-projects/index.html

associate-device-with-placement          | create-placement
create-project                           | delete-placement
delete-project                           | describe-placement
describe-project                         | disassociate-device-from-placement
get-devices-in-placement                 | list-placements
list-projects                            | list-tags-for-resource
tag-resource                             | untag-resource
update-placement                         | update-project
help

 

[aws iotanalytics cli command]

https://docs.aws.amazon.com/cli/latest/reference/iotanalytics/index.html

batch-put-message                        | cancel-pipeline-reprocessing
create-channel                           | create-dataset
create-dataset-content                   | create-datastore
create-pipeline                          | delete-channel
delete-dataset                           | delete-dataset-content
delete-datastore                         | delete-pipeline
describe-channel                         | describe-dataset
describe-datastore                       | describe-logging-options
describe-pipeline                        | get-dataset-content
list-channels                            | list-dataset-contents
list-datasets                            | list-datastores
list-pipelines                           | list-tags-for-resource
put-logging-options                      | run-pipeline-activity
sample-channel-data                      | start-pipeline-reprocessing
tag-resource                             | untag-resource
update-channel                           | update-dataset
update-datastore                         | update-pipeline
help

 

[aws iotevents cli command]

https://docs.aws.amazon.com/cli/latest/reference/iotevents/index.html

create-detector-model                    | create-input
delete-detector-model                    | delete-input
describe-detector-model                  | describe-input
describe-logging-options                 | list-detector-model-versions
list-detector-models                     | list-inputs
list-tags-for-resource                   | put-logging-options
tag-resource                             | untag-resource
update-detector-model                    | update-input
help

 

[aws iotevents-data cli command]

https://docs.aws.amazon.com/cli/latest/reference/iotevents-data/index.html

batch-put-message                        | batch-update-detector
describe-detector                        | list-detectors
help

 

[aws iotsecuretunneling cli command]

https://docs.aws.amazon.com/cli/latest/reference/iotsecuretunneling/index.html

close-tunnel                             | describe-tunnel
list-tags-for-resource                   | list-tunnels
open-tunnel                              | tag-resource
untag-resource                           | help

 

[aws iotthingsgraph cli command]

https://docs.aws.amazon.com/cli/latest/reference/iotthingsgraph/index.html

associate-entity-to-thing                | create-flow-template
create-system-instance                   | create-system-template
delete-flow-template                     | delete-namespace
delete-system-instance                   | delete-system-template
deploy-system-instance                   | deprecate-flow-template
deprecate-system-template                | describe-namespace
dissociate-entity-from-thing             | get-entities
get-flow-template                        | get-flow-template-revisions
get-namespace-deletion-status            | get-system-instance
get-system-template                      | get-system-template-revisions
get-upload-status                        | list-flow-execution-messages
list-tags-for-resource                   | search-entities
search-flow-executions                   | search-flow-templates
search-system-instances                  | search-system-templates
search-things                            | tag-resource
undeploy-system-instance                 | untag-resource
update-flow-template                     | update-system-template
upload-entity-definitions                | help

 

:

[AWS] 아마존 리눅스 & 우분투 타임존 변경

Cloud&Container/AWS 2020. 3. 12. 21:20

https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/set-time.html

 

문서 보고 잘 따라 하시면 됩니다. :)

Amazon Linux AMI에서 Amazon Time Sync Service 구성

Amazon Time Sync Service를 사용하도록 인스턴스를 구성하려면

  1. 인스턴스를 연결하고 NTP 서비스를 제거합니다.

     

    [ec2-user ~]$ sudo yum erase 'ntp*'
  2. chrony 패키지를 설치합니다.

     

    [ec2-user ~]$ sudo yum install chrony
  3. vim 또는 nano과 같은 텍스트 편집기를 사용하여 /etc/chrony.conf 파일을 엽니다. 파일이 다음 라인을 포함하고 있는지 확인합니다.

     

    server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4

    이 라인이 존재할 경우, Amazon Time Sync Service가 이미 구성된 상태이기 때문에 다음 단계로 넘어갈 수 있습니다. 라인이 없는 경우에는 파일에 이미 존재하는 다른 server 또는 pool 문 뒤에 라인을 추가하고 변경 사항을 저장합니다.

  4. chrony 데몬(chronyd)을 다시 시작합니다.

     

    [ec2-user ~]$ sudo service chronyd restartStarting chronyd: [ OK ]

    참고

    RHEL 및 CentOS(최대 버전 6까지)에서 서비스 이름은 chrony이 아니라 chronyd입니다.

  5. chkconfig 명령을 사용해서 매번 시스템이 부팅할 때마다 시작되도록 chronyd를 구성합니다.

     

    [ec2-user ~]$ sudo chkconfig chronyd on
  6. chrony가 169.254.169.123 IP 주소를 사용하여 시간을 동기화하고 있는지 확인합니다.

     

    [ec2-user ~]$ chronyc sources -v210 Number of sources = 7 .-- Source mode '^' = server, '=' = peer, '#' = local clock. / .- Source state '*' = current synced, '+' = combined , '-' = not combined, | / '?' = unreachable, 'x' = time may be in error, '~' = time too variable. || .- xxxx [ yyyy ] +/- zzzz || Reachability register (octal) -. | xxxx = adjusted offset, || Log2(Polling interval) --. | | yyyy = measured offset, || \ | | zzzz = estimated error. || | | \ MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^* 169.254.169.123 3 6 17 43 -30us[ -226us] +/- 287us ^- ec2-12-34-231-12.eu-west> 2 6 17 43 -388us[ -388us] +/- 11ms ^- tshirt.heanet.ie 1 6 17 44 +178us[ +25us] +/- 1959us ^? tbag.heanet.ie 0 6 0 - +0ns[ +0ns] +/- 0ns ^? bray.walcz.net 0 6 0 - +0ns[ +0ns] +/- 0ns ^? 2a05:d018:c43:e312:ce77:> 0 6 0 - +0ns[ +0ns] +/- 0ns ^? 2a05:d018:dab:2701:b70:b> 0 6 0 - +0ns[ +0ns] +/- 0ns

    반환된 출력에서 ^*는 기본 설정된 타임 소스를 나타냅니다.

  7. chrony에서 보고된 시간 동기화 지표를 확인합니다.

     

    [ec2-user ~]$ chronyc trackingReference ID : A9FEA97B (169.254.169.123) Stratum : 4 Ref time (UTC) : Wed Nov 22 13:18:34 2017 System time : 0.000000626 seconds slow of NTP time Last offset : +0.002852759 seconds RMS offset : 0.002852759 seconds Frequency : 1.187 ppm fast Residual freq : +0.020 ppm Skew : 24.388 ppm Root delay : 0.000504752 seconds Root dispersion : 0.001112565 seconds Update interval : 64.4 seconds Leap status : Normal

Ubuntu에서 Amazon Time Sync Service 구성

Amazon Time Sync Service를 사용하도록 인스턴스를 구성하려면

  1. 인스턴스를 연결해 apt를 사용하여 chrony 패키지를 설치합니다.

     

    ubuntu:~$ sudo apt install chrony

    참고

    필요할 경우 sudo apt update를 실행하여 먼저 인스턴스를 업데이트합니다.

  2. vim 또는 nano과 같은 텍스트 편집기를 사용하여 /etc/chrony/chrony.conf 파일을 엽니다. 파일에 이미 존재하는 server 또는 pool 문 앞에 다음 라인을 추가하고 변경 사항을 저장합니다.

     

    server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4
  3. chrony 서비스를 다시 시작합니다.

     

    ubuntu:~$ sudo /etc/init.d/chrony restart[ ok ] Restarting chrony (via systemctl): chrony.service.
  4. chrony가 169.254.169.123 IP 주소를 사용하여 시간을 동기화하고 있는지 확인합니다.

     

    ubuntu:~$ chronyc sources -v210 Number of sources = 7 .-- Source mode '^' = server, '=' = peer, '#' = local clock. / .- Source state '*' = current synced, '+' = combined , '-' = not combined, | / '?' = unreachable, 'x' = time may be in error, '~' = time too variable. || .- xxxx [ yyyy ] +/- zzzz || Reachability register (octal) -. | xxxx = adjusted offset, || Log2(Polling interval) --. | | yyyy = measured offset, || \ | | zzzz = estimated error. || | | \ MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^* 169.254.169.123 3 6 17 12 +15us[ +57us] +/- 320us ^- tbag.heanet.ie 1 6 17 13 -3488us[-3446us] +/- 1779us ^- ec2-12-34-231-12.eu-west- 2 6 17 13 +893us[ +935us] +/- 7710us ^? 2a05:d018:c43:e312:ce77:6 0 6 0 10y +0ns[ +0ns] +/- 0ns ^? 2a05:d018:d34:9000:d8c6:5 0 6 0 10y +0ns[ +0ns] +/- 0ns ^? tshirt.heanet.ie 0 6 0 10y +0ns[ +0ns] +/- 0ns ^? bray.walcz.net 0 6 0 10y +0ns[ +0ns] +/- 0ns

    반환된 출력에서 ^*는 기본 설정된 타임 소스를 나타냅니다.

  5. chrony에서 보고된 시간 동기화 지표를 확인합니다.

     

    ubuntu:~$ chronyc trackingReference ID : 169.254.169.123 (169.254.169.123) Stratum : 4 Ref time (UTC) : Wed Nov 29 07:41:57 2017 System time : 0.000000011 seconds slow of NTP time Last offset : +0.000041659 seconds RMS offset : 0.000041659 seconds Frequency : 10.141 ppm slow Residual freq : +7.557 ppm Skew : 2.329 ppm Root delay : 0.000544 seconds Root dispersion : 0.000631 seconds Update interval : 2.0 seconds Leap status : Normal

 

:

[AWS] ..user is not authorized to perform: iam:PassRole on resource.. 에러 시

Cloud&Container/AWS 2020. 3. 4. 18:35

항상 그렇지만 에러 메시지를 보면 답이 다 나와 있습니다.

"iam:PassRole" 에 대한 권한이 없다는 것입니다.

 

근데 충분한 권한을 줬다고 생각 했어도 왜 저런 에러가 나는 거지 하고 의심이 될 때가 있습니다.

원인도 찾았고 해결책도 찾았지만 AWS 뿐만 아니라 Cloud 서비스를 잘 사용하기 위해서는 보안과 권한에 대해서 정말 자세히 알고 고민을 하지 않으면 안될 것 같다는 확신이 또 들었습니다.

 

근데 생각 보다 IAM 관련해서 서비스 유형에 따른 템플릿 같은게 많이 없는 것 같아 좀 아쉽 더군요.

시간 날 때 한번 만들어 봐야 겠습니다.

 

iam:PassRole을 수행하도록 인증되지 않음

서비스 연결 역할을 생성하는 경우 해당 역할을 서비스에 전달할 권한이 있어야 합니다. 일부 서
비스는 서비스에서 작업을 수행할 때 계정에 서비스 연결 역할을 자동으로 생성합니다. 예를 들어
Amazon EC2 Auto Scaling에서는 사용자가 Auto Scaling 그룹을 처음으로 생성할 때 사용자를 대신해
AWSServiceRoleForAutoScaling 서비스 연결 역할을 생성합니다. PassRole 권한 없이 Auto Scaling
그룹을 생성하려고 하면 다음 오류가 발생합니다.

 

ClientError: An error occurred (AccessDenied) when calling the
PutLifecycleHook operation: User: arn:aws:sts::111122223333:assumed-role/
Testrole/Diego is not authorized to perform: iam:PassRole on resource:
arn:aws:iam::111122223333:role/aws-service-role/autoscaling.amazonaws.com/
AWSServiceRoleForAutoScaling

 

이 오류를 해결하려면 관리자에게 iam:PassRole 권한을 추가해 달라고 요청합니다.
서비스 연결 역할을 지원하는 서비스를 알아보려면 IAM로 작업하는 AWS 서비스 (p. 571) 단원을 참조하
십시오. 서비스가 자동으로 서비스 연결 역할을 생성하는지 여부를 알아보려면 예 링크를 선택하여 해당 서
비스의 서비스 연결 역할 설명서 단원을 참조하십시오.

 

저 역시 role 에서 정책을 하나 새로 만들어서 해결 했습니다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:GetRole",
                "iam:PassRole"
            ],
            "Resource": "arn:aws:s3:::test-iot-s3-action"
        }
    ]
}

Action 목록이 궁금 하신 분들은 아래 문서 참고 하세요.

https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html

:

[AWS IoT] CA 인증서 등록

Cloud&Container/AWS 2020. 3. 3. 20:42

참고 문서)

https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html

 

$ openssl genrsa -out rootCA.key 2048
$ openssl req -x509 -new -extensions v3_ca -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
Country Name (KR) []:KR
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:
Email Address []:
$ openssl genrsa -out verificationCert.key 2048
$ aws iot get-registration-code 
{
    "registrationCode": "879216d3f0b9fee2e0947fe32fd4ed9670d65fa9aff3e67e590582db30f62878"
}
$ openssl req -new -key verificationCert.key -out verificationCert.csr
Country Name (KR) []:KR
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:879216d3f0b9fee2e0947fe32fd4ed9670d65fa9aff3e67e590582db30f62878
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
$ openssl x509 -req -in verificationCert.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out verificationCert.pem -days 500 -sha256
$ aws iot register-ca-certificate --ca-certificate file://rootCA.pem --verification-cert file://verificationCert.pem
{
    "certificateArn": "arn:aws:iot:ap-northeast-2:99999999999:cacert/879216d3f0b9fee2e0947fe32fd4ed9670d65fa9aff3e67e590582db30f62878",
    "certificateId": "879216d3f0b9fee2e0947fe32fd4ed9670d65fa9aff3e67e590582db30f62878"
}
 
$ cat /etc/ssl/openssl.cnf
[ req ]
#default_bits = 2048
#default_md = sha256
#default_keyfile  = privkey.pem
distinguished_name = req_distinguished_name
extensions               = v3_ca # 추가 설정
req_extensions           = v3_ca # 추가 설정
attributes = req_attributes

[ v3_ca ]
basicConstraints         = CA:TRUE # 추가 설정

[ req_distinguished_name ]
countryName = Country Name (KR)
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (eg, fully qualified host name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64

[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20

 

위 테스트는 맥북에서 진행 된 것입니다.

Ubuntu 에서는 별도 설정 변경 없이 잘 되는 것으로 이야기 들었습니다.

저 위에 빨간색 부분이 달라 계속 오류가 발생을 했었습니다.

 

[에러메시지]

An error occurred (CertificateValidationException) when calling the RegisterCACertificate operation: CA certificate is not valid.

The CA certificate does not have the basicConstraints extension as true

:

[AWS] VPC 부터 EC2 생성해서 SSH 연결해보기

Cloud&Container/AWS 2020. 2. 25. 16:30

AWS 에서 쵝 인프라 및 네트워크를 구성 하고 Bastion 설정을 통해 SSH Tunneling 을 해보도록 하겠습니다.

(기억력을 돕기 위해 작성한 내용입니다.)

 

[AWS에서 초기 인프라 및 네트워크 구성 하기]
생성 하는 순서는 아래와 같이 진행을 하시면 됩니다.

1. VPC 생성을 합니다.
2. Subnet 생성을 합니다.
- Public Subnet
- Private Subnet
3. Route Table 생성을 합니다.
- Public Route Table
- Private Route Table
4. Subnet 과 Route Table 연결을 합니다.
5. Internet Gateway 생성을 합니다.
- 인터넷 전용 연결 게이트웨이로 사용 합니다.
6. VPC 와 Internet Gateway 연결을 합니다.
7. Route Table 에서 Internet Gateway 연결을 합니다.
- Public Route Table 을 연결 합니다.
8. Network ACL 과 Security Group 설정을 합니다.
- 생성한 자원들에 대한 접근 제어 설계를 통해 구성 합니다.
- Inbounds, Outbounds


[VPC 생성]
- 생성할 VPC Name tag 를 작성 합니다.
- vpc-startup
- IPv4 CIDR block 을 작성 합니다.
- 10.0.0.0/16
참고 글)
https://jjeong.tistory.com/1405
- IPv6 CIDR block 은 기본 "No IPv6 CIDR Block" 을 선택 합니다.
- Tenancy 는 "Default" 를 선택 합니다.

[Subnet 생성]
- 생성할 Subnet 의 Name tag 를 작성 합니다.
- sbn2a-prd-public
- sbn2b-prd-private
- 연결할 VPC 를 선택 합니다.
- 생성할 Availability Zone 을 선택 합니다.
- VPC CIDR 범위에 속하는 IPv4 CIDR block 을 등록 합니다.
- 10.0.0.0/20
- First IP : 10.0.0.0
- Last IP : 10.0.15.255
- AWS 내 Available IPv4 Addresses : 4091 개

[Route Table 생성]
- 생성할 Route Table 의 Name tag 를 작성 합니다.
- rtb-prd-public
- rtb-prd-private
- 연결할 VPC 를 선택 합니다.

[Subnet 과 Route Table 연결]
- Route Table 정보 화면에서 Subnet Associations 를 선택 합니다.
- Edit subnet associations 를 클릭 합니다.
- 연결할 Subnet 을 선택 합니다.

[Internet Gateway 생성 / VPC 와 연결]
- 생성할 Internet Gateway 의 Name tag 를 작성 합니다.
- 목록에서 생성한 IGW 를 선택 하고 Actions 에서 Attach to VPC 를 통해 연결 합니다.

[Route Table 에 Internet Gateway 연결]
- Public Route Table 에서 Routes 탭의 Edit routes 를 클릭 합니다.
- Add route 를 통해 IGW 를 등록 합니다.
- 0.0.0.0/0

[Network ACL 설정 및 Subnet 연결]
- Public zone 과 Private zone 에 대한 ACL 을 생성 합니다.
- 생성할 ACL 의 Name tag 를 작성 합니다.
- acl-prd-public
- acl-prd-private
- 연결할 VPC 를 선택 합니다.
- Public zone acl 에 SSH Tunnel Gateway 구성을 위한 Inbound Rule 을 생성 합니다.
- 초기 SSH 연결 테스트만 하기 위한 설정 입니다.
- SSH(22), TCP(6), 22, 0.0.0.0/0, ALLOW
- Private zone acl 에 Inbound Rule 을 생성 합니다.
- SSH Tunnel Gateway 에서 접속 할 수 있도록 SSH 오픈 및 Source 제한을 합니다.
- 설정한 ACL 을 Subnet 에 적용 될 수 있도록 연결 설정 합니다.

[Security Group 생성]
- 생성할 Security Group Name 을 작성 합니다.
- 사용할 VPC 를 선택 합니다.
- SSH Tunnel Gateway 구성을 위한 Inbound 를 설정 합니다.
-  SSH, TCP, 22, My IP 로 Add Rule 합니다.
- Outbound 는 All 로 구성 합니다.

여기까지 했으면 VPC, ZONE, Security 에 대한 기본 구성을 해본 것입니다.
이제 EC2 인스턴스를 생성해서 SSH Tunnel 용 Gateway (Bastion) 를 구성해 보도록 하겠습니다. 

[EC2 생성]
- Amazon Linux 2 AMI 를 선택 합니다.
t2.micro 를 선택 합니다. (저는 free tier 적용을 위해 선택 했기 때문에 용도와 목적에 맞게 선택 하시면 됩니다.)
- 생성할 VPC 를 선택 합니다.
- 생성할 Subnet 을 선택 합니다.
- Public IP 할당 여부를 선택 합니다. (Bastion 구성을 위해 Public IP 할당)
- Storage, Tag 설정 이후 Security Group 설정을 합니다.
- Select an existing security group 을 통해 이미 만들어 놓은 것을 선택 합니다.
- Key pair 를 다운받습니다.
- 인스턴스를 시작 합니다.

[SSH 연결]
$ ssh -i ec2key-prd-gw.pem ec2-user@ec2-xxx-xxx-xxx-xxx.ap-northeast-2.compute.amazonaws.com

[ssh-keygen on 맥북]
$ ssh-keygen -t rsa
$ cat .ssh/id_rsa.pub
ssh-rsa .....HENRYJEONG.local

[User 생성]

https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/managing-users.html
[ec2-user@ip-42 ~]$ sudo adduser henryjeong
[ec2-user@ip-42 ~]$ sudo su - henryjeong
[henryjeong@ip-42 ~]$ mkdir .ssh
[henryjeong@ip-42 ~]$ chmod 700 .ssh
[henryjeong@ip-42 .ssh]$ touch authorized_keys
[henryjeong@ip-42 .ssh]$ chmod 600 authorized_keys
[henryjeong@ip-42 .ssh]$ vi authorized_keys

[User 로 접속]
$ ssh henryjeong@xxx.xxx.xxx.xxx
Last login: Tue Feb 25 07:23:45 2020

       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-2/
[henryjeong@ip-10-0-6-44 ~]$

# EC2 에 Public IP 는 생성이 되었으나 Public DNS 가 생성되지 않았을 경우 

Your answer

  • Go to console.aws.amazon.com.
  • Go To Services and then VPC.
  • Open Your VPCs.
  • Select your VPC connected to your EC2 and.
  • Choose Select Actions.
  • Click on Edit DNS Hostnames.
  • Then Change DNS hostnames: to YES.
: