2
2

More than 1 year has passed since last update.

Serverlessでlambdaデプロイする手順とデプロイしようとした時のエラー対応

Last updated at Posted at 2022-10-25

読者の対象

  • Serverless初心者でエラーに困る方々

  • windowsユーザ


serverless環境のインストール

# 実行ポリシーを確認(windowsターミナルを管理者実行して実行権限を確認してください)
Get-ExecutionPolicy

# powershellでチョコレートのパッケージインストール
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))


# チョコレートでサーバレスフレームワークインストール
choco install serverless -y


# チョコレートでnodejsを使えるようにインストール
choco install nodejs -y


# チョコレートでpythonを使えるようにインストール
choco install python -y

serverlessのデプロイ先AWSとの連携設定

  1. AWSのプロファイル設定
    (まず自分のAWSでIAMユーザを作成してユーザのポリシーにadministratoraccessをつけます。)
# ローカルにAWSプロファイル登録
# (デフォルト設定を信じると不測の事態が起きるのでデプロイ時にプロファイル指定するため使用します。)
# 例

$ aws configure --profile [sample]
AWS Access Key ID [None]: XXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: XXXXXXXXXXXXXXXX
Default region name [None]: ap-northeast-1
Default output format [None]: json

# 指定プロファイルの確認コマンド
aws configure get region --profile [sample]
aws configure list
すべての設定データを一覧表示するには、aws configure list コマンドを使用します。このコマンドは、構成したすべての設定の AWS CLI 名、それらの値、構成の取得元を表示します。


aws configure list-profiles
すべてのプロファイル名を一覧表示するには、aws configure list-profilesコマンドを使用します。

$ aws configure list-profiles

# 試験としてaws s3 lsでも打ってみる(バケット表示されたら正常である。)
  1. serverlessで何のプロファイルを使うか指定する。
$ serverless config credentials --provider aws --key xxxxx --secret xxxxx



Serverless: Setting up AWS...
Serverless: Saving your AWS profile in "~/.aws/credentials"...

catで設定が追加されていることを確認します。
cat ~/.aws/credentials

serverlessコマンドでAWSへデプロイ

(エラーが多くなってきます)

  1. テンプレートからサービスを作成
$ mkdir app
$ cd app
$ serverless create --template aws-nodejs -p hello-js

✔ Project successfully created in "hello-js" from "aws-nodejs" template (10s)

# どんなファイルが生成されたか確認します。
$ ls
.gitignore
handler.js
serverless.yml

2. -v オプションを付けてデプロイ実行してログを追ってみる

# プロファイル指定したデプロイを行います。

$ serverless deploy --aws-profile my-sls
Warning: Invalid configuration encountered
  at root: unrecognized property 'region'

Learn more about configuration validation here: http://slss.io/configuration-validation

Deploying slstest to stage dev (us-east-1)

✔ Service deployed to stack slstest-dev (106s)

functions:
  hello: slstest-dev-hello (389 B)

1 deprecation found: run 'serverless doctor' for more details

Toggle on monitoring with the Serverless Dashboard: run "serverless"
PS C:\Users\DELL\Desktop\sls\slstest> cat .\serverless.yml
# Welcome to Serverless!
#
# This file is the main config file for your service.
# It's very minimal at this point and uses default values.
# You can always add more config options for more control.
# We've included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
#    docs.serverless.com
#
# Happy Coding!

service: slstest
# app and org for use with dashboard.serverless.com
#app: your-app-name
#org: your-org-name

# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
frameworkVersion: "3"

provider:
  name: aws
  runtime: python3.7

# you can overwrite defaults here
#  stage: dev
region: ap-northeast-1

# you can add statements to the Lambda function's IAM Role here
#  iam:
#    role:
#      statements:
#        - Effect: "Allow"
#          Action:
#            - "s3:ListBucket"
#          Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ]  }
#        - Effect: "Allow"
#          Action:
#            - "s3:PutObject"
#          Resource:
#            Fn::Join:
#              - ""
#              - - "arn:aws:s3:::"
#                - "Ref" : "ServerlessDeploymentBucket"
#                - "/*"

# you can define service wide environment variables here
#  environment:
#    variable1: value1

# you can add packaging information here
#package:
#  patterns:
#    - '!exclude-me.py'
#    - '!exclude-me-dir/**'
#    - include-me.py
#    - include-me-dir/**

functions:
  hello:
    handler: handler.hello
#    The following are a few example events you can configure
#    NOTE: Please make sure to change your handler code to work with those events
#    Check the event documentation for details
#    events:
#      - httpApi:
#          path: /users/create
#          method: get
#      - websocket: $connect
#      - s3: ${env:BUCKET}
#      - schedule: rate(10 minutes)
#      - sns: greeter-topic
#      - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
#      - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx
#      - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx
#      - iot:
#          sql: "SELECT * FROM 'some_topic'"
#      - cloudwatchEvent:
#          event:
#            source:
#              - "aws.ec2"
#            detail-type:
#              - "EC2 Instance State-change Notification"
#            detail:
#              state:
#                - pending
#      - cloudwatchLog: '/aws/lambda/hello'
#      - cognitoUserPool:
#          pool: MyUserPool
#          trigger: PreSignUp
#      - alb:
#          listenerArn: arn:aws:elasticloadbalancing:us-east-1:XXXXXX:listener/app/my-load-balancer/50dc6c495c0c9188/
#          priority: 1
#          conditions:
#            host: example.com
#            path: /hello

#    Define function environment variables here
#    environment:
#      variable2: value2

# you can add CloudFormation resource templates here
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: my-new-bucket
#  Outputs:
#     NewOutput:
#       Description: "Description for the output"
#       Value: "Some output value"
# 初期設定だとregion「us-east-1」にデプロイされます。

# デプロイ後にcloudfomationのファイルが作成されています。
$ cd .serverless
$ ls
cloudformation-template-update-stack.json
cloudformation-template-create-stack.json
serverless-state.json
slstest.zip

# ここからやっぱりCloudFormationを使ってバケットとかビルド成果物のアップロード等を行っているんだな、ということは分かりました。


デプロイしたlambda-functionを削除


デプロイ時発生するエラーの対応

Error:
The security token included in the request is invalid.

指定プロファイルのIAMユーザが権限不足な時、発生するエラーです。
プロファイル指定しなくても起こるので、不測の事態を回避するにも
「--aws-profile 」オプションを使った方がよいでしょう。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2