Created
February 14, 2018 17:58
-
-
Save cepefernando/a589c45e911f89af43ddcd3e60964254 to your computer and use it in GitHub Desktop.
terraform-destroy
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 git import Repo | |
import os | |
import subprocess | |
import urllib | |
import urllib2 | |
import boto3 | |
import logging | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
TERRAFORM_VERSION = '0.10.7' | |
TERRAFORM_DOWNLOAD_URL = ( | |
' | |
https://releases.hashicorp.com/terraform/%s/terraform_%s_linux_amd64.zip' % | |
(TERRAFORM_VERSION, TERRAFORM_VERSION)) | |
TERRAFORM_DIR = os.path.join('/tmp', 'terraform_%s' % TERRAFORM_VERSION) | |
TERRAFORM_PATH = os.path.join(TERRAFORM_DIR, 'terraform') | |
REPO_URL =" | |
http://stash.stepstone.com/rest/archive/latest/projects/STI/repos/terraform-uat-envs/archive?format=zip | |
" | |
REPO_DIR ="terraform-repo" | |
def lambda_handler(event, context): | |
site = event["site"] | |
logger.info(event) | |
logger.info("Installing terraform") | |
install_terraform() | |
logger.info("Finished installing terraform") | |
logger.info("Cloning repo") | |
clone_repo(event["site"]) | |
logger.info("finished cloning repo") | |
base_dir = "/tmp/{}/{}".format(site, site) | |
check_call([TERRAFORM_PATH, "init", "--force-copy"], base_dir) | |
check_call([TERRAFORM_PATH, "workspace", "select", event["envname"]], | |
base_dir) | |
check_call([TERRAFORM_PATH, "destroy", "-force", "-var", | |
"env_name={}".format(event["envname"])], base_dir) | |
return event["envname"] | |
def clone_repo(site): | |
try: | |
extract_dir = "/tmp/{}".format(site) | |
logger.info('Downloading repo from %s' % REPO_URL) | |
download_file(REPO_URL, 'repo.zip') | |
# urllib.urlretrieve(REPO_URL, '/tmp/repo.zip') | |
check_call(['unzip', '-o', '/tmp/repo.zip', '-d', extract_dir ]) | |
check_call(["ls"], extract_dir) | |
except Exception, e: | |
logger.error(e) | |
# return | |
def download_file(url, dest): | |
with open( '/tmp/{}'.format(dest), 'wb') as f: | |
r = urllib2.urlopen(url) | |
logger.info("Response code: {}".format(r.getcode())) | |
f.write(r.read()) | |
f.close() | |
logger.info("Finished downloading file {}".format(url)) | |
def install_terraform(): | |
"""Install Terraform on the Lambda instance.""" | |
# Most of a Lambda's disk is read-only, but some transient storage is | |
# provided in /tmp, so we install Terraform here. This storage may | |
# persist between invocations, so we skip downloading a new version if | |
# it already exists. | |
# http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html | |
if os.path.exists(TERRAFORM_PATH): | |
return | |
logger.info('Downloading terraform from %s' % TERRAFORM_DOWNLOAD_URL) | |
urllib.urlretrieve(TERRAFORM_DOWNLOAD_URL, '/tmp/terraform.zip') | |
# Flags: | |
# '-o' = overwrite existing files without prompting | |
# '-d' = output directory | |
check_call(['unzip', '-o', '/tmp/terraform.zip', '-d', TERRAFORM_DIR]) | |
check_call([TERRAFORM_PATH, '--version']) | |
def check_call(args, cwd = '/tmp'): | |
"""Wrapper for subprocess that checks if a process runs correctly, and | |
if not, prints stdout and stderr.""" | |
logger.info('args {}'.format(args)) | |
proc = subprocess.Popen(args, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
cwd=cwd) | |
stdout, stderr = proc.communicate() | |
if proc.returncode != 0: | |
logger.info("Output from Terraform {}".format(stdout)) | |
logger.info("Errors from Terraform {}".format(stderr)) | |
raise subprocess.CalledProcessError( | |
returncode=proc.returncode, | |
cmd=args) | |
else: | |
logger.info("Command executed successfully. Output: | |
{}".format(stdout)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment