Last active
December 18, 2017 08:55
-
-
Save rav94/fa2a1f55f0ba845c212ce55f0909f84b to your computer and use it in GitHub Desktop.
Manage Systemd Units on AWS CoreOS Tagged Instances with Fabric and boto
This file contains 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
import boto, urllib2 | |
from boto.ec2 import connect_to_region | |
from fabric.api import env, run, cd, settings, sudo | |
from fabric.api import parallel | |
import os | |
import sys | |
REGION = os.environ.get("AWS_EC2_REGION") | |
# Server user | |
env.user = "core" | |
# List of AWS private key Files | |
env.key_filename = ["~/.ssh/key_file.pem"] | |
# Fabric task to restart systemctl, runs in parallel | |
# To execute task using fabric run following | |
# fab set_hosts:Name,AWS_TAGGED_INSTANCE_NAME,us-west-2 restart_systemctl | |
@parallel | |
def restart_systemctl(servicefile): | |
with cd("/etc/systemd/system"): | |
run('sudo systemctl restart %s' % servicefile) | |
# Fabric task to set env.hosts based on tag key-value pair | |
def set_hosts(tag = "Name", value="AWS_TAGGED_INSTANCE_NAME", region=REGION): | |
key = "tag:"+tag | |
env.hosts = _get_public_dns(region, key, value) | |
# Private method to get public DNS name for instance with given tag key and value pair | |
def _get_public_dns(region, key, value ="*"): | |
public_dns = [] | |
connection = _create_connection(region) | |
reservations = connection.get_all_instances(filters = {key : value}) | |
for reservation in reservations: | |
for instance in reservation.instances: | |
print "Instance", instance.public_dns_name | |
public_dns.append(str(instance.public_dns_name)) | |
return public_dns | |
# Private method for getting AWS connection | |
def _create_connection(region): | |
print "Connecting to ", region | |
conn = connect_to_region( | |
region_name = region, | |
aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"), | |
aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY") | |
) | |
print "Connection with AWS established" | |
return conn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment