目次

概要

EC2インスタンス上にJenkinsをインストールして、API Gateway & Lambda をテスト/デプロイする環境を構築する。

IAMロールの作成

マネジメントコンソール からCodeCommit にアクセスする為のEC2用のロールを作成する。

TODO: アタッチするポリシーを書く

IAMユーザの作成

マネジメントコンソール から デプロイ等に使用するIAMユーザを作成する。

TODO: アタッチするポリシーを書く

CodeCommitリポジトリの作成

マネジメントコンソール からリポジトリを作成しておく。

EC2インスタンスの作成

マネジメントコンソール からJenkinsをインストールするEC2インスタンスを作成する。
※セキュリティグループでポート 8080 を許可しておく事。
※先程作成しておいたIAMロールを設定しておく事。

EC2インスタンスの設定

EC2インスタンスに接続して以下の作業を行う。

ec2-user用の aws-cli の設定

確認用に ec2-user 用に aws-cli の設定をしておく。
ここでは、作成しておいたIAMユーザの AWS Access Key ID、AWS Secret Access Key、リージョン等を設定する。

aws configure
AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: XXXXX.......XXXXXX
Default region name [None]: ap-northeast-1
Default output format [None]:

ec2-user 用の git の設定

確認用に ec2-user 用に git クライアントの設定を行っておく。
認証にはIAMを使用する為、以下の通り設定する。

git config --global credential.helper '!aws codecommit credential-helper $@'
git config --global credential.useHttpPath true
git config --global user.name "ユーザ名"
git config --global user.email "メールアドレス"

CodeCommit へのアクセス確認

先ほど作成した CodeCommit リポジトリにIAMでアクセスできるか確認する。

git clone https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/Xxxxxxx

※Jenkins からのアクセスは jenkinsユーザでのアクセスになる為、別途設定が必要。(後述)

Jenkinsのインストール

起動したEC2インスタンスで以下の作業を行う。
※参考: https://d1.awsstatic.com/Projects/P5505030/aws-project_Jenkins-build-server.pdf

JDK8 のインストール

sudo yum install -y java-1.8.0-openjdk-devel

使用するJavaバージョンの切替

sudo alternatives --config java

2 プログラムがあり 'java' を提供します。

  選択       コマンド
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   2           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

Enter を押して現在の選択 [+] を保持するか、選択番号を入力します:2

バージョンが切り替わったか確認

java -version
openjdk version "1.8.0_201"
OpenJDK Runtime Environment (build 1.8.0_201-b09)
OpenJDK 64-Bit Server VM (build 25.201-b09, mixed mode)

Gitのインストール

sudo yum install git -y

Jenkinsのインストール

sudo yum update -y
sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat/jenkins.io.key
sudo yum install jenkins -y

Jenkins ユーザ用の git 設定

jenkins からCodeCommit にアクセスする際に IAMロールでアクセスするように設定する。
jenkins ユーザのホームディレクトリは /var/lib/jenkins になっているので、その配下に .gitconfig を以下の通り作成する。

sudo touch /var/lib/jenkins/.gitconfig
sudo chmod 664 /var/lib/jenkins/.gitconfig
sudo chown jenkins:jenkins /var/lib/jenkins/.gitconfig
sudo vim /var/lib/jenkins/.gitconfig

[user]
        name = ユーザ名
        email = メールアドレス
[credential]
        helper = !aws codecommit credential-helper $@
        useHttpPath = true

Jenkinsユーザ用の aws-cliの設定

作成しておいたIAMユーザの AWS Access Key ID、AWS Secret Access Key、リージョン等を設定する。

sudo -u jenkins aws configure
AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: XXXXX.......XXXXXX
Default region name [None]: ap-northeast-1
Default output format [None]:

Jenkinsのサービス開始

sudo service jenkins start

Jenkinsインストール用の管理者パスワードを確認

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

処理の作成

デプロイする処理(API Gateway 及び Lambda)を作成する。

準備

git チェックアウト

mkdir ~/workspace
git clone https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/SampleRepo    # 作成しておいたCodeCommitリポジトリのURL
cd SampleRepo
git checkout develop

処理の作成

book.py

# coding: utf-8
"""
サンプルLambda.
"""

import json


def index(event, context):
    """本の一覧を取得する.

    Args:
        event (obj): イベント
        context (obj): コンテキスト

    """
    # 本の一覧
    books = [{'isbn': f'sample{i+1:03d}', 'title': f'BOOK{i+1:03d}'} for i in range(10)]

    # 戻り値
    response = {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps({'list': books, 'count': len(books)})
    }

    return response

template.yml

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Test serverless application.

Resources:

  BookFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: book.index
      Runtime: python3.6
      Events:
        List:
          Type: Api
          Properties:
            Path: /book
            Method: get

ローカルで動作確認

作成した処理をSAMローカルで動作確認する。

sam-cli インストール

sudo yum -y install gcc
sudo yum install python-devel
pip install --upgrade pip
pip install --user aws-sam-cli

python3.6インストール

yum list available | grep "python36"
sudo yum install python36

Dockerインストール&起動

sudo yum install -y docker
sudo service docker start
sudo usermod -a -G docker ec2-user

SAMローカルを起動

いったんログアウト。

exit

再度ログインして SAM Local起動

cd ~/workspace/SampleRepo
sam local start-api --template template.yml
2019-01-01 08:15:11 Found credentials in shared credentials file: ~/.aws/credentials
2019-01-01 08:15:11 Mounting BookFunction at http://127.0.0.1:3000/book [GET]
2019-01-01 08:15:11 You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
2019-01-01 08:15:11  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)

別のターミナルを起動&ログインして 動作確認

curl http://127.0.0.1:3000/book
{"list": [{"isbn": "sample001", "title": "BOOK001"}, {"isbn": "sample002", "title": "BOOK002"}, {"isbn": "sample003", "title": "BOOK003"}, {"isbn": "sample004", "title": "BOOK004"}, {"isbn": "sample005", "title": "BOOK005"}, {"isbn": "sample006", "title": "BOOK006"}, {"isbn": "sample007", "title": "BOOK007"}, {"isbn": "sample008", "title": "BOOK008"}, {"isbn": "sample009", "title": "BOOK009"}, {"isbn": "sample010", "title": "BOOK010"}], "count": 10}

デプロイ用のシェルを作成する

デプロイ処理は Jenkinsでもそのまま使用できるようにシェル化する。

build.sh

#!/bin/bash

# スタック名
DIR_NAME=`basename \`pwd\``
STACK_NAME=`echo $DIR_NAME | sed 's/Repo$/Stack/'`

# アカウントIDの取得
ACCOUNT_ID=`aws sts get-caller-identity | grep Account | awk '{print $2}' | sed -e "s/[^0-9]//g"`

# S3バケットがない場合は作る(バケット名は世界で唯一である必要がある為、末尾にアカウントID等を付与しておく)
BUCKET_NAME=my-cloudformation-templates-${ACCOUNT_ID}
BUCKET_COUNT=`aws s3api list-buckets | grep -e "\"${BUCKET_NAME}\"" | wc -l`
if [ "${BUCKET_COUNT}" == "0" ]; then
    echo aws s3api create-bucket --create-bucket-configuration '{"LocationConstraint": "ap-northeast-1"}' --bucket $BUCKET_NAME
fi

# 検証&パッケージング&デプロイ
aws cloudformation validate-template --template-body file://template.yml \
  && aws cloudformation package --template-file template.yml --s3-bucket $BUCKET_NAME --output-template-file packaged-template.yml \
  && aws cloudformation deploy --template-file packaged-template.yml --stack-name $STACK_NAME --capabilities CAPABILITY_IAM

git リポジトリにプッシュ

git commit & push

git add .
git commit -m 'first commit'
git push

masterにマージ

git checkout master
git merge develop
git push

Jenkinsの設定

Jenkinsにログイン

http://ec2-XX-XXX-XX-XX.ap-northeast-1.compute.amazonaws.com:8080 にアクセスし、Administrator password に、先程確認した管理者パスワードを入力する
※ [Install suggested plugins] で適当なプラグインをインストールしておく。

ジョブの作成

TODO:

XXXXXXXXXX

TODO:

トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS