Skip to content

Commit

Permalink
add vpc_ha and elasting_running_worpress projects, see readme for det…
Browse files Browse the repository at this point in the history
…ails
  • Loading branch information
msacchetti-fl committed Dec 3, 2021
1 parent 913747e commit f470f4f
Show file tree
Hide file tree
Showing 10 changed files with 289 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.env
.terraform*
*.tfstate*
*.zip
20 changes: 20 additions & 0 deletions elasting_running_worpress/elastic.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
data "aws_instance" "alive" {

filter {
name = "image-id"
values = [ "ami-63ec5b1e"]
}

filter {
name = "instance-state-name"
values = [ "running"]
}

}


resource "aws_eip" "bar" {
vpc = true

instance = data.aws_instance.alive.id
}
17 changes: 17 additions & 0 deletions elasting_running_worpress/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "3.65.0"
}
}

required_version = ">= 0.14.9"
}

provider "aws" {} # provided via env file

variable "aws_region" {
# provided via env file
description = "Aws region to use"
}
10 changes: 10 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ make PROJECT=vm_import destoy

# Available projects


## vpc_ha

Creates a VPC with a public and a private subnet for each abailability zone.
Creates an autoscaling group to maintain a single worpress insance available across the 3 availability zones
Creates an Elastic Ip and uses a Livecycle hook with a python lambta to keep it attached to the running instance upon scaling events.

## elasting_running_worpress/
Retrieve current running wodpress insance and "manually" attach elastic IP to it

## lambda_api_gw

Creates an HelloWord lambra function and exposes it via Api Gateway
Expand Down
42 changes: 39 additions & 3 deletions vpc_ha/autoscale_instance.tf
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ resource "aws_launch_configuration" "launch_wordpress" {
resource "aws_autoscaling_group" "autoscale_single" {
name = "single_ha_wordpress"
launch_configuration = aws_launch_configuration.launch_wordpress.name
vpc_zone_identifier = [for subnet in aws_subnet.private : "${subnet.id}"]
vpc_zone_identifier = [for subnet in aws_subnet.public : "${subnet.id}"]
min_size = 1
max_size = 1
desired_capacity = 1
Expand All @@ -43,9 +43,45 @@ resource "aws_autoscaling_group" "autoscale_single" {

}



### SSH Key ###
data "aws_key_pair" "deploy" {
key_name = "deploykey"
}


#### lifecycle management ###

resource "aws_autoscaling_lifecycle_hook" "insance_start_hook" {
name = "ec2_instance_start"
autoscaling_group_name = aws_autoscaling_group.autoscale_single.name
default_result = "CONTINUE"
heartbeat_timeout = 30
lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING"

notification_metadata = <<EOF
{
"project": "vpc_ha"
}
EOF

}
resource "aws_cloudwatch_event_rule" "scale_event" {
name = "capture-ec2-scale"
description = "Capture EC2 instance scaling up"

event_pattern = <<EOF
{
"source": ["aws.autoscaling"],
"detail-type": ["EC2 Instance-launch Lifecycle Action"],
"detail": {
"AutoScalingGroupName": ["single_ha_wordpress"]
}
}
EOF
}

resource "aws_cloudwatch_event_target" "lambda_eip_target" {
rule = aws_cloudwatch_event_rule.scale_event.name
target_id = "ReassignEipLambda"
arn = aws_lambda_function.elastic.arn
}
7 changes: 7 additions & 0 deletions vpc_ha/eip.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
resource "aws_eip" "elastic_wordpress" {
vpc = true
tags = {
Name = "wordpress"
project = "vpc_ha"
}
}
109 changes: 109 additions & 0 deletions vpc_ha/lambda.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
data "archive_file" "lambda_elastic" {
type = "zip"
source_dir = "${path.module}/lambda"
output_path = "${path.module}/lambda.zip"
}

resource "aws_s3_bucket_object" "lambda_elastic" {
bucket = aws_s3_bucket.lambda_lifecycle_bucket.id

key = "lambda.zip"
source = data.archive_file.lambda_elastic.output_path
etag = filemd5(data.archive_file.lambda_elastic.output_path)

tags = {
Name = "Lambda function bucket object"
project = "vpc_ha"
}
}

resource "aws_lambda_function" "elastic" {
function_name = "ReassignElasticIp"

s3_bucket = aws_s3_bucket.lambda_lifecycle_bucket.id
s3_key = aws_s3_bucket_object.lambda_elastic.key

runtime = "python3.6"
handler = "reassign_eip.lambda_handler"

source_code_hash = data.archive_file.lambda_elastic.output_base64sha256

role = aws_iam_role.lifecycle_role.arn

tags = {
Name = "Reassign EIP Lambda function"
project = "vpc_ha"
}
}

resource "aws_cloudwatch_log_group" "elastic" {
name = "/aws/lambda/${aws_lambda_function.elastic.function_name}"
retention_in_days = 1
tags = {
Name = "Lambda function LogGroup"
project = "vpc_ha"
}
}

resource "aws_iam_role" "lifecycle_role" {
name = "lifecycle_lambda_exec"

assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})

inline_policy {
name = "AutoScalingEvent-policy"
policy = jsonencode(
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"autoscaling:CompleteLifecycleAction"
],
"Resource": "${aws_autoscaling_group.autoscale_single.arn}"
}
]
})
}

inline_policy {
name = "AssociateEIP-policy"
policy = jsonencode(
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeAddresses",
"ec2:AllocateAddress",
"ec2:DescribeInstances",
"ec2:AssociateAddress"
],
"Resource": "*"
}
]
})
}

managed_policy_arns = [
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" ,
"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"
]

tags = {
project = "vpc_ha"
}
}
72 changes: 72 additions & 0 deletions vpc_ha/lambda/reassign_eip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import json
import boto3

client = boto3.client('ec2')

def lambda_handler(event, context):

print("Event: " + json.dumps(event))

instances = client.describe_instances(
Filters=[
{
'Name': 'image-id',
'Values': [
'ami-63ec5b1e',
]
},{
'Name': 'instance-state-name',
'Values': [
'running',
]
},
]
)

eip = client.describe_addresses(
Filters=[
{
'Name': 'tag:Name',
'Values': [
'wordpress',
]
},
]
)
# print("Instances")
# print(instances)
# print("EIP")
# print(eip)

for r in instances['Reservations']:
for i in r['Instances']:
instance_id = i['InstanceId']
print(instance_id)

eip_allocation_id = ""
eip_ip = ""
for e in eip['Addresses']:
eip_allocation_id = e['AllocationId']
eip_ip = e['PublicIp']
print("eip_allocation_id: " + eip_allocation_id)
print("eip_ip: " + eip_ip)

association = client.associate_address(
InstanceId=instance_id,
PublicIp=eip_ip,
AllowReassociation=True
)

# print("association")
# print(association)

response = {
"instance": instance_id,
"eip": eip_ip,
"association": association.get('AssociationId',"Unassigned")
}

return {
'statusCode': 200,
'body': json.dumps(response)
}
4 changes: 4 additions & 0 deletions vpc_ha/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ terraform {
source = "hashicorp/aws"
version = "3.65.0"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.2.0"
}
}

required_version = ">= 0.14.9"
Expand Down
10 changes: 10 additions & 0 deletions vpc_ha/s3-bucket.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
resource "aws_s3_bucket" "lambda_lifecycle_bucket" {
bucket = "playground-lambda-lifecycle-bucket"
acl = "private"
force_destroy = true

tags = {
Name = "Lifecycle lambda function bucket"
project = "vpc_ha"
}
}

0 comments on commit f470f4f

Please sign in to comment.