しばやん雑記

Azure とメイドさんが大好きなフリーランスのプログラマーのブログ

CircleCI を使って C# で書いた AWS Lambda Function のデプロイを自動化する

前までは AWS Lambda のコードを GitHub で管理する方法に悩んでいたんですが、C# 対応で .NET Core のツールが用意されたので CircleCI などでビルドしてデプロイすることが簡単になりました。

C# サポートについて発表されたブログでも、下の方に dotnet CLI が便利に使えるよって書いてました。

The Amazon.Lambda.Tools NuGet package adds commands to the new dotnet CLI that allow you to deploy your Lambda functions and serverless applications to AWS, no matter what platform you're on. Even if you are developing in Visual Studio on Windows, the AWS Lambda tools in the dotnet CLI are helpful for setting up a CI/CD pipeline for your application.

Announcing C# Support for AWS Lambda | AWS Compute Blog

dotnet lambda というサブコマンドは良い使い方だと思います。

毎回 Visual Studio を使ってデプロイするのは手間なので、この間書いた SendGrid の Event Webhook を受け取るサンプルを使って、CircleCI からのデプロイを試しました。

Lambda に作成した関数をデプロイためには lambda deploy-function を実行すればいいみたいですが、ヘルプを見るとパラメータが結構多いです。

毎回指定するのは手間なので、ここは aws-lambda-tools-defaults.json を用意しておきます。

{
  "Information" : [
    "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
    "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",

    "dotnet lambda help",

    "All the command line options for the Lambda command can be specified in this file."
  ],

  "profile": "default",
  "region" : "ap-northeast-1",
  "configuration" : "Release",
  "framework" : "netcoreapp1.0",
  "function-runtime":"dotnetcore1.0",
  "function-memory-size" : 256,
  "function-timeout" : 30,
  "function-handler" : "AWSLambda1::AWSLambda1.Function::FunctionHandler"
}

Visual Studio で新しい AWS Lambda のプロジェクトを作成すると同時に作成されているはずです。profile と region が空っぽなので profile は default に、region は使うリージョンの名前を入れます。

profile を default にしておくと、CircleCI で設定した認証情報が使われます。

f:id:shiba-yan:20161204231508p:plain

最後に circle.yml にビルドとデプロイのためのコマンドを書いておきます。やってることはシンプルです。

一応説明しておくと、最初に .NET Core のインストールと NuGet パッケージの復元を行ってから、ビルドが通るかを確認。最後に Lambda へのデプロイコマンドを実行しています。

dependencies:
  pre:
    - sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main" > /etc/apt/sources.list.d/dotnetdev.list'
    - sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
    - sudo apt-get update
    - sudo apt-get install dotnet-dev-1.0.0-preview2-003131
  override:
    - dotnet restore

test:
  override:
    - cd AWSLambda1 && dotnet build

deployment:
  master:
    branch: master
    commands:
      - cd AWSLambda1 && dotnet lambda deploy-function event-callback-function

CircleCI は Ubuntu が使われているので .NET Core も Ubuntu 用をインストールしています。

実際にビルドすると Lambda へのデプロイが行われていることが CircleCI のログから確認できます。

f:id:shiba-yan:20161204231434p:plain

AWS CLI を使うことなく .NET Core のツールチェーンだけで完結してしまうのはかなり便利でした。

既に Node.js で書いてある Lambda のコードを C# で書き直して CI/CD に乗せようかと思っていましたが、CircleCI から簡単にデプロイが出来ると分かったので満足です。