Skip to content

Instantly share code, notes, and snippets.

@cepefernando
Created February 14, 2018 18:01
Show Gist options
  • Save cepefernando/34f6001b6d189c6ab0ec84120ff8b4f3 to your computer and use it in GitHub Desktop.
Save cepefernando/34f6001b6d189c6ab0ec84120ff8b4f3 to your computer and use it in GitHub Desktop.
# -- coding: utf-8 --
import os
import subprocess
import urllib
import boto3
TERRAFORM_VERSION = '0.9.6'
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')
def check_call(args):
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd='/tmp')
stdout, stderr = proc.communicate()
if proc.returncode != 0:
print(stdout)
print(stderr)
raise subprocess.CalledProcessError(
returncode=proc.returncode,
cmd=args)
def install_terraform():
if os.path.exists(TERRAFORM_PATH):
return
urllib.urlretrieve(TERRAFORM_DOWNLOAD_URL, '/tmp/terraform.zip')
check_call(['unzip', '-o', '/tmp/terraform.zip', '-d', TERRAFORM_DIR])
check_call([TERRAFORM_PATH, '--version'])
def uploadstate(s3_bucket, path2):
s3 = boto3.resource('s3')
planfile2 = s3.Object(s3_bucket, path2)
planfile2.upload_file('/tmp/terraform.tfstate')
def apply_terraform_plan(s3_bucket, path):
s3 = boto3.resource('s3')
planfile = s3.Object(s3_bucket, path)
planfile.download_file('/tmp/terraform.tf')
check_call([TERRAFORM_PATH, 'apply'])
def handler(event, context):
s3_bucket = 'saonterraform'
path = 'main.tf'
path2 = 'terraform.tfstate'
install_terraform()
apply_terraform_plan(s3_bucket=s3_bucket, path=path)
uploadstate(s3_bucket=s3_bucket, path2=path2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment