Skip to content

Commit abbd9ea

Browse files
authored
Merge pull request #26 from DNXLabs/ssh_key_pair
Optionally, private key can be generated to connect to ec2 of ecs nodes
2 parents d185f24 + dd218bf commit abbd9ea

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

_outputs.tf

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,7 @@ output "alb_secgrp_id" {
9797
output "efs_fs_id" {
9898
value = try(aws_efs_file_system.ecs[0].id, "")
9999
}
100+
101+
output "private_key_pem" {
102+
value = try(tls_private_key.algorithm[0].private_key_pem, "")
103+
}

_variables.tf

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,3 +289,13 @@ variable "fargate_only" {
289289
default = false
290290
description = "Enable when cluster is only for fargate and does not require ASG/EC2/EFS infrastructure"
291291
}
292+
293+
variable "ec2_key_enabled" {
294+
default = false
295+
description = "Generate a SSH private key and include in launch template of ECS nodes"
296+
}
297+
298+
variable "vpn_cidr" {
299+
default = ["10.37.0.0/16"]
300+
description = "Cidr of VPN to grant ssh access to ECS nodes"
301+
}

ec2-launch-template.tf

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,21 @@ resource "aws_launch_template" "ecs" {
3333

3434
user_data = base64encode(data.template_file.userdata[0].rendered)
3535

36+
key_name = var.ec2_key_enabled ? aws_key_pair.generated_key[0].key_name : null
37+
3638
lifecycle {
3739
create_before_destroy = true
3840
}
3941
}
42+
43+
resource "tls_private_key" "algorithm" {
44+
count = var.ec2_key_enabled ? 1 : 0
45+
algorithm = "RSA"
46+
rsa_bits = 4096
47+
}
48+
49+
resource "aws_key_pair" "generated_key" {
50+
count = var.ec2_key_enabled ? 1 : 0
51+
key_name = "${var.name}-key"
52+
public_key = tls_private_key.algorithm[0].public_key_openssh
53+
}

sg-ecs-nodes.tf

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ resource "aws_security_group_rule" "all_from_alb_internal_to_ecs_nodes" {
3232
source_security_group_id = aws_security_group.alb_internal[0].id
3333
}
3434

35+
resource "aws_security_group_rule" "ssh_from_vpn_to_ecs_nodes" {
36+
count = var.ec2_key_enabled ? 1 : 0
37+
38+
description = "ssh from VPN"
39+
type = "ingress"
40+
from_port = 22
41+
to_port = 22
42+
protocol = "tcp"
43+
cidr_blocks = var.vpn_cidr
44+
security_group_id = aws_security_group.ecs_nodes.id
45+
}
46+
3547
resource "aws_security_group_rule" "all_from_ecs_nodes_to_ecs_nodes" {
3648
description = "Traffic between ECS nodes"
3749
type = "ingress"

0 commit comments

Comments
 (0)