Skip to content

Instantly share code, notes, and snippets.

@yuya-takeyama
Created January 29, 2022 02:14
Show Gist options
  • Save yuya-takeyama/b86d5d3b5b46c4ae66ecbeac318ff11b to your computer and use it in GitHub Desktop.
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
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"
}
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 = "/"
}
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