리셋 되지 말자

[Terraform] AWS ECR 생성 및 사용 본문

Infra

[Terraform] AWS ECR 생성 및 사용

kyeongjun-dev 2021. 7. 7. 14:39

참고 사이트

- https://www.44bits.io/ko/post/amazon-ecr-login-by-awscliv2
- https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecr_repository

 

실습 환경

vagrant로 centos/7 생성 후, 실행

- Vagrantfile

Vagrant.configure("2") do |config|
  #ansible-client001
  config.vm.define "server" do |cfg|
      cfg.vm.box = "centos/7"
      cfg.vm.provider "virtualbox" do |vb|
          vb.name = "server"
          vb.memory = 2048
          vb.cpus = 2
      end
      cfg.vm.host_name = "server"
      cfg.vm.network "private_network", ip: "192.168.252.100", :adapter => 2 
  end
end

 

Docker 설치

[vagrant@server ~]$ curl -fsSL https://get.docker.com -o get-docker.sh
[vagrant@server ~]$ sudo sh get-docker.sh

# 설치가 끝나면
[vagrant@server ~]$ sudo usermod -aG docker vagrant
[vagrant@server ~]$ sudo systemctl start docker
[vagrant@server ~]$ sudo systemctl enable docker

# 접속 종료했다가 다시 접속
[vagrant@server ~]$ exit
vagrant ssh

 

 

AWS CLI 2 설치

- 링크 : https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/install-cliv2-linux.html

[vagrant@server ~]$ sudo yum install -y unzip
[vagrant@server ~]$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
[vagrant@server ~]$ unzip awscliv2.zip
[vagrant@server ~]$ sudo ./aws/install
You can now run: /usr/local/bin/aws --version

 

 

Terraform 설치

아래 링크에서 진행

https://not-to-be-reset.tistory.com/368

- wget 없다고 뜨면, 설치

sudo yum install -y wget

 

 

AWS 콘솔에서 키 발급

- 로그인 후, IAM 서비스 이동

 

- 정책 탭 이동

 

- 정책 생성 클릭

 

- Public이 아닌 그냥 Elastic Container Registry 선택

 

- 모든 체크

 

- 리소스에서 모든 리소스 선택

다음 -> 태그 추가 없이, 다음

 

- 적당한 이름 입력후 우측 하단 '정책 생성'으로 진행

 

- 사용자 탭에서 '사용자 추가' 클릭

 

- 적당한 사용자 이름과, 콘솔 비밀번호 입력후 '다음'

 

- 위에서 생성한 정책에 직접 연결 ('다음' 누르면 나오는 태그추가 생략)

 

- 사용자 만들기

 

- 키 발급 완료 (기록해놓기)

 

 

Terraform에서 사용할 AWS 키를 CentOS 에 등록

- 아래의 키 내용 말고, 직접 받은 key를 입력

[vagrant@server ~]$ export AWS_ACCESS_KEY_ID=AKIdkn123Kkndfk2G5
[vagrant@server ~]$ export AWS_SECRET_ACCESS_KEY=78EGlLuk2nkdjbkefnkl3kHSJMUP

 

AWS CLI 사용을 위한 key, region 등록

[vagrant@server ~]$ mkdir ~/.aws
[vagrant@server ~]$ vi ~/.aws/credentials

 

- credentials

[default]
aws_access_key_id=$AWS_ACCESS_KEY_ID
aws_secret_access_key=$AWS_SECRET_ACCESS_KEY
region=ap-northeast-2

 

 

Terraform 스크립트 작성

- 디렉토리 생성 후 이동

[vagrant@server ~]$ mkdir ECR
[vagrant@server ~]$ cd ECR

 

- versions.tf

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

provider "aws" {
  access_key = ""
  secret_key = ""
  region = "ap-northeast-2"
}

 

- ecr.tf

resource "aws_ecr_repository" "foo" {
  name                 = "bar"
  image_tag_mutability = "MUTABLE"
  image_scanning_configuration {
    scan_on_push = true
  }
}

resource "null_resource" "null_for_ecr_get_login_password" {
  provisioner "local-exec" {
    command = <<EOF
      aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin ${aws_ecr_repository.foo.repository_url}
    EOF
  }
}

 

output "ecr_registry_id" {
  value = aws_ecr_repository.foo.registry_id
}

output "ecr_repository_url" {
  value = aws_ecr_repository.foo.repository_url
}

 

 

Terraform 실행

- init

[vagrant@server ECR]$ terraform init

 

- 패키지 설치 확인. aws, null

[vagrant@server ECR]$ terraform --version
Terraform v0.14.8
+ provider registry.terraform.io/hashicorp/aws v3.48.0     
+ provider registry.terraform.io/hashicorp/null v3.1.0

 

- plan

[vagrant@server ECR]$ terraform plan

An execution plan has been generated and is shown below.   
Resource actions are indicated with the following symbols: 
  + create

Terraform will perform the following actions:

  # aws_ecr_repository.foo will be created
  + resource "aws_ecr_repository" "foo" {
      + arn                  = (known after apply)
      + id                   = (known after apply)
      + image_tag_mutability = "MUTABLE"
      + name                 = "bar"
      + registry_id          = (known after apply)
      + repository_url       = (known after apply)
      + tags_all             = (known after apply)

      + image_scanning_configuration {
          + scan_on_push = true
        }
    }

  # null_resource.null_for_ecr_get_login_password will be created
  + resource "null_resource" "null_for_ecr_get_login_password" {
      + id = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + ecr_registry_id    = (known after apply)
  + ecr_repository_url = (known after apply)

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

 

- apply (중간에 yes입력)

 WARNING! Your password will be stored unencrypted in /home/vagrant/.docker/config.json.

위가 있으면 성공

 

- docker의 config.json 파일 생성된것 확인

[vagrant@server ECR]$ ls ~/.docker/
config.json

 

 

Docker 이미지 Push, Pull 테스트

- 공식 hello-world 이미지 다운로드

[vagrant@server ECR]$ docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete
Digest: sha256:9f6ad537c5132bcce57f7a0a20e317228d382c3cd61edae14650eec68b2b345c
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest

 

- tag 변경

[vagrant@server ECR]$ docker tag hello-world:latest 3746872365.dkr.ecr.ap-northeast-2.amazonaws.com/bar:test

 

- ECR에 push

[vagrant@server ECR]$ docker push 3746872365.dkr.ecr.ap-northeast-2.amazonaws.com/bar:test

 

- ECR 콘솔에서 확인

 

- docker image 전부 삭제

[vagrant@server ECR]$ docker rmi -f $(docker images -aq)

 

- ECR 에서 image pull

[vagrant@server ECR]$ docker pull 3746872365.dkr.ecr.ap-northeast-2.amazonaws.com/bar:test
[vagrant@server ECR]$ docker images
REPOSITORY                                              TAG       IMAGE ID       CREATED        SIZE
395389474517.dkr.ecr.ap-northeast-2.amazonaws.com/bar   test      d1165f221234   4 months ago   13.3kB

 

성공~

Comments