継続は力なり

タイトル通り定期的な更新を心掛けるブログです。

スピーディーなコンテナ環境の構築とアプリケーションデプロイができる『AWS Copilot CLI』

タダです.

現在ベータ版ですが ECS や Fargate でのアプリケーションの作成/リリース/管理するための開発者向けツールである「AWS Copilot CLI」を触ってみました.この記事でツールの概要,ツールの導入,サンプルアプリケーションのデプロイを通じてこのツールで AWS へのコンテナ環境構築とデプロイがシュッとできる感覚が伝われば幸いです✨

ツールの概要

AWS Copilot CLI」(以下 Copilot CLI)は,ECS や Fargate のアプリケーションの作成,リリース,運用する時に DevOps のベストプラクティスと本番環境に対応したインフラストラクチャのパターンを使った支援のためのツールにしていくことが記載されてます.

Our mission is to help customers build, release and operate applications on Amazon ECS with dev-ops best practices and production ready infrastructure patterns.

github.com

特徴としては Dockerfile とアプリケーションのコードさえあればターミナルで完結して10分以内に ECS 上でコードを動かせるようなので,この辺がシュッと環境構築とデプロイを行える所以です.

Got a Dockerfile and some code? Get it up and running on ECS in under 10 minutes, with just one command.Ready to take that app to production? Spin up new environments and a continuous delivery pipeline without having to leave your terminal.

利用シーンとして次のケースが列挙されています.開発からデプロイまで包括的にカバーしており,CI/CD パイプラインにも組み込んで使えるツールです.

関連するすべてのマイクロサービスを1つのアプリケーションにまとめる

リージョンやアカウントを超えたテスト環境と本番環境の設定

本番さながらのスケーラブルなECSサービスとインフラストラクチャのセットアップ

すべてのマイクロサービスの CI/CD パイプラインを設定する

ターミナルからサービスの監視とデバッグ

ecs-cli との関係

同じような CLI ツールに「ecs-cli」があります.違いが何かなと思ったら ECS CLI v2 版として位置づけられているのが「Copilot CLI」のようです.GitHub の ECS CLI v2 のリンクも「Copilot CLI」のリポジトリにリンクされていましたので「ecs-cli」の後継として今後のスタンダードツールになっていくものと想像してます.開発者向けツールであるためDeveloper Experienceにフォーカスしているのが特徴ですね.

The ECS CLI v2 is a brand new CLI focused on the full developer experience of building, deploying and operating your containerized apps. From helping manage all of your infrastructure, to setting up CD Pipelines, the V2 is here to help. The ECS CLI v2 is still in preview and quite different from V1, but we'd love your feedback! For more info on V2, V1 and how these projects are being developed check out our V2 proposal.

github.com

ツールのインストール

それでは「Copilot CLI」をローカルにいれてみます.インストールは macOSLinux の2つの方法がありますが,僕は macOS なのでインストール用のコマンド一発で簡単に導入できました.

» curl -Lo /usr/local/bin/copilot https://github.com/aws/copilot-cli/releases/download/v0.1.0/copilot-darwin-v0.1.0 && chmod +x /usr/local/bin/copilot && copilot --help
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   634  100   634    0     0   1350      0 --:--:-- --:--:-- --:--:--  1348
100 37.9M  100 37.9M    0     0   107k      0  0:06:02  0:06:02 --:--:--  119k
👩<200d>✈️ Launch and manage applications on Amazon ECS and AWS Fargate.

Commands
  Getting Started 🌱
    init        Create a new ECS application.
    docs        Open the copilot docs.

  Develop ✨
    app         Commands for applications.
                Applications are a collection of services and environments.

    env         Commands for environments.
                Environments are deployment stages shared between services.

    svc         Commands for services.
                Services are long-running Amazon ECS services.

  Release 🚀
    pipeline    Commands for pipelines.
                Continuous delivery pipelines to release services.

    deploy      Deploy your service.

  Settings ⚙️
    version     Print the version number.
    completion  Output shell completion code.

Flags
  -h, --help      help for copilot
  -v, --version   version for copilot

Examples
  Displays the help menu for the "init" command.
  `$ copilot init --help`

CLI をインストールできたので,サンプルアプリケーションのデプロイをやってみます.なお,裏で AWS CLI を利用しているため予めaws configureでセットアップしておきましょう.

Copilot CLI を使ったサンプルアプリケーションのデプロイウォークスルー

サンプルアプリケーションはこのリポジトリで公開されていますので,ローカルに pull してきます.静的コンテンツをコンテナに乗せて公開するものになってます.

ローカル環境のセットアップ

まず,copilot initコマンドでローカル環境のセットアップをします.アプリケーション名,サービスのタイプ(フロントエンドかバックエンドか),サービス名,Dockerfile の場所を指定するだけで完了します.

» copilot init
Note: It's best to run this command in the root of your Git repository.
Welcome to the Copilot CLI! We're going to walk you through some questions
to help you get set up with an application on ECS. An application is a collection of
containerized services that operate together.

Application name: sample-app

Service type: Load Balanced Web Service
Service name: front-end

Dockerfile: ./Dockerfile
Ok great, we'll set up a Load Balanced Web Service named front-end in application sample-app listening on port 80.

✔ Created the infrastructure to manage services under application sample-app.

✔ Wrote the manifest for service front-end at copilot/front-end/manifest.yml
Your manifest contains configurations like your container size and port (:80).

✔ Created ECR repositories for service front-end.

この時点でディレクトリとしてcopilot が作られ,配下にmanifest.ymlファイルができました.

 » tree
.
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── copilot
│   └── front-end
│       └── manifest.yml
└── index.html

ドキュメントによるとmanifest.ymlcopilot initcopilot svc init実行した結果を CloudFormation テンプレートに変換したファイルです.CloudFormation テンプレートを書く手間を省けるのと,CloudFormation の記法を気にせず環境構築のコードが出来上がるのは開発者としてだいぶ負担が減るなと思います.

# The manifest for the "front-end" service.
# Read the full specification for the "Load Balanced Web Service" type at:
#  https://github.com/aws/amazon-ecs-cli-v2/wiki/Manifests#load-balanced-web-svc

# Your service name will be used in naming your resources like log groups, ECS services, etc.
name: front-end
# The "architecture" of the service you're running.
type: Load Balanced Web Service

image:
  # Path to your service's Dockerfile.
  build: ./Dockerfile
  # Port exposed through your container to route traffic to it.
  port: 80

http:
  # Requests to this path will be forwarded to your service.
  # To match all requests you can use the "/" path.
  path: '/'
  # You can specify a custom health check path. The default is "/"
  # healthcheck: '/'

# Number of CPU units for the task.
cpu: 256
# Amount of memory in MiB used by the task.
memory: 512
# Number of tasks that should be running in your service.
count: 1

# Optional fields for more advanced use-cases.
#
#variables:                    # Pass environment variables as key value pairs.
#  LOG_LEVEL: info
#
#secrets:                      # Pass secrets from AWS Systems Manager (SSM) Parameter Store.
#  GITHUB_TOKEN: GITHUB_TOKEN  # The key is the name of the environment variable, the value is the name of the SSM parameter.

# You can override any of the values defined above by environment.
#environments:
#  test:
#    count: 2               # Number of tasks to run for the "test" environment.

コンテナの環境構築とサンプルアプリケーションのデプロイ

それでは,コンテナの環境構築とアプリケーションのデプロイをします.なお,記事の構成上分離していますが,copilot initコマンドのウィザードでデプロイができます.

All right, you're all set for local development.
Deploy: Yes

✔ Created the infrastructure for the test environment.
- Virtual private cloud on 2 availability zones to hold your services     [Complete]
- Virtual private cloud on 2 availability zones to hold your services     [Complete]
  - Internet gateway to connect the network to the internet               [Complete]
  - Public subnets for internet facing services                           [Complete]
  - Private subnets for services that can't be reached from the internet  [Complete]
  - Routing tables for services to talk with each other                   [Complete]
- ECS Cluster to hold your services                                       [Complete]
- Application load balancer to distribute traffic                         [Complete]
✔ Linked account XXXXXXXXXXXX(AWSアカウント番号) and region ap-northeast-1 to application sample-app.

✔ Created environment test in region ap-northeast-1 under application sample-app.
Sending build context to Docker daemon  77.82kB
Step 1/3 : FROM nginx
latest: Pulling from library/nginx
8559a31e96f4: Already exists
8d69e59170f7: Pull complete
3f9f1ec1d262: Pull complete
d1f5ff4f210d: Pull complete
1e22bfa8652e: Pull complete
Digest: sha256:21f32f6c08406306d822a0e6e8b7dc81f53f336570e852e25fbe1e3e3d0d0133
Status: Downloaded newer image for nginx:latest
 ---> 2622e6cca7eb
Step 2/3 : EXPOSE 80
 ---> Running in ff4d317656d1
Removing intermediate container ff4d317656d1
 ---> 26762c0d19ed
Step 3/3 : COPY index.html /usr/share/nginx/html
 ---> 418ae089702d
Successfully built 418ae089702d
Successfully tagged XXXXXXXXXXXX.dkr.ecr.ap-northeast-1.amazonaws.com/sample-app/front-end:f8d65d4
Login Succeeded
The push refers to repository [XXXXXXXXXXXX.dkr.ecr.ap-northeast-1.amazonaws.com/sample-app/front-end]
f2ed02c7c10a: Pushed
f978b9ed3f26: Pushed
9040af41bb66: Pushed
7c7d7f446182: Pushed
d4cf327d8ef5: Pushed
13cb14c2acd3: Pushed
f8d65d4: digest: sha256:234bf1c50d5b5b0f27abaec5be3e2b33cf1f81f0caa3f3a5c015cb0610e79004 size: 1570


✔ Deployed front-end, you can access it at http://XXXX.ap-northeast-1.elb.amazonaws.com.

http://XXXX.ap-northeast-1.elb.amazonaws.com にアクセスしてみるとコンテンツが表示されました.ここまでターミナルのウィザードに沿って選択肢を選ぶだけで ECS クラスター環境とコンテナを動かし,コンテンツのデプロイがシュッと完了しました.

f:id:sadayoshi_tada:20200701005045p:plain

環境のクリーンアップ

サンプルアプリケーションの実行環境削除もcopilot app delete --env-profiles test=default一発で終わり,CloudFormation スタックを削除する動きをとります.環境作りから削除までターミナルで完結できました.

» copilot app delete --env-profiles test=default
Are you sure you want to delete application sample-app? Yes
✔ Deleted service front-end from environment test.
✔ Deleted service front-end resources from application sample-app.
✔ Deleted service front-end from application sample-app.
✔ Deleted environment test from application sample-app.
✔ Cleaned up deployment resources.
✔ Deleted application resources.
✔ Deleted application configuration.
✔ Deleted local .workspace file.

まとめ

Copilot CLI」でのコンテナ環境構築とアプリケーションデプロイをさらいました.少ないコマンドで環境構築もデプロイもスピーディーに(シュッと)できました.「ecs-cli」の後継ツールとして今後利用される機会が増えていくものと予想されるので,ベータ版の頃から触って関わっていく機会だと思い,僕もこれから使っていきたいです.この記事で「Copilot」を使ってみるきっかけになれば幸いです.