-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
96 lines (76 loc) · 2.97 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python3
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
import subprocess
import urllib.request
import os
from shutil import copytree, ignore_patterns, rmtree
# Version of Terraform that we're using
TERRAFORM_VERSION = '1.4.4'
# Download URL for Terraform
PLATFORM = 'linux'
TERRAFORM_DOWNLOAD_URL = (
'https://releases.hashicorp.com/terraform/%s/terraform_%s_%s_amd64.zip'
% (TERRAFORM_VERSION, TERRAFORM_VERSION, PLATFORM))
# Paths where Terraform should be installed
TERRAFORM_DIR = os.path.join('/tmp', 'terraform_%s' % TERRAFORM_VERSION)
TERRAFORM_PATH = os.path.join(TERRAFORM_DIR, 'terraform')
PROJECT_DIR = os.path.join('/tmp', 'project')
def check_call(args, cwd=None, printOut=False):
"""Wrapper for subprocess that checks if a process runs correctly,
and if not, prints stdout and stderr.
"""
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
print(stdout.decode())
print(stderr.decode())
raise subprocess.CalledProcessError(
returncode=proc.returncode,
cmd=args)
if printOut:
print(stdout.decode())
print(stderr.decode())
def install_terraform():
"""Install Terraform."""
if os.path.exists(TERRAFORM_PATH):
return
print(TERRAFORM_PATH)
urllib.request.urlretrieve(TERRAFORM_DOWNLOAD_URL, '/tmp/terraform.zip')
check_call(['unzip', '-o', '/tmp/terraform.zip', '-d',
TERRAFORM_DIR], '/tmp')
check_call([TERRAFORM_PATH, '--version'])
def handler(event, context):
print(event)
if os.path.exists(PROJECT_DIR):
rmtree(PROJECT_DIR)
copytree('.', PROJECT_DIR, ignore=ignore_patterns('.terraform',
'credentials.json'))
install_terraform()
check_call([TERRAFORM_PATH, 'init'],
cwd=PROJECT_DIR,
printOut=True)
check_call([TERRAFORM_PATH, 'apply',
'-target=google_access_context_manager_service_perimeter.service_perimeter', '-no-color',
'-auto-approve', '-lock=false',
'-lock-timeout=300s'],
cwd=PROJECT_DIR,
printOut=True)
check_call([TERRAFORM_PATH, 'output', '-json'],
cwd=PROJECT_DIR,
printOut=True)