Created
March 20, 2017 00:26
-
-
Save danhper/3cc9bb70a2bedb02648ccaf0d5ac66f8 to your computer and use it in GitHub Desktop.
Sample fabfile to deploy to AWS (with closed firewall) from CI servers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
import boto3 | |
IP_CHECK_URL = "http://checkip.amazonaws.com/" | |
BASTION_SECURITY_GROUP_NAME = "the security group name of your bastion or server" | |
EC2_REGION = "us-east-1" # or whatever you are deploying to | |
ec2 = boto3.client("ec2", EC2_REGION) | |
def _find_security_group(): | |
filters = [{"Name": "group-name", "Values": [BASTION_SECURITY_GROUP_NAME]}] | |
result = ec2.describe_security_groups(Filters=filters) | |
group_id = result["SecurityGroups"][0]["GroupId"] | |
return boto3.resource("ec2", EC2_REGION).SecurityGroup(group_id) | |
def _ssh_ingress(cidr_ip): | |
return { | |
"IpProtocol": "tcp", | |
"CidrIp": cidr_ip, | |
"FromPort": 22, | |
"ToPort": 22 | |
} | |
def _authorize_ip(security_group, cidr_ip): | |
for permission in security_group.ip_permissions: | |
if permission["FromPort"] != 22: | |
continue | |
for ip_range in permission["IpRanges"]: | |
if ip_range.get("CidrIp", None) == cidr_ip: | |
return False | |
security_group.authorize_ingress(**_ssh_ingress(cidr_ip)) | |
return True | |
def _get_cidr_ip(): | |
ip = requests.get(IP_CHECK_URL).text.strip() | |
return "{0}/32".format(ip) | |
@contextmanager | |
def _ip_authorized(): | |
cidr_ip = _get_cidr_ip() | |
security_group = _find_security_group() | |
should_revoke = _authorize_ip(security_group, cidr_ip) | |
try: | |
yield | |
finally: | |
if should_revoke: | |
security_group.revoke_ingress(**_ssh_ingress(cidr_ip)) | |
def _run_deploy(): | |
run("ls") | |
def deploy(): | |
with _ip_authorized(): | |
_run_deploy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment