You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dlab.apache.org by om...@apache.org on 2019/08/14 18:37:48 UTC
[incubator-dlab] branch DLAB-terraform updated: add external
tf-state path
This is an automated email from the ASF dual-hosted git repository.
omartushevskyi pushed a commit to branch DLAB-terraform
in repository https://gitbox.apache.org/repos/asf/incubator-dlab.git
The following commit(s) were added to refs/heads/DLAB-terraform by this push:
new 1784423 add external tf-state path
new f078ae6 Merge pull request #254 from bohdana-kuzmenko/DLAB-terraform
1784423 is described below
commit 17844231e45339e5453079f2efe37322f41d2996
Author: bogdana <bo...@gmail.com>
AuthorDate: Wed Aug 14 21:31:33 2019 +0300
add external tf-state path
---
infrastructure-provisioning/terraform/bin/dlab.py | 200 +++++++++++++++-------
1 file changed, 142 insertions(+), 58 deletions(-)
diff --git a/infrastructure-provisioning/terraform/bin/dlab.py b/infrastructure-provisioning/terraform/bin/dlab.py
index cb4e4cf..e4e5c42 100644
--- a/infrastructure-provisioning/terraform/bin/dlab.py
+++ b/infrastructure-provisioning/terraform/bin/dlab.py
@@ -37,10 +37,10 @@ class TerraformOutputBase:
class LocalStorageOutputProcessor(TerraformOutputBase):
- @property
- def output_path(self):
- return os.path.abspath(
- os.path.join(os.path.dirname(INITIAL_LOCATION), 'output.json'))
+ output_path = None
+
+ def __init__(self, path):
+ self.output_path = path
def write(self, obj):
existed_data = {}
@@ -70,14 +70,7 @@ class LocalStorageOutputProcessor(TerraformOutputBase):
json.dump(updated, fp)
-def get_args_string(cli_args):
- """Convert dict of cli argument into string
-
- Args:
- cli_args: dict of cli arguments
- Returns:
- str: string of joined key=values
- """
+def extract_args(cli_args):
args = []
for key, value in cli_args.items():
if not value:
@@ -86,7 +79,34 @@ def get_args_string(cli_args):
quoted_list = ['"{}"'.format(item) for item in value]
joined_values = ', '.join(quoted_list)
value = '[{}]'.format(joined_values)
- args.append("-var '{0}={1}'".format(key, value))
+ args.append((key, value))
+ return args
+
+
+def get_var_args_string(cli_args):
+ """Convert dict of cli argument into string
+
+ Args:
+ cli_args: dict of cli arguments
+ Returns:
+ str: string of joined key=values
+ """
+ args = extract_args(cli_args)
+ args = ["-var '{0}={1}'".format(key, value) for key, value in args]
+ return ' '.join(args)
+
+
+def get_args_string(cli_args):
+ """Convert dict of cli argument into string
+
+ Args:
+ cli_args: dict of cli arguments
+ Returns:
+ str: string of joined key=values
+ """
+
+ args = extract_args(cli_args)
+ args = ["{0} {1}".format(key, value) for key, value in args]
return ' '.join(args)
@@ -205,48 +225,89 @@ class TerraformProvider:
if terraform_success_validate not in terraform_validate_result:
raise TerraformProviderError(terraform_validate_result)
- def apply(self, cli_args):
+ @staticmethod
+ def apply(tf_params, cli_args):
"""Run terraform
Args:
- target: str
+ tf_params: dict of terraform parameters
cli_args: dict of parameters
Returns:
None
"""
logging.info('terraform apply')
- args_str = get_args_string(cli_args)
- command = 'terraform apply -auto-approve {}'
- logging.info(command.format(args_str))
- Console.execute_to_command_line(command.format(args_str))
- def destroy(self, cli_args):
+ args_str = get_var_args_string(cli_args)
+ params_str = get_args_string(tf_params)
+ command = ('terraform apply -auto-approve {} {}'
+ .format(params_str, args_str))
+ logging.info(command)
+ Console.execute_to_command_line(command)
+
+ @staticmethod
+ def destroy(tf_params, cli_args):
"""Destroy terraform
Args:
- target: str
+ tf_params: dict of terraform parameters
cli_args: dict of parameters
Returns:
None
"""
logging.info('terraform destroy')
- args_str = get_args_string(cli_args)
- command = 'terraform destroy -auto-approve {}'
- logging.info(command.format(args_str))
- Console.execute_to_command_line(command.format(args_str))
+ args_str = get_var_args_string(cli_args)
+ params_str = get_args_string(tf_params)
+ command = ('terraform destroy -auto-approve {} {}'
+ .format(params_str, args_str))
+ logging.info(command)
+ Console.execute_to_command_line(command)
+ state_file = tf_params['-state']
+ state_file_backup = tf_params['-state']+'.backup'
+ if os.path.isfile(state_file):
+ os.remove(state_file)
+ if os.path.isfile(state_file_backup):
+ os.remove(state_file_backup)
- def output(self, *args):
+ @staticmethod
+ def output(tf_params, *args):
"""Get terraform output
Args:
+ tf_params: dict of terraform parameters
*args: list of str parameters
Returns:
str: terraform output result
"""
- return Console.execute('terraform output {}'.format(' '.join(args)))
+ params = get_args_string(tf_params)
+ return Console.execute('terraform output {} {}'
+ .format(params, ' '.join(args)))
class AbstractDeployBuilder:
+ def __init__(self):
+
+ args = self.parse_args()
+ self.service_args = args.get('service')
+ state_dir = self.service_args.get('state')
+ if not state_dir:
+ self.tf_output = os.path.join(INITIAL_LOCATION, 'output.json')
+ self.tf_params = {}
+ else:
+ if os.path.isdir(state_dir) and os.access(state_dir, os.W_OK):
+ service_name = (args.get(self.terraform_args_group_name)
+ .get('service_base_name'))
+ output_dir = (os.path.join(state_dir, service_name))
+ self.tf_output = os.path.join(output_dir, 'output.json')
+ self.tf_params = {
+ '-state': os.path.join(output_dir,
+ '{}.tfstate'.format(self.name))
+ }
+ else:
+ sys.stdout.write('path doesn\'t exist')
+ sys.exit(1)
+ if self.use_tf_output_file:
+ self.fill_sys_argv_from_file()
+ self.terraform_args = self.parse_args().get(self.terraform_args_group_name)
@property
@abstractmethod
@@ -260,6 +321,16 @@ class AbstractDeployBuilder:
@property
@abstractmethod
+ def name(self):
+ """ get Terraform name
+
+ Returns:
+ str: TF name
+ """
+ raise NotImplementedError
+
+ @property
+ @abstractmethod
def terraform_args_group_name(self):
""" get Terraform location
@@ -288,24 +359,24 @@ class AbstractDeployBuilder:
"""
raise NotImplementedError
+ @property
+ def use_tf_output_file(self):
+ return False
+
def apply(self):
- cli_args = self.parse_args()
- terraform_args = cli_args.get(self.terraform_args_group_name)
terraform = TerraformProvider()
- terraform.apply(terraform_args)
+ terraform.apply(self.tf_params, self.terraform_args)
def destroy(self):
- cli_args = self.parse_args()
- terraform_args = cli_args.get(self.terraform_args_group_name)
terraform = TerraformProvider()
- terraform.destroy(terraform_args)
+ terraform.destroy(self.tf_params, self.terraform_args)
def store_output_to_file(self):
terraform = TerraformProvider()
- output = terraform.output('-json')
+ output = terraform.output(self.tf_params, '-json')
output = {key: value.get('value')
for key, value in json.loads(output).items()}
- output_writer = LocalStorageOutputProcessor()
+ output_writer = LocalStorageOutputProcessor(self.tf_output)
output_writer.write(output)
def update_extracted_file_data(self, obj):
@@ -317,8 +388,7 @@ class AbstractDeployBuilder:
pass
def fill_sys_argv_from_file(self):
-
- output_processor = LocalStorageOutputProcessor()
+ output_processor = LocalStorageOutputProcessor(self.tf_output)
output = output_processor.extract()
if output:
self.update_extracted_file_data(output)
@@ -385,6 +455,10 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
self._pkey_path = self.args.get('service').get('pkey')
@property
+ def name(self):
+ return 'ssn-k8s'
+
+ @property
def args(self):
return self._args
@@ -417,6 +491,7 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
def cli_args(self):
params = ParamsBuilder()
(params
+ .add_str('--state', 'State file path', required=True, group='service')
.add_str('--access_key_id', 'AWS Access Key ID', required=True,
group='k8s')
.add_str('--allowed_cidrs',
@@ -541,11 +616,9 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
with Console.ssh(self.ip, self.user_name, self.pkey_path) as c:
while True:
tiller_status = c.run(
- "kubectl get pods --all-namespaces | grep tiller | awk '{print $4}'") \
- .stdout
-
+ "kubectl get pods --all-namespaces "
+ "| grep tiller | awk '{print $4}'").stdout
tiller_success_status = 'Running'
-
if tiller_success_status in tiller_status:
break
if (time.time() - start_time) >= 1200:
@@ -554,7 +627,8 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
def select_master_ip(self):
terraform = TerraformProvider()
- output = terraform.output('-json ssn_k8s_masters_ip_addresses')
+ output = terraform.output(self.tf_params,
+ '-json ssn_k8s_masters_ip_addresses')
ips = json.loads(output)
if not ips:
raise TerraformProviderError('no ips')
@@ -574,10 +648,11 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
logging.info('apply helm charts')
args = self.parse_args()
dns_name = json.loads(TerraformProvider()
- .output('-json ssn_k8s_alb_dns_name'))
+ .output(self.tf_params,
+ '-json ssn_k8s_alb_dns_name'))
logging.info('apply ssn-helm-charts')
terraform_args = args.get('helm_charts')
- args_str = get_args_string(terraform_args)
+ args_str = get_var_args_string(terraform_args)
with Console.ssh(self.ip, self.user_name, self.pkey_path) as conn:
with conn.cd('terraform/ssn-helm-charts/main'):
conn.run('terraform init')
@@ -593,14 +668,16 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
def output_terraform_result(self):
dns_name = json.loads(
- TerraformProvider().output('-json ssn_k8s_alb_dns_name'))
+ TerraformProvider().output(self.tf_params,
+ '-json ssn_k8s_alb_dns_name'))
ssn_bucket_name = json.loads(
- TerraformProvider().output('-json ssn_bucket_name'))
+ TerraformProvider().output(self.tf_params, '-json ssn_bucket_name'))
ssn_k8s_sg_id = json.loads(
- TerraformProvider().output('-json ssn_k8s_sg_id'))
+ TerraformProvider().output(self.tf_params, '-json ssn_k8s_sg_id'))
ssn_subnet = json.loads(
- TerraformProvider().output('-json ssn_subnet'))
- ssn_vpc_id = json.loads(TerraformProvider().output('-json ssn_vpc_id'))
+ TerraformProvider().output(self.tf_params, '-json ssn_subnet'))
+ ssn_vpc_id = json.loads(
+ TerraformProvider().output(self.tf_params, '-json ssn_vpc_id'))
logging.info("""
DLab SSN K8S cluster has been deployed successfully!
@@ -625,7 +702,7 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
output = ' '.join(conn.run('terraform output -json')
.stdout.split())
self.fill_args_from_dict(json.loads(output))
- output_processor = LocalStorageOutputProcessor()
+ output_processor = LocalStorageOutputProcessor(self.tf_output)
output = {key: value.get('value')
for key, value in json.loads(output).items()}
output_processor.write(output)
@@ -643,12 +720,13 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
def deploy(self):
logging.info('deploy')
+ output = ' '.join(
+ TerraformProvider().output(self.tf_params, '-json').split())
+ self.fill_args_from_dict(json.loads(output))
self.select_master_ip()
self.add_ip_to_known_hosts(self.ip)
self.check_k8s_cluster_status()
self.check_tiller_status()
- output = ' '.join(TerraformProvider().output('-json').split())
- self.fill_args_from_dict(json.loads(output))
self.copy_terraform_to_remote()
self.run_remote_terraform()
self.fill_remote_terraform_output()
@@ -656,25 +734,30 @@ class AWSK8sSourceBuilder(AbstractDeployBuilder):
def destroy(self):
logging.info('ssn-k8s destroy')
- output_processor = LocalStorageOutputProcessor()
+ output_processor = LocalStorageOutputProcessor(self.tf_output)
endpoint_output_keys = ['keycloak_client_secret']
endpoint_output_keys.extend(
- json.loads(TerraformProvider().output('-json')).keys())
+ json.loads(
+ TerraformProvider().output(self.tf_params, '-json')).keys())
output_processor.remove_keys(endpoint_output_keys)
super(AWSK8sSourceBuilder, self).destroy()
class AWSEndpointBuilder(AbstractDeployBuilder):
- def __init__(self):
- super(AWSEndpointBuilder, self).__init__()
- self.fill_sys_argv_from_file()
-
def update_extracted_file_data(self, obj):
if 'ssn_vpc_id' in obj:
obj['vpc_id'] = obj['ssn_vpc_id']
@property
+ def name(self):
+ return 'endpoint'
+
+ @property
+ def use_tf_output_file(self):
+ return True
+
+ @property
def terraform_location(self):
tf_dir = os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))
return os.path.join(tf_dir, 'aws/endpoint/main')
@@ -687,6 +770,7 @@ class AWSEndpointBuilder(AbstractDeployBuilder):
def cli_args(self):
params = ParamsBuilder()
(params
+ .add_str('--state', 'State file path', required=True, group='service')
.add_str('--secret_access_key', 'AWS Secret Access Key', required=True,
group='endpoint')
.add_str('--access_key_id', 'AWS Access Key ID', required=True,
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@dlab.apache.org
For additional commands, e-mail: commits-help@dlab.apache.org