手動で作った lambda を code として管理する

tl;dr;

既存の lambda をダウンロードし、コンソールを使わず sam を用いて管理する方法をまとめた。deploy 方法から注意事項までを記載。

既存 lambda をダウンロード

 lambda をダウンロードすると大きく2つに分けてダウンロードすることができる。

sam のドキュメントについてはこちら

関数のエクスポートを押下すると、

 

  • AWS SAM ファイルのダウンロード
  • デプロイパッケージのダウンロード

が選択できる。

端的に言うと

  • lambda の設定ファイル
  • プログラムのコード

だ。両方ダウンロードする。

sam のセットアップ

公式ドキュメントの手順を準拠すると、 sam のインストールは以下の通りとなる。

brew tap aws/tap
brew install aws-sam-cli

deploy ディレクトリの初期化

今回は python3.8 を利用するので以下のように設定した。
ダウンロードした zipファイル は unzipコマンドなどで解凍しておく。

sam init


	SAM CLI now collects telemetry to better understand customer needs.

	You can OPT OUT and disable telemetry collection by setting the
	environment variable SAM_CLI_TELEMETRY=0 in your shell.
	Thanks for your help!

	Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html

Which template source would you like to use?
	1 - AWS Quick Start Templates
	2 - Custom Template Location
Choice: 1

Which runtime would you like to use?
	1 - nodejs12.x
	2 - python3.8
	3 - ruby2.5
	4 - go1.x
	5 - java11
	6 - dotnetcore2.1
	7 - nodejs10.x
	8 - nodejs8.10
	9 - python3.7
	10 - python3.6
	11 - python2.7
	12 - java8
	13 - dotnetcore2.0
	14 - dotnetcore1.0
Runtime: 2

Project name [sam-app]: 

Cloning app templates from https://github.com/awslabs/aws-sam-cli-app-templates.git

AWS quick start application templates:
	1 - Hello World Example
	2 - EventBridge Hello World
	3 - EventBridge App from scratch (100+ Event Schemas)
Template selection: 1

-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: python3.8
Dependency Manager: pip
Application Template: hello-world
Output Directory: .

Next steps can be found in the README file at ./sam-app/README.md
    
coco@darkenagy sam % 

ダウンロードした yamlファイル を、 template.yml と言うファイル名に変更する。

mv test-imagemagick.yaml template.yml 

requirements.txt も必要になるので、作成する。使わない場合でも空のファイルを用意する必要があるので、 touch するなり作成する。

touch requirements.txt

以下のように表示されれば成功。

sam build
Building resource 'testimagemagick'
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided
    

ちなみに、sam コマンドでも、.aws 配下の profile を読み込むことも可能。

`sam build –profile cloudformation` 

エラーが発生した場合は debugモード で確認することができる。

sam build --debug

あとは invoke するなり、deploy するなりすればよい。

deploy

`sam deploy –guided`コマンドを利用することで deploy が可能。

% sam deploy --guided

Configuring SAM deploy
======================

	Looking for samconfig.toml :  Not found

	Setting default arguments for 'sam deploy'
	=========================================
	Stack Name [sam-app]: 
	AWS Region [us-east-1]: ap-northeast-1
	#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
	Confirm changes before deploy [y/N]: y
	#SAM needs permission to be able to create roles to connect to the resources in your template
	Allow SAM CLI IAM role creation [Y/n]: y
	Save arguments to samconfig.toml [Y/n]: y

	Looking for resources needed for deployment: Found!

		Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1dc492sz2bqu7
		A different default S3 bucket can be set in samconfig.toml

	Saved arguments to config file
	Running 'sam deploy' for future deployments will use the parameters saved above.
	The above parameters can be changed by modifying samconfig.toml
	Learn more about samconfig.toml syntax at 
	https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

	Deploying with following values
	===============================
	Stack name                 : sam-app
	Region                     : ap-northeast-1
	Confirm changeset          : True
	Deployment s3 bucket       : aws-sam-cli-managed-default-samclisourcebucket-1dc492sz2bqu7
	Capabilities               : ["CAPABILITY_IAM"]
	Parameter overrides        : {}

Initiating deployment
=====================
Uploading to sam-app/9a97ece5eb5fac3dd9dff84a97110722  9611 / 9611.0  (100.00%)
Uploading to sam-app/cac8e2252620a466ff8e4becb2d4a8ed.template  638 / 638.0  (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                                           LogicalResourceId                                                   ResourceType                                                      
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                                               testimagemagick                                                     AWS::Lambda::Function                                             
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:821594579130:changeSet/samcli-deploy1578156109/01d374f5-800c-438e-b4cb-4f25d8d0bc4d


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]:

問題なければyを押す。

2020-01-05 01:42:01 - Waiting for stack create/update to complete

CloudFormation events from changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                     ResourceType                                       LogicalResourceId                                  ResourceStatusReason                             
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                 AWS::Lambda::Function                              testimagemagick                                    -                                                
CREATE_IN_PROGRESS                                 AWS::Lambda::Function                              testimagemagick                                    Resource creation Initiated                      
CREATE_COMPLETE                                    AWS::Lambda::Function                              testimagemagick                                    -                                                
CREATE_COMPLETE                                    AWS::CloudFormation::Stack                         sam-app                                            -                                                
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - sam-app in ap-northeast-1

確認

成功すれば以下の通り作成される。

function name が、意図した名前と違う場合、明示的に指定することができる。

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: An AWS Serverless Specification template describing your function.
Resources:
  testimagemagick:
    Type: 'AWS::Serverless::Function'
    Properties:
      FunctionName: test-imagemagick-123
      Handler: lambda_function.lambda_handler
      Runtime: python3.8
      CodeUri: .
      Description: ''
      MemorySize: 128
      Timeout: 3
      Role: 'arn:aws:iam::123:role/lambdaExecution'
      Layers:
        - 'arn:aws:lambda:ap-northeast-1:123:layer:image-magick:2'

template.yml で`FunctionName`を指定する。

再度`sam build`、 `sam deploy` を行うと、新しい lambda function に置き換わる。

注意点

手動で作り上げた lambda を sam を用いて上書いて管理することはできないのか。
結論、そのままはできない。

現在自分が動かしているものについては、手動で作った lambda は削除し、その後 sam を用いたdepoloy に切替えるなどして対応している。

 

【アップデート】ついに来た!CloudFormationで手動で作成したリソースをStackにインポート可能になりました

 

しかし、CloudForomation で手動で作成したリソースをインポートできるようになったので、これを使えばできるかも。(未確認)

試したことある人いたら twitter でもご一報ください。