Inspired by https://qiita.com/masaminh/items/17edb2aaeb78c4c7274e
Created
January 29, 2022 02:14
-
-
Save yuya-takeyama/b86d5d3b5b46c4ae66ecbeac318ff11b to your computer and use it in GitHub Desktop.
Example of a Terraform module that creates an API Gateway to send requests to an arbitrary API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
resource "random_string" "api-id" { | |
length = "16" | |
special = false | |
} | |
resource "aws_api_gateway_rest_api" "main" { | |
name = "http-caller-${random_string.api-id.result}" | |
description = "Call ${var.method} ${var.uri}" | |
body = jsonencode({ | |
openapi = "3.0.1" | |
info = { | |
title = "example" | |
version = "1.0" | |
} | |
paths = { | |
"/" = { | |
lower(var.method) = { | |
x-amazon-apigateway-integration = { | |
httpMethod = var.method | |
payloadFormatVersion = "1.0" | |
type = "HTTP_PROXY" | |
uri = var.uri | |
} | |
} | |
} | |
} | |
}) | |
endpoint_configuration { | |
types = ["REGIONAL"] | |
} | |
} | |
resource "aws_api_gateway_deployment" "main" { | |
rest_api_id = aws_api_gateway_rest_api.main.id | |
triggers = { | |
redeployment = sha1(jsonencode(aws_api_gateway_rest_api.main.body)) | |
} | |
lifecycle { | |
create_before_destroy = true | |
} | |
} | |
resource "aws_api_gateway_stage" "prod" { | |
deployment_id = aws_api_gateway_deployment.main.id | |
rest_api_id = aws_api_gateway_rest_api.main.id | |
stage_name = "prod" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
output "api_endpoint" { | |
value = trimsuffix(trimprefix(aws_api_gateway_deployment.main.invoke_url, "https://"), "/") | |
} | |
output "method" { | |
value = var.method | |
} | |
output "stage" { | |
value = aws_api_gateway_stage.prod.stage_name | |
} | |
output "path" { | |
value = "/" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
variable "method" { | |
type = string | |
default = "GET" | |
} | |
variable "uri" { | |
type = string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment