Created
February 14, 2018 18:01
-
-
Save cepefernando/34f6001b6d189c6ab0ec84120ff8b4f3 to your computer and use it in GitHub Desktop.
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
# -- 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