• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language HCL
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Terraform module to provision a NAT Instance using an Auto Scaling Group and Spot Instance from $1/month

terraform-aws-nat-instance CircleCI

This is a Terraform module which provisions a NAT instance.

Features:

  • Providing NAT for private subnet(s)
  • Auto healing using an auto scaling group
  • Saving cost using a spot instance (from $1/month)
  • Fixed source IP address by reattaching ENI
  • Supporting Systems Manager Session Manager
  • Compatible with workspaces

Terraform 0.12 or later is required.

Warning: Generally you should use a NAT gateway. This module provides a very low cost solution for testing purpose.

Getting Started

You can use this module with terraform-aws-modules/vpc/aws module as follows:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"

  name                 = "main"
  cidr                 = "172.18.0.0/16"
  azs                  = ["us-west-2a", "us-west-2b", "us-west-2c"]
  private_subnets      = ["172.18.64.0/20", "172.18.80.0/20", "172.18.96.0/20"]
  public_subnets       = ["172.18.128.0/20", "172.18.144.0/20", "172.18.160.0/20"]
  enable_dns_hostnames = true
}

module "nat" {
  source = "int128/nat-instance/aws"

  name                        = "main"
  vpc_id                      = module.vpc.vpc_id
  public_subnet               = module.vpc.public_subnets[0]
  private_subnets_cidr_blocks = module.vpc.private_subnets_cidr_blocks
  private_route_table_ids     = module.vpc.private_route_table_ids
}

resource "aws_eip" "nat" {
  network_interface = module.nat.eni_id
  tags = {
    "Name" = "nat-instance-main"
  }
}

Now create an EC2 instance in the private subnet to verify the NAT configuration. Open the AWS Systems Manager Session Manager, log in to the instance and make sure you have external access from the instance.

See also the example.

How it works

This module provisions the following resources:

  • Auto Scaling Group with mixed instances policy
  • Launch Template
  • Elastic Network Interface
  • Security Group
  • IAM Role for SSM and ENI attachment
  • VPC Route (optional)

You need to attach your elastic IP to the ENI.

Take a look at the diagram:

diagram

By default the latest Amazon Linux 2 image is used. You can set image_id for a custom image.

The instance will execute runonce.sh and snat.sh to enable NAT as follows:

  1. Attach the ENI to eth1.
  2. Set the kernel parameters for IP forwarding and masquerade.
  3. Switch the default route to eth1.

Configuration

User data

You can set additional write_files and runcmd section. For example,

module "nat" {
  user_data_write_files = [
    {
      path : "/opt/nat/run.sh",
      content : file("./run.sh"),
      permissions : "0755",
    },
  ]
  user_data_runcmd = [
    ["/opt/nat/run.sh"],
  ]
}

See also cloud-init modules and the example for more.

SSH access

You can enable SSH access by setting key_name option and opening the security group. For example,

module "nat" {
  key_name = "YOUR_KEY_PAIR"
}

resource "aws_security_group_rule" "nat_ssh" {
  security_group_id = module.nat.sg_id
  type              = "ingress"
  cidr_blocks       = ["0.0.0.0/0"]
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
}

Migration guide

Upgrade to v2 from v1

This module no longer creates an EIP since v2.

To keep your EIP when you migrate to module v2, rename the EIP in the state as follows:

% terraform state mv -dry-run module.nat.aws_eip.this aws_eip.nat
Would move "module.nat.aws_eip.this" to "aws_eip.nat"

% terraform state mv module.nat.aws_eip.this aws_eip.nat
Move "module.nat.aws_eip.this" to "aws_eip.nat"
Successfully moved 1 object(s).

Contributions

This is an open source software. Feel free to open issues and pull requests.

Requirements

Name Version
terraform >= 0.12.0

Providers

Name Version
aws n/a

Modules

No modules.

Resources

Name Type
aws_autoscaling_group.this resource
aws_iam_instance_profile.this resource
aws_iam_role.this resource
aws_iam_role_policy.eni resource
aws_iam_role_policy_attachment.ssm resource
aws_launch_template.this resource
aws_network_interface.this resource
aws_route.this resource
aws_security_group.this resource
aws_security_group_rule.egress resource
aws_security_group_rule.ingress_any resource
aws_ami.this data source

Inputs

Name Description Type Default Required
enabled Enable or not costly resources bool true no
image_id AMI of the NAT instance. Default to the latest Amazon Linux 2 string "" no
instance_types Candidates of spot instance type for the NAT instance. This is used in the mixed instances policy list(string)
[
"t3.nano",
"t3a.nano"
]
no
key_name Name of the key pair for the NAT instance. You can set this to assign the key pair to the NAT instance string "" no
name Name for all the resources as identifier string n/a yes
private_route_table_ids List of ID of the route tables for the private subnets. You can set this to assign the each default route to the NAT instance list(string) [] no
private_subnets_cidr_blocks List of CIDR blocks of the private subnets. The NAT instance accepts connections from this subnets list(string) n/a yes
public_subnet ID of the public subnet to place the NAT instance string n/a yes
ssm_policy_arn SSM Policy to be attached to instance profile string "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" no
tags Tags applied to resources created with this module map(string) {} no
use_spot_instance Whether to use spot or on-demand EC2 instance bool true no
user_data_runcmd Additional runcmd section of cloud-init list(list(string)) [] no
user_data_write_files Additional write_files section of cloud-init list(any) [] no
vpc_id ID of the VPC string n/a yes

Outputs

Name Description
eni_id ID of the ENI for the NAT instance
eni_private_ip Private IP of the ENI for the NAT instance
iam_role_name Name of the IAM role for the NAT instance
sg_id ID of the security group of the NAT instance

More Repositories

1

kubelogin

kubectl plugin for Kubernetes OpenID Connect authentication (kubectl oidc-login)
Go
1,100
star
2

gradle-ssh-plugin

Gradle SSH Plugin
Groovy
310
star
3

gradle-swagger-generator-plugin

Gradle plugin for OpenAPI YAML validation, code generation and API document publishing
Groovy
270
star
4

gpup

A command to upload photos and movies to Google Photos Library using the official Google Photos Library API
Go
211
star
5

argocd-commenter

Notify ArgoCD Application status via Pull Request comment or GitHub Deployment API
Go
112
star
6

groovy-ssh

SSH automation tool based on Groovy DSL
Groovy
111
star
7

slack-docker

Slack/Mattermost Integration for notifying Docker events, written in Go
Go
109
star
8

kauthproxy

Local authentication proxy for Kubernetes Dashboard (kubectl auth-proxy)
Go
100
star
9

devops-kompose

[DEPRECATED] DevOps tools on Kubernetes with Helm charts
Smarty
80
star
10

datadog-actions-metrics

Send GitHub Actions metrics to Datadog for developer experience
TypeScript
58
star
11

terraform-aws-kops-alb

Terraform module for ALB, Route53 and nginx-ingress with kops on AWS
HCL
52
star
12

bntp

Lightweight New Tab Page with Bookmarks by Chrome extension
TypeScript
51
star
13

devops-compose

DevOps tools on Docker Compose
Shell
42
star
14

oauth2cli

Go package of OAuth 2.0 authorization for command line tools, which allows simple authorization flow for better UX
Go
40
star
15

kubectl-external-forward

kubectl plugin to connect to external host via Envoy Proxy in Kubernetes cluster
Go
40
star
16

gistnote

Evernote like Gist editor
JavaScript
40
star
17

wslexec

A wrapper to run Linux command inside WSL (Windows Subsystem for Linux) from native apps
Go
39
star
18

idea-fsnotifier-wsl

IntelliJ IDEA fsnotifier for WSL (Windows Subsystem for Linux)
C
36
star
19

kubernetes-dashboard-proxy

[DEPRECATED] Helm chart with OpenID Connect Proxy for Kubernetes Dashboard
Smarty
36
star
20

gradle-plugin-starter

Gradle plugin template project
Groovy
35
star
21

spock-spring-boot-example

An example of testing Spring Boot application with Spock framework
Groovy
33
star
22

kaniko-action

Build container image using Kaniko in GitHub Actions
TypeScript
27
star
23

feign-oauth2-example

Example of Spring Cloud Feign and Spring Security OAuth2
Groovy
26
star
24

typescript-actions-monorepo

Template of monorepo for GitHub Actions written in TypeScript
TypeScript
25
star
25

helm-github-pages

Publish your Kubernetes Helm Charts on GitHub Pages. DEPRECATED: please use https://github.com/helm/chart-releaser
Shell
22
star
26

ghcp

Tool to fork a repository, commit files, create a pull request and upload assets using GitHub API
Go
20
star
27

docker-build-cache-config-action

Generate effective cache parameters for docker/build-push-action in GitHub Actions
TypeScript
18
star
28

create-ecr-repository-action

Action to create Amazon ECR or ECR Public repository and put lifecycle policy
TypeScript
18
star
29

ktunnels

Kubernetes controller for port-forwarding from your machine to remote hosts via Envoy TCP proxy
Go
17
star
30

terraform-aws-kubernetes-irsa

Terraform module for IAM Roles for Service Accounts (IRSA) on self-hosted Kubernetes cluster such as kops
HCL
17
star
31

hide-comment-action

Action to hide (minimize) comments in pull request
TypeScript
16
star
32

keycloak-bulk

A bulk operation tool for the Keycloak identity manager
JavaScript
15
star
33

gradleupdate

Gradle badge service
Go
13
star
34

samba-dfree

Disk space calculator for Samba
Go
13
star
35

httpstub

Declarative YAML based HTTP stub server for integration test
Java
12
star
36

diff-action

Post diff to comment of pull request in GitHub Actions
TypeScript
12
star
37

yamlpatch

Apply JSON Patch to YAML Document preserving positions and comments
Go
11
star
38

hello-envoy

Example of Envoy TCP Proxy with dynamic filesystem configuration
Makefile
11
star
39

android-ble-button

BLE button app on Android
Kotlin
10
star
40

typescript-action

Template of TypeScript Action with Prettier, ESLint, TSConfig, Jest and automated release
TypeScript
10
star
41

appengine-scala-starter

App Engine Scala Template with Unfiltered and Scalate
Scala
10
star
42

hello-google-photos

Uploading photos using Google Photos Library API in Go
Go
10
star
43

appengine-spring-boot-starter

Spring Boot + Kotlin + App Engine Standard Environment
Kotlin
10
star
44

wait-for-workflows-action

Wait for workflow runs in GitHub Actions, for enabling status check in branch protection rule
TypeScript
9
star
45

kustomize-action

Run kustomize build in parallel in GitHub Action
TypeScript
9
star
46

gitbucket-docker

GitBucket Docker Image and Kubernetes Helm Chart
Shell
8
star
47

jira-to-slack

Slack / Mattermost Integration to notify JIRA events
Go
8
star
48

comment-action

Action to run a command and post a comment to pull request
TypeScript
8
star
49

spring-boot-kotlin-starter

Spring Boot and Kotlin starter
Kotlin
7
star
50

errto

Rewrite Go error handling code between errors, golang.org/x/xerrors and github.com/pkg/errors
Go
7
star
51

docker-manifest-create-action

Create a multi-architectures container image in GitHub Actions
TypeScript
7
star
52

gradle-starter

Hello World application with Gradle
Groovy
7
star
53

release-typescript-action

Automate release of TypeScript Action
TypeScript
7
star
54

deploy-lambda-action

Deploy code or container image to existing Lambda function in GitHub Actions
TypeScript
6
star
55

spring-cloud-api-gateway-example

Example Implementation of API Gateway Pattern using Spring Cloud Netflix
Groovy
6
star
56

awsswitch

Export the credentials variables to switch a role with MFA, interoperable with AWS CLI
Go
6
star
57

oauth2dev

Go package of OAuth 2.0 Device Authorization Grant (RFC 8628), compatible with golang.org/x/oauth2
Go
6
star
58

kubebuilder-updates

Scaffold code generated by the latest version of kubebuilder for patch upgrade
Go
5
star
59

dotfiles

Dot files of my environment
Shell
5
star
60

assign-pull-request-reviewers-action

Action to assign pull request reviewers by label
TypeScript
5
star
61

hubot-jira

A Hubot script for notifying JIRA events and creating backlogs on JIRA
CoffeeScript
4
star
62

deployment-action

Action to create GitHub Deployment to receive notifications from external deployment tool
TypeScript
4
star
63

aqua-action

[DEPRECATED] Use https://github.com/aquaproj/aqua-installer instead
TypeScript
4
star
64

kustomtree

A tool to sort Kustomize manifests into kind based directories
Go
4
star
65

send-datadog-action

General-purpose action to send custom metric or event to Datadog
TypeScript
4
star
66

twitter-feed-function

[OBSOLETE] Twitter Feed RSS on Google Cloud Functions
JavaScript
4
star
67

kind-oidc

How to set up Kubernetes OpenID Connect authentication using Kind
Shell
4
star
68

slack

Slack/Mattermost Incoming Webhooks API Client for Go
Go
4
star
69

kubectl-tree-e2e-test

E2E test of kubectl-tree to show how to test with Kind on GitHub Actions
Makefile
4
star
70

update-generated-files-action

Push commit to pull request for auto-fix in GitHub Actions
TypeScript
4
star
71

github-api-rate-limit-metrics-action

Action to send metrics of GitHub API rate limit to Datadog
TypeScript
4
star
72

goxzst

A command to make cross build, ZIP archives, SHA digests and render templates
Go
4
star
73

latest-gradle-wrapper

Latest version of Gradle Wrapper, continuously updated by CI
3
star
74

flux-continuous-deployment-demo

A demo of Continuous Deployment with Flux using the automated image update feature
Makefile
3
star
75

hubot-gitbucket

Hubot script for GitBucket notification
JavaScript
3
star
76

list-associated-pull-requests-action

List associated pull requests of a pull request in monorepo by GitHub Actions
TypeScript
3
star
77

wait-for-docker-image-action

Action to wait until Docker image is available at current Git revision
TypeScript
3
star
78

kubectl-snippets

Just snippets of kubectl
3
star
79

rename-exif

A command line tool to rename image files by Exif data
Ruby
3
star
80

typescript-k6

Write grafana/k6 in TypeScript, run in GitHub Actions and send to Datadog
TypeScript
3
star
81

renovate-merge-bot

Assist automerge of Renovate pull requests in GitHub Actions
TypeScript
3
star
82

go-renovate-config

Renovate config for Go and Kubernetes
3
star
83

taskwalls.appspot.com

ToDo Management Application
JavaScript
3
star
84

workflow-run-summary-action

Summarize workflow run for Slack notification
TypeScript
3
star
85

oauth2-github-app

Go package for authenticating with GitHub App Installation token, interoperable with golang.org/x/oauth2 package
Go
3
star
86

akoi-action

Action to install packages using https://github.com/suzuki-shunsuke/akoi
TypeScript
3
star
87

kubesnapshot

A command to take snapshots of EBS volumes owned by Kubernetes cluster, written in Go and ready on AWS Lambda or Kubernetes Cron Job
Go
3
star
88

delete-deployments-action

Clean up outdated GitHub Deployments in GitHub Actions
TypeScript
3
star
89

ssoexec

A wrapper to run third-party tools with AWS SSO
Go
3
star
90

buildx-push-action

[DEPRECATED] GitHub Action to build and push Docker image with BuildKit cache for multi-stage build
Shell
3
star
91

cronjob-runner

A command to run one-shot job from CronJob template and tail container logs in Kubernetes
Go
3
star
92

kube-aws-alb-starter

Kubernetes starter with kube-aws and Terraform
HCL
2
star
93

aggregate-deployments-action

Aggregate GitHub Deployments against commit SHA in GitHub Actions
TypeScript
2
star
94

swagger-security-example

An example project with Swagger security definitions such as OAuth2 and API key
Java
2
star
95

appengine-spring-boot-plugin

Gradle plugin for App Engine Standard and Spring Boot
Groovy
2
star
96

docker-mirror-multiarch

How to mirror a multi-architecture Docker image
2
star
97

kubebuilder-workflows

Reusable workflows for kubebuilder project
Makefile
2
star
98

ses-to-slack

Lambda function to forward mails from AWS SES to Slack/Mattermost
JavaScript
2
star
99

go-release-action

Publish Go binary into GitHub Releases
Go
2
star
100

instagit

Instant Git server providing HTTP access to local repositories
Java
2
star