Skip to content

Instantly share code, notes, and snippets.

@sysless
Created April 17, 2017 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sysless/fd15ec65183315168d065550b68ace75 to your computer and use it in GitHub Desktop.
Save sysless/fd15ec65183315168d065550b68ace75 to your computer and use it in GitHub Desktop.
Bastion drawbridge
Resources:
EC2Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- 'ec2.amazonaws.com'
Action: 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: Bastion
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'cloudwatch:PutMetricData'
- 'ec2:AssociateAddress'
Resource: '*'
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: /
Roles:
- !Ref EC2Role
EIP:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
LaunchConfig:
Type: AWS::AutoScaling::LaunchConfiguration
Properties:
ImageId: ami-XXXXXXXX
InstanceType: t2.nano
IamInstanceProfile: !GetAtt InstanceProfile.Arn
UserData:
"Fn::Base64":
!Sub |
#!/bin/bash
yum update -y
echo "* * * * * root /usr/bin/aws cloudwatch --region ${AWS::Region} put-metric-data --metric-name Users --namespace Bastion --value \$(ps aux | grep sshd | grep -v root | cut -f1 -d' ' | sort | uniq | wc -l)" > /etc/cron.d/cloudwatch
aws ec2 associate-address --instance-id $(curl -s http://169.254.169.254/latest/meta-data/instance-id) --allocation-id ${EIP.AllocationId}
AssociatePublicIpAddress: true
SecurityGroups:
- sg-XXXXXXXX
ASG:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
LaunchConfigurationName: !Ref LaunchConfig
VPCZoneIdentifier:
- subnet-XXXXXXXX
- subnet-XXXXXXXX
- subnet-XXXXXXXX
DesiredCapacity: 1
MinSize: 0
MaxSize: 1
HealthCheckGracePeriod: 300
Tags:
- Key: Name
Value: Bastion
PropagateAtLaunch: true
UpdatePolicy:
AutoScalingRollingUpdate:
MaxBatchSize: 1
MinInstancesInService: 0
ScaleDown:
Type: AWS::AutoScaling::ScalingPolicy
Properties:
AdjustmentType: "ExactCapacity"
AutoScalingGroupName: !Ref ASG
ScalingAdjustment: 0
BastionNoUsers:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: BastionUsers
AlarmDescription: Terminate instance if no users
Namespace: Bastion
MetricName: Users
Statistic: Maximum
Period: 60
EvaluationPeriods: 15
ComparisonOperator: LessThanOrEqualToThreshold
Threshold: 0
AlarmActions:
- !Ref ScaleDown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment