Created
June 17, 2016 15:38
-
-
Save tomahock/dbeff0379ee78460cfd3b1a3c202d73b to your computer and use it in GitHub Desktop.
Get aws instances from terraform.tfstate and ssh to one of them
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 json | |
import re | |
import os.path | |
from subprocess import call | |
def prompt(message, errormessage, isvalid): | |
res = None | |
while res is None: | |
res = input(str(message)+': ') | |
if not isvalid(res): | |
print str(errormessage) | |
res = None | |
return res | |
with open('terraform.tfstate') as data_file: | |
data = json.load(data_file) | |
resources = data['modules'][0]['resources'] | |
regex_txt = "aws_instance" | |
instanceRegex = re.compile(regex_txt, re.IGNORECASE) | |
instances = [] | |
for (i, item) in resources.iteritems(): | |
match = instanceRegex.search(i) | |
if match is not None: | |
instances.append(resources[i]) | |
print('######## Available Instances ########') | |
for (i, item) in enumerate(instances): | |
print("%s => %s" % (i, item['primary']['attributes']['tags.Name'])) | |
#print json.dumps(i, indent=4, sort_keys=True) | |
serverIndex = prompt( | |
message = "Option: ", | |
errormessage = "Invalid option", | |
isvalid = lambda v : v >= 0 and v < len(instances) | |
) | |
key = "%s/.ssh/%s.pem" % (os.environ['HOME'],instances[serverIndex]["primary"]["attributes"]["key_name"]) | |
ecsUser = "ec2-user" | |
centosUser = "centos" | |
ecsAmi = "ami-4e6ffe3d" | |
centosAmi = "ami-7abd0209" | |
instanceEcsRegex = re.compile(ecsAmi, re.IGNORECASE) | |
matchEcsAmi = instanceEcsRegex.search(instances[serverIndex]["primary"]["attributes"]["ami"]) | |
instanceCentosRegex = re.compile(centosAmi, re.IGNORECASE) | |
matchCentosAmi = instanceCentosRegex.search(instances[serverIndex]["primary"]["attributes"]["ami"]) | |
if matchEcsAmi is not None: | |
host = "%s@%s" % (ecsUser, instances[serverIndex]["primary"]["attributes"]["public_ip"]) | |
elif matchCentosAmi is not None: | |
host = "%s@%s" % (centosUser, instances[serverIndex]["primary"]["attributes"]["public_ip"]) | |
call(["ssh", "-i", key, host]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment