LoginSignup
1
1

More than 5 years have passed since last update.

MAC環境にAnsible導入後、AWSサービス構築までの道〜⑤API Gateway〜

Last updated at Posted at 2018-10-10

第5回
AnsibleでAPI Gatewayを構築し、Lambdaポリシーの設定を行う。
API Gatewayのモジュールは提供されているようですが、新規構築ができないのでは?と思い、今回はaws apigatewayコマンドを使用して構築を行う。

やりたいこと

  1. 既存のAPIからクローン
  2. API情報を取得し、Lambda function名を変更
  3. ステージの作成
  4. Lambdaポリシー追加(トリガーの追加)
    ===khskさんスペルミスの指摘ありがとうございました!(10/11追記)===

create_apigateway.yml作成

変数化できる部分はvars_filesにまとめています。

create_apigateway.yml
# aws apigateway create-rest-apiにて作成
# --clone-from {{ gateway_id }}  でClone元のgateway_idを指定する
- name: Create RestApi
  shell: aws apigateway create-rest-api --name '{{ prefix }}-{{ project_name }}-image-resize' --description '{{ prefix }}-{{ project_name }}-image-resize' --clone-from {{ gateway_id }}
  register: api_info

# aws apigateway情報を変数に代入
- name: Set Api Info
  set_fact: api_info_json="{{ api_info.stdout | from_yaml }}"

# Resources情報の取得
- name: Get Resources
  shell: aws apigateway get-resources --rest-api-id "{{ api_info_json.id }}"
  register: resources_info

- name: Set Api Info
  set_fact: resources_info_json="{{ resources_info.stdout }}"

# Lambda Function名の変更(事前に作成したLambda関数名を指定)
- name: Update Lambda Function
  shell: aws apigateway update-integration --rest-api-id "{{ api_info_json.id }}" --resource-id "{{ resources_info_json['items'].1.id }}" --http-method GET --patch-operations op='replace',path='/uri',value='arn:aws:apigateway:{{ region_east }}:lambda:path/2015-03-31/functions/arn:aws:lambda:{{ region_east }}:{{ account_id }}:function:{{ prefix }}-{{ project_name }}/invocations'

# ステージ作成
- name: Create Stage (API Deploy)
  shell: aws apigateway create-deployment --region "{{ region_east }}" --rest-api-id "{{ api_info_json.id }}" --stage-name '{{ stage_name }}'

# Lambdaポリシー追加(トリガーの設定)
# lambda_policyモジュールを使用
- name: Add Policy Lambda
  lambda_policy:
    aws_access_key: "{{ key }}"
    aws_secret_key: "{{ secret }}"
    region: "{{ region_east }}"
    state: "{{ state | default('present') }}"
    function_name: "{{ prefix }}-{{ project_name }}"
    statement_id: lambda-s3-myBucket-create-data-log
    action: lambda:InvokeFunction
    principal: "apigateway.{{ aws_domain }}"
    source_arn: "arn:aws:execute-api:{{ region_east }}:{{ account_id }}:{{ api_info_json.id }}/*/GET/*"

実行

以下コマンドにて実行。
「-vvv」をつけることで、詳細な実行ログが出力されます。
エラーが出ている際など、非常に助かるので常にオプション付与して実行しています!

ansible-playbook -vvv -i localhost, -c local create_apigateway.yml

マネージメントコンソール確認

<API Gateway>
API Gatewayのリソース、ステージが作成されていることを確認。
またLambda function名が変更されていることを確認。

<Lambda>
トリガーにAPI Gatewayが追加されていること。

感想

Lambdaのトリガーを設定するところで結構苦戦しました。
しっかりと仕組みを理解していないとダメですね…

1
1
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
1
1