diff --git a/Dockerfile b/Dockerfile old mode 100644 new mode 100755 index b877c4260..de7645d8a --- a/Dockerfile +++ b/Dockerfile @@ -20,6 +20,7 @@ RUN microdnf install -y sudo && \ USER $USERNAME WORKDIR /cd3user/oci_tools/ COPY cd3_automation_toolkit cd3_automation_toolkit/ +COPY othertools othertools/ WORKDIR /cd3user/ diff --git a/OCIWorkVMStack/scripts/installToolkit.sh b/OCIWorkVMStack/scripts/installToolkit.sh index 90d4204bf..8a9e3889d 100644 --- a/OCIWorkVMStack/scripts/installToolkit.sh +++ b/OCIWorkVMStack/scripts/installToolkit.sh @@ -75,7 +75,7 @@ user_id=$(echo "$metadata" | jq -r '.metadata.current_user_ocid') cust_name=$(echo "$metadata" | jq -r '.metadata.tenancy_name') tenancy_id=$(echo "$metadata" | jq -r '.metadata.tenancy_ocid') config_region=$(echo "$metadata" | jq -r '.metadata.config_region') -sudo sed -c -i "s/customer_name=.*/customer_name=$cust_name/" $tenancyconfig_properties +sudo sed -c -i "s/prefix=.*/prefix=$cust_name/" $tenancyconfig_properties sudo sed -c -i "s/tenancy_ocid=.*/tenancy_ocid=$tenancy_id/" $tenancyconfig_properties sudo sed -c -i "s/region=.*/region=$config_region/" $tenancyconfig_properties sudo sed -c -i "s/user_ocid=.*/user_ocid=$user_id/" $tenancyconfig_properties diff --git a/README.md b/README.md index 32596c8e3..25785a1be 100644 --- a/README.md +++ b/README.md @@ -7,12 +7,12 @@
- [What's New](https://github.com/oracle-devrel/cd3-automation-toolkit/releases/tag/v2024.3.2)  • [Excel Templates](https://oracle-devrel.github.io/cd3-automation-toolkit/latest/excel-templates/)  • [CD3 Docs](https://oracle-devrel.github.io/cd3-automation-toolkit/) •  [Watch & Learn](https://www.youtube.com/playlist?list=PLPIzp-E1msrbJ3WawXVhzimQnLw5iafcp)  • [Blogs & Tutorials](https://oracle-devrel.github.io/cd3-automation-toolkit/latest/tutorials/)  • [Livelabs](https://apexapps.oracle.com/pls/apex/f?p=133:180:112501098061930::::wid:3724)  • [Slack Channel](https://oracle-devrel.github.io/cd3-automation-toolkit/latest/queries) + [What's New](https://github.com/oracle-devrel/cd3-automation-toolkit/releases/tag/v2024.4.0)  • [Excel Templates](https://oracle-devrel.github.io/cd3-automation-toolkit/latest/excel-templates/)  • [CD3 Docs](https://oracle-devrel.github.io/cd3-automation-toolkit/) •  [Watch & Learn](https://www.youtube.com/playlist?list=PLPIzp-E1msrbJ3WawXVhzimQnLw5iafcp)  • [Blogs & Tutorials](https://oracle-devrel.github.io/cd3-automation-toolkit/latest/tutorials/)  • [Livelabs](https://apexapps.oracle.com/pls/apex/f?p=133:180:112501098061930::::wid:3724)  • [Slack Channel](https://oracle-devrel.github.io/cd3-automation-toolkit/latest/queries)
-CD3 stands for **Cloud Deployment Design Deliverable**. The CD3 Automation toolkit enables you to effortlessly Build, Export and Manage OCI (Oracle Cloud Infrastruture) resources by converting Excel templates to fully functional Terraform modules within minutes ⚡️⚡️ . +CD3 stands for **Cloud Deployment Design Deliverable**. The CD3 Automation toolkit enables you to effortlessly Build, Export and Manage OCI (Oracle Cloud Infrastructure) resources by converting Excel templates to fully functional Terraform modules within minutes ⚡️⚡️ . Additionally, the toolkit also supports seamless resource management using OCI DevOps GIT service and Jenkins Pipelines. diff --git a/cd3_automation_toolkit/Compute/create_terraform_dedicatedhosts.py b/cd3_automation_toolkit/Compute/create_terraform_dedicatedhosts.py index c81368660..95b04ba64 100644 --- a/cd3_automation_toolkit/Compute/create_terraform_dedicatedhosts.py +++ b/cd3_automation_toolkit/Compute/create_terraform_dedicatedhosts.py @@ -130,9 +130,6 @@ def create_terraform_dedicatedhosts(inputfile, outdir, service_dir,prefix, ct): tfStr[reg] = template.render(count=0, region=reg).replace(src, tfStr[reg] + "\n" + src) tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource = sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) - # Write to TF file outfile = reg_out_dir + "/" + auto_tfvars_filename tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) diff --git a/cd3_automation_toolkit/Compute/create_terraform_instances.py b/cd3_automation_toolkit/Compute/create_terraform_instances.py index 837341b9b..410c36407 100755 --- a/cd3_automation_toolkit/Compute/create_terraform_instances.py +++ b/cd3_automation_toolkit/Compute/create_terraform_instances.py @@ -53,7 +53,7 @@ def create_terraform_instances(inputfile, outdir, service_dir, prefix, ct): tfStr[eachregion] = '' boot_policy_tfStr[eachregion] = '' - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) for i in df.index: region = str(df.loc[i, 'Region']) @@ -93,9 +93,9 @@ def create_terraform_instances(inputfile, outdir, service_dir, prefix, ct): df.loc[i, 'Shape']).lower() == 'nan' or str(df.loc[i, 'Compartment Name']).lower() == 'nan' or str( df.loc[i, 'Pub Address']).lower() == 'nan' or str( df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).lower() == 'nan' or str( - df.loc[i, 'Subnet Name']).lower() == 'nan' or str(df.loc[i, 'Source Details']).lower() == 'nan'): + df.loc[i, 'Network Details']).lower() == 'nan' or str(df.loc[i, 'Source Details']).lower() == 'nan'): print( - "\nOne/All of the Column/Columns from Region, Shape, Compartment Name, Availability Domain, Display Name, Pub Address, Source Details and Subnet Name is empty in Instances sheet of CD3..exiting...Please check.") + "\nOne/All of the Column/Columns from Region, Shape, Compartment Name, Availability Domain, Display Name, Pub Address, Source Details and Network Details is empty in Instances sheet of CD3..exiting...Please check.") exit(1) # Perform the plugin match @@ -137,25 +137,30 @@ def create_terraform_instances(inputfile, outdir, service_dir, prefix, ct): columnvalue = columnvalue.strip() tempdict = {'shape': [columnvalue]} - if columnname == "Subnet Name": - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + subnet_id = '' + network_compartment_id = '' + vcn_name = '' + if columnname == "Network Details": + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str( - i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - - tempdict = {'network_compartment_id': commonTools.check_tf_variable(network_compartment_id), - 'vcn_name': vcn_name, + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, 'subnet_id': subnet_id} if columnname == 'Display Name': @@ -255,9 +260,6 @@ def create_terraform_instances(inputfile, outdir, service_dir, prefix, ct): tfStr[reg] = template.render(count=0, region=reg).replace(src, tfStr[reg] + "\n" + src) tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource = sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) - # Write to TF file outfile = reg_out_dir + "/" + auto_tfvars_filename tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) diff --git a/cd3_automation_toolkit/Compute/export_dedicatedvmhosts_nonGreenField.py b/cd3_automation_toolkit/Compute/export_dedicatedvmhosts_nonGreenField.py index 43b9c3e0b..7464ee5e6 100644 --- a/cd3_automation_toolkit/Compute/export_dedicatedvmhosts_nonGreenField.py +++ b/cd3_automation_toolkit/Compute/export_dedicatedvmhosts_nonGreenField.py @@ -10,6 +10,7 @@ import oci import os +import subprocess as sp from oci.config import DEFAULT_LOCATION from commonTools import * @@ -18,9 +19,11 @@ oci_obj_names = {} -def print_dedicatedvmhosts(region, dedicatedvmhost, values_for_column, ntk_compartment_name): +def print_dedicatedvmhosts(region, dedicatedvmhost, values_for_column, ntk_compartment_name,state): dedicatedvmhost_tf_name = commonTools.check_tf_variable(dedicatedvmhost.display_name) - importCommands[region.lower()].write("\nterraform import \"module.dedicated-hosts[\\\"" +dedicatedvmhost_tf_name+ "\\\"].oci_core_dedicated_vm_host.dedicated_vm_host\" " + str(dedicatedvmhost.id)) + tf_resource = f'module.dedicated-hosts[\\"{dedicatedvmhost_tf_name}\\"].oci_core_dedicated_vm_host.dedicated_vm_host' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(dedicatedvmhost.id)}' for col_header in values_for_column: if col_header == 'Region': @@ -50,7 +53,10 @@ def export_dedicatedvmhosts(inputfile, outdir, service_dir, config, signer, ct, global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -69,39 +75,48 @@ def export_dedicatedvmhosts(inputfile, outdir, service_dir, config, signer, ct, print("\nCD3 excel file should not be opened during export process!!!") print("Tabs- DedicatedVMHosts will be overwritten during export process!!!\n") + # Fetch DVH Details + print("\nFetching details of Dedicated VM Hosts...") + # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' + for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/'+file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg+"/"+service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - - # Fetch Block Volume Details - print("\nFetching details of Dedicated VM Hosts...") + importCommands[reg] = '' - for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Dedicated VM Hosts #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() compute_client = oci.core.ComputeClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) for ntk_compartment_name in export_compartments: dedicatedvmhosts = oci.pagination.list_call_get_all_results(compute_client.list_dedicated_vm_hosts,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name], lifecycle_state="ACTIVE") + for dedicatedvmhost in dedicatedvmhosts.data: dedicatedvmhost=compute_client.get_dedicated_vm_host(dedicatedvmhost.id).data - print_dedicatedvmhosts(region, dedicatedvmhost,values_for_column, ntk_compartment_name) + print_dedicatedvmhosts(region, dedicatedvmhost,values_for_column, ntk_compartment_name,state) - # write data into file + # writing data for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/'+file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + + init_commands = f'\n######### Writing import for Dedicated VM Hosts #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) commonTools.write_to_cd3(values_for_column, cd3file, "DedicatedVMHosts") diff --git a/cd3_automation_toolkit/Compute/export_instances_nonGreenField.py b/cd3_automation_toolkit/Compute/export_instances_nonGreenField.py index b53295dfa..d7a5e5b33 100644 --- a/cd3_automation_toolkit/Compute/export_instances_nonGreenField.py +++ b/cd3_automation_toolkit/Compute/export_instances_nonGreenField.py @@ -7,6 +7,7 @@ import sys import oci import os +import subprocess as sp sys.path.append(os.getcwd() + "/..") from commonTools import * @@ -22,7 +23,7 @@ def adding_columns_values(region, ad, fd, vs, publicip, privateip, os_dname, sha values_for_column_instances[col_header].append(ad) elif (col_header == "Fault Domain"): values_for_column_instances[col_header].append(fd) - elif (col_header == "Subnet Name"): + elif (col_header == "Network Details"): values_for_column_instances[col_header].append(vs) elif (col_header == "Pub Address"): values_for_column_instances[col_header].append(publicip) @@ -80,7 +81,7 @@ def find_vnic(ins_id, compartment_id): return net -def __get_instances_info(compartment_name, compartment_id, reg_name, display_names, ad_names, ct): +def __get_instances_info(compartment_name, compartment_id, reg_name, display_names, ad_names, ct,state): config.__setitem__("region", ct.region_dict[reg_name]) compute = oci.core.ComputeClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) network = oci.core.VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -118,7 +119,9 @@ def __get_instances_info(compartment_name, compartment_id, reg_name, display_nam ins_fd = ins.fault_domain # FD ins_id = ins.id tf_name = commonTools.check_tf_variable(ins_dname) - importCommands[reg_name].write("\nterraform import \"module.instances[\\\"" + tf_name + "\\\"].oci_core_instance.instance\" " + str(ins.id)) + tf_resource = f'module.instances[\\"{tf_name}\\"].oci_core_instance.instance' + if tf_resource not in state["resources"]: + importCommands[reg_name] += f'\n{tf_or_tofu} import "{tf_resource}" {str(ins.id)}' # Shape Details ins_shape = ins.shape @@ -162,7 +165,9 @@ def __get_instances_info(compartment_name, compartment_id, reg_name, display_nam bkp_policy_name = bkp_pname.data.display_name.title() # backup policy name tf_name = commonTools.check_tf_variable(ins_dname) # print(bvp.data[0]) - importCommands[reg_name].write("\nterraform import \"module.instances[\\\"" + tf_name + "\\\"].oci_core_volume_backup_policy_assignment.volume_backup_policy_assignment[0]\" " + str(bvp.data[0].id)) + tf_resource = f'module.instances[\\"{tf_name}\\"].oci_core_volume_backup_policy_assignment.volume_backup_policy_assignment[0]' + if tf_resource not in state["resources"]: + importCommands[reg_name] += f'\n{tf_or_tofu} import "{tf_resource}" {str(bvp.data[0].id)}' if (bkp_pname.data.display_name not in ["Gold", "Silver", "Bronze"]): bkp_policy_name = bkp_pname.data.display_name for comp_name, comp_id in ct.ntk_compartment_ids.items(): @@ -199,7 +204,15 @@ def __get_instances_info(compartment_name, compartment_id, reg_name, display_nam vcn_id = subnet_info.data.vcn_id vcn_info = network.get_vcn(vcn_id=vcn_id) vcn_name = vcn_info.data.display_name - vs = vcn_name + "_" + subnet_name # VCN + Subnet Name + ntk_compartment_id = network.get_vcn(subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + vs = network_compartment_name + "@" + vcn_name + "::" + subnet_name + + #vs = vcn_name + "_" + subnet_name # VCN + Subnet Name #vs = commonTools.check_tf_variable(vs) privateip = vnic_info.private_ip @@ -273,7 +286,10 @@ def export_instances(inputfile, outdir, service_dir,config1, signer1, ct, export print("\nAcceptable cd3 format: .xlsx") exit() - global instance_keys, user_data_in, os_keys, importCommands, idc, rows, AD, values_for_column_instances, df, sheet_dict_instances, config, signer # declaring global variables + global instance_keys, user_data_in, os_keys, importCommands, idc, rows, AD, values_for_column_instances, df, sheet_dict_instances, config, signer,tf_or_tofu # declaring global variables + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] config=config1 signer=signer1 @@ -294,22 +310,27 @@ def export_instances(inputfile, outdir, service_dir,config1, signer1, ct, export print("Tabs- Instances will be overwritten during this export process!!!\n") # Create of .sh file - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' + for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg+"/"+service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Instances #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass for ntk_compartment_name in export_compartments: - __get_instances_info(ntk_compartment_name, ct.ntk_compartment_ids[ntk_compartment_name], reg, display_names, ad_names,ct) + __get_instances_info(ntk_compartment_name, ct.ntk_compartment_ids[ntk_compartment_name], reg, display_names, ad_names,ct,state) # writing image ocids and SSH keys into variables file var_data = {} @@ -361,11 +382,15 @@ def export_instances(inputfile, outdir, service_dir,config1, signer1, ct, export f.write(var_data[reg]) f.close() - # write data into file + # writing data for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + + init_commands = f'\n######### Writing import for Instances #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) commonTools.write_to_cd3(values_for_column_instances, cd3file, "Instances") print("{0} Instance Details exported into CD3.\n".format(len(values_for_column_instances["Region"]))) diff --git a/cd3_automation_toolkit/CostManagement/Budget/create_terraform_budget.py b/cd3_automation_toolkit/CostManagement/Budget/create_terraform_budget.py index 76e1f7125..4170c90fb 100644 --- a/cd3_automation_toolkit/CostManagement/Budget/create_terraform_budget.py +++ b/cd3_automation_toolkit/CostManagement/Budget/create_terraform_budget.py @@ -45,9 +45,12 @@ def create_terraform_budgets(inputfile, outdir, service_dir, prefix,ct): dfcolumns = df.columns.values.tolist() # Take backup of files - for eachregion in ct.all_regions: + for eachregion in [ct.home_region]: tfStr_budget[eachregion] = '' tfStr_budget_alert_rule[eachregion] = '' + resource = sheetName.lower() + srcdir = outdir + "/" + eachregion + "/" + service_dir + "/" + commonTools.backup_file(srcdir + "/", resource, auto_tfvars_filename) for i in df.index: @@ -182,9 +185,6 @@ def create_terraform_budgets(inputfile, outdir, service_dir, prefix,ct): tfStr_budget[reg] += budget_alert_template.render(count=0, region=reg).replace(budget_alert_Str,tfStr_budget_alert_rule[reg]) tfStr_budget[reg] = "".join([s for s in tfStr_budget[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource=sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) - oname = open(outfile, "w+") oname.write(tfStr_budget[reg]) oname.close() diff --git a/cd3_automation_toolkit/CostManagement/Budget/export_budgets_nonGreenField.py b/cd3_automation_toolkit/CostManagement/Budget/export_budgets_nonGreenField.py index a159f1329..8ab459e2c 100644 --- a/cd3_automation_toolkit/CostManagement/Budget/export_budgets_nonGreenField.py +++ b/cd3_automation_toolkit/CostManagement/Budget/export_budgets_nonGreenField.py @@ -9,6 +9,8 @@ import sys import oci import os +import subprocess as sp + from commonTools import * sys.path.append(os.getcwd()+"/..") @@ -105,7 +107,10 @@ def print_budgets(values_for_columns, region, budget,budget_name,budget_alert_ru def export_budgets_nongreenfield(inputfile, outdir, service_dir, config, signer, ct,export_regions=[]): global importCommands global values_for_column_budgets - global sheet_dict_budgets + global sheet_dict_budgets,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile total_resources = 0 budget_done = [] @@ -129,22 +134,26 @@ def export_budgets_nongreenfield(inputfile, outdir, service_dir, config, signer, for reg in [ct.home_region]: importCommands = "" region = reg.lower() - script_file = f'{outdir}/{region}/{service_dir}/tf_import_commands_budgets_nonGF.sh' + script_file = f'{outdir}/{region}/{service_dir}/import_commands_budgets.sh' # Create backups if os.path.exists(script_file): - commonTools.backup_file(os.path.dirname(script_file), "tf_import_budgets", os.path.basename(script_file)) + commonTools.backup_file(os.path.dirname(script_file), "import_budgets", os.path.basename(script_file)) config.__setitem__("region", ct.region_dict[region]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass tenancy_id = config["tenancy"] budgets_client = oci.budget.BudgetClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) budgets_list = oci.pagination.list_call_get_all_results(budgets_client.list_budgets,compartment_id=tenancy_id,lifecycle_state="ACTIVE",target_type="ALL") if budgets_list.data != []: - importCommands += "\n######### Writing import for budgets #########\n\n" - importCommands += "#!/bin/bash" - importCommands += "\n" - importCommands += "terraform init" for budget in budgets_list.data: budget_name = str(budget.display_name) budget_id = str(budget.id) @@ -159,17 +168,25 @@ def export_budgets_nongreenfield(inputfile, outdir, service_dir, config, signer, budget = [] print_budgets(values_for_column_budgets, region, budget,budget_name,budget_alert_rule,ct) budget_done.append(budget_tf_name) - importCommands += "\nterraform import \"module.budget-alert-rules[\\\""+alert_tf_name+"\\\"].oci_budget_alert_rule.alert_rule\" " + alert_id + tf_resource = f'module.budget-alert-rules[\\"{alert_tf_name}\\"].oci_budget_alert_rule.alert_rule' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {alert_id}' + else: print_budgets(values_for_column_budgets, region, budget,budget.display_name, budget_alert_rules.data, ct) total_resources += 1 + tf_resource = f'module.budgets[\\"{budget_tf_name}\\"].oci_budget_budget.budget' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {budget_id}' - importCommands += "\nterraform import \"module.budgets[\\\"" + budget_tf_name + "\\\"].oci_budget_budget.budget\" " + budget_id - importCommands += "\nterraform plan\n" + + init_commands = f'\n######### Writing import for Budgets #########\n\n#!/bin/bash\n{tf_or_tofu} init' if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' with open(script_file, 'a') as importCommandsfile: - importCommandsfile.write(importCommands) + importCommandsfile.write(init_commands + importCommands) + commonTools.write_to_cd3(values_for_column_budgets, cd3file, "Budgets") print("{0} rows exported into CD3 for Budgets and Budget alert-rules.\n".format(total_resources)) diff --git a/cd3_automation_toolkit/Database/create_terraform_adb.py b/cd3_automation_toolkit/Database/create_terraform_adb.py index 5cfee3ad8..0ccc5566d 100644 --- a/cd3_automation_toolkit/Database/create_terraform_adb.py +++ b/cd3_automation_toolkit/Database/create_terraform_adb.py @@ -43,7 +43,7 @@ def create_terraform_adb(inputfile, outdir, service_dir, prefix, ct): # List of the column headers dfcolumns = df.columns.values.tolist() - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) # Initialise empty TF string for each region for reg in ct.all_regions: tfStr[reg] = '' @@ -130,28 +130,30 @@ def create_terraform_adb(inputfile, outdir, service_dir, prefix, ct): tempStr.update(tempdict) continue - - if columnname == "Subnet Name": - if columnvalue != '': - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" - vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = commonTools.check_tf_variable(subnets.vcn_subnet_map[key][0]) - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str( - i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") - exit(1) - else: - subnet_id = "" + subnet_id = '' + network_compartment_id = '' + vcn_name = '' + if columnname == "Network Details": + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - network_compartment_id = "" + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") + exit(1) + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, 'subnet_id': subnet_id} diff --git a/cd3_automation_toolkit/Database/create_terraform_dbsystems_vm_bm.py b/cd3_automation_toolkit/Database/create_terraform_dbsystems_vm_bm.py index 7b4a0f481..2d8595924 100644 --- a/cd3_automation_toolkit/Database/create_terraform_dbsystems_vm_bm.py +++ b/cd3_automation_toolkit/Database/create_terraform_dbsystems_vm_bm.py @@ -30,7 +30,7 @@ def create_terraform_dbsystems_vm_bm(inputfile, outdir, service_dir, prefix, ct) oname = {} tfStr = {} ADS = ["AD1", "AD2", "AD3"] - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) # Load the template file file_loader = FileSystemLoader(f'{Path(__file__).parent}/templates') @@ -87,7 +87,7 @@ def create_terraform_dbsystems_vm_bm(inputfile, outdir, service_dir, prefix, ct) str(df.loc[i, 'Compartment Name']).lower() == 'nan' and \ str(df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).lower() == 'nan' and \ str(df.loc[i, 'DB System Display Name']).lower() == 'nan' and \ - str(df.loc[i, 'Subnet Name']).lower() == 'nan' and \ + str(df.loc[i, 'Network Details']).lower() == 'nan' and \ str(df.loc[i, 'Shape']).lower() == 'nan' and \ str(df.loc[i, 'Node Count']).lower() == 'nan' and \ str(df.loc[i, 'CPU Core Count']).lower() == 'nan' and \ @@ -105,10 +105,10 @@ def create_terraform_dbsystems_vm_bm(inputfile, outdir, service_dir, prefix, ct) str(df.loc[i, 'Compartment Name']).lower() == 'nan' or \ str(df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).lower() == 'nan' or \ str(df.loc[i, 'SSH Key Var Name']).lower() == 'nan' or \ - str(df.loc[i, 'Subnet Name']).lower() == 'nan' or \ + str(df.loc[i, 'Network Details']).lower() == 'nan' or \ str(df.loc[i, 'Hostname Prefix']).lower() == 'nan' or \ str(df.loc[i, 'Shape']).lower() == 'nan' : - print("\nRegion, Compartment Name, Availability Domain(AD1|AD2|AD3), SSH Key Var Name, Subnet Name, Hostname, Shape are mandatory fields. Please enter a value and try again.......Exiting!!") + print("\nRegion, Compartment Name, Availability Domain(AD1|AD2|AD3), SSH Key Var Name, Network Details, Hostname, Shape are mandatory fields. Please enter a value and try again.......Exiting!!") exit(1) if str(df.loc[i, 'DB Name']).lower() == 'nan' or \ str(df.loc[i, 'DB Version']).lower() == 'nan' or \ @@ -143,30 +143,32 @@ def create_terraform_dbsystems_vm_bm(inputfile, outdir, service_dir, prefix, ct) display_tf_name = commonTools.check_tf_variable(display_tf_name) tempdict = {'display_tf_name': display_tf_name} - if columnname == 'Subnet Name': - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + subnet_id = '' + network_compartment_id = '' + vcn_name = '' + if columnname == 'Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str( - i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - - tempdict = {'network_compartment_id': commonTools.check_tf_variable(network_compartment_id), - 'vcn_name': vcn_name, + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, 'subnet_id': subnet_id} - # if columnname == 'Backup Subnet Name': - # columnvalue = commonTools.check_tf_variable(columnvalue) - if columnname == 'Availability Domain(AD1|AD2|AD3)': columnname = 'availability_domain' diff --git a/cd3_automation_toolkit/Database/create_terraform_exa_vmclusters.py b/cd3_automation_toolkit/Database/create_terraform_exa_vmclusters.py index d234e5a61..737261a6f 100644 --- a/cd3_automation_toolkit/Database/create_terraform_exa_vmclusters.py +++ b/cd3_automation_toolkit/Database/create_terraform_exa_vmclusters.py @@ -44,7 +44,7 @@ def create_terraform_exa_vmclusters(inputfile, outdir, service_dir, prefix, ct): # List of the column headers dfcolumns = df.columns.values.tolist() - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) # Initialise empty TF string for each region for reg in ct.all_regions: @@ -85,13 +85,13 @@ def create_terraform_exa_vmclusters(inputfile, outdir, service_dir, prefix, ct): str(df.loc[i, 'Compartment Name']).lower() == 'nan' or \ str(df.loc[i, 'Exadata Infra Display Name']).lower() == 'nan' or \ str(df.loc[i, 'VM Cluster Display Name']).lower() == 'nan' or \ - str(df.loc[i, 'Client Subnet Name']).lower() == 'nan' or \ - str(df.loc[i, 'Backup Subnet Name']).lower() == 'nan' or \ + str(df.loc[i, 'Client Network Details']).lower() == 'nan' or \ + str(df.loc[i, 'Backup Network Details']).lower() == 'nan' or \ str(df.loc[i, 'CPU Core Count']).lower() == 'nan' or \ str(df.loc[i, 'SSH Key Var Name']).lower() == 'nan' or \ str(df.loc[i, 'Hostname Prefix']).lower() == 'nan' or \ str(df.loc[i, 'Oracle Grid Infrastructure Version']).lower() == 'nan': - print("\nRegion, Compartment Name, Exadata Infra Display Name, VM Cluster Display Name, Subnet Names, CPU Core Count, Hostname Prefix, Oracle Grid Infrastructure Version, SSH Key Var Name are mandatory fields. Please enter a value and try again.......Exiting!!") + print("\nRegion, Compartment Name, Exadata Infra Display Name, VM Cluster Display Name, Network Details, CPU Core Count, Hostname Prefix, Oracle Grid Infrastructure Version, SSH Key Var Name are mandatory fields. Please enter a value and try again.......Exiting!!") exit(1) # tempdict = {'oracle_db_software_edition' : 'ENTERPRISE_EDITION_EXTREME_PERFORMANCE'} @@ -127,43 +127,54 @@ def create_terraform_exa_vmclusters(inputfile, outdir, service_dir, prefix, ct): display_tf_name = commonTools.check_tf_variable(display_tf_name) tempdict = {'exadata_infra_display_tf_name': display_tf_name} - if columnname == 'Client Subnet Name': - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + subnet_id = '' + network_compartment_id = '' + vcn_name = '' + if columnname == 'Client Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str( - i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - - tempdict = {'network_compartment_id': commonTools.check_tf_variable(network_compartment_id), - 'vcn_name': vcn_name, + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, 'client_subnet_name': subnet_id} - if columnname == 'Backup Subnet Name': - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + subnet_id = '' + network_compartment_id = '' + vcn_name = '' + if columnname == 'Backup Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str( - i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() tempdict = {'backup_subnet_name': subnet_id} diff --git a/cd3_automation_toolkit/Database/export_adb_nonGreenField.py b/cd3_automation_toolkit/Database/export_adb_nonGreenField.py index 92bd18ce8..f1ec973db 100644 --- a/cd3_automation_toolkit/Database/export_adb_nonGreenField.py +++ b/cd3_automation_toolkit/Database/export_adb_nonGreenField.py @@ -8,6 +8,7 @@ # import oci import os +import subprocess as sp from commonTools import * from oci.config import DEFAULT_LOCATION @@ -15,7 +16,7 @@ oci_obj_names = {} -def print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name): +def print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name,state,ct): adb_tf_name = commonTools.check_tf_variable(adb.display_name) customer_emails = "" if hasattr(adb,"customer_contacts") and adb.customer_contacts: @@ -28,9 +29,13 @@ def print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name) adb_subnet_name = adb_subnet_info.data.display_name # Subnet-Name adb_vcn_name = vnc_client.get_vcn(adb_subnet_info.data.vcn_id).data.display_name - else: - adb_subnet_name = "" - adb_vcn_name = "" + ntk_compartment_id = vnc_client.get_vcn(adb_subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = ntk_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + vs = network_compartment_name + "@" + adb_vcn_name + "::" + adb_subnet_name # Fetch NSGs @@ -49,8 +54,9 @@ def print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name) whitelisted_ips = whitelisted_ips + "," + ip whitelisted_ips = whitelisted_ips[1:] - importCommands[region.lower()].write( - "\nterraform import \"module.adb[\\\"" + adb_tf_name + "\\\"].oci_database_autonomous_database.autonomous_database\" " + str(adb.id)) + tf_resource = f'module.adb[\\"{adb_tf_name}\\"].oci_database_autonomous_database.autonomous_database' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(adb.id)}' for col_header in values_for_column: if col_header == 'Region': @@ -59,9 +65,9 @@ def print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name) values_for_column[col_header].append(ntk_compartment_name) elif col_header == 'ADB Display Name': values_for_column[col_header].append(adb.display_name) - elif col_header == 'Subnet Name': + elif col_header == 'Network Details': if (adb_subnet_id is not None): - values_for_column[col_header].append(adb_vcn_name + "_" + adb_subnet_name) + values_for_column[col_header].append(vs) else: values_for_column[col_header].append("") elif col_header == 'Whitelisted IP Addresses': @@ -117,7 +123,10 @@ def export_adbs(inputfile, outdir, service_dir, config, signer, ct, export_compa global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile # input file if ('.xls' not in cd3file): @@ -136,25 +145,27 @@ def export_adbs(inputfile, outdir, service_dir, config, signer, ct, export_compa print("Tabs- ADB will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch ADB details print("\nFetching details of ADBs...") - - for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for ADBs #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() adb_client = oci.database.DatabaseClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) @@ -163,17 +174,19 @@ def export_adbs(inputfile, outdir, service_dir, config, signer, ct, export_compa for ntk_compartment_name in export_compartments: adbs = oci.pagination.list_call_get_all_results(adb_client.list_autonomous_databases,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name],lifecycle_state="AVAILABLE") - for adb in adbs.data: adb = adb_client.get_autonomous_database(adb.id).data - print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name) + print_adbs(region, vnc_client, adb, values_for_column, ntk_compartment_name,state,ct) - for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') commonTools.write_to_cd3(values_for_column, cd3file, "ADB") - print("{0} ADBs exported into CD3.\n".format(len(values_for_column["Region"]))) + # writing data + for reg in export_regions: + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + init_commands = f'\n######### Writing import for ADBs #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Database/export_dbsystems_vm_bm_nonGreenField.py b/cd3_automation_toolkit/Database/export_dbsystems_vm_bm_nonGreenField.py index 94f90a75f..7c19ee9af 100644 --- a/cd3_automation_toolkit/Database/export_dbsystems_vm_bm_nonGreenField.py +++ b/cd3_automation_toolkit/Database/export_dbsystems_vm_bm_nonGreenField.py @@ -14,12 +14,13 @@ from jinja2 import Environment, FileSystemLoader import json import re +import subprocess as sp importCommands = {} oci_obj_names = {} -def print_dbsystem_vm_bm(region, db_system_vm_bm, count,db_home, database ,vnc_client, key_name, values_for_column, ntk_compartment_name): +def print_dbsystem_vm_bm(region, db_system_vm_bm, count,db_home, database ,vnc_client, key_name, values_for_column, ntk_compartment_name,state,ct): db_system_vm_bm_tf_name = commonTools.check_tf_variable(db_system_vm_bm.display_name) db_system_subnet_id = db_system_vm_bm.subnet_id @@ -27,6 +28,13 @@ def print_dbsystem_vm_bm(region, db_system_vm_bm, count,db_home, database ,vnc_c sub_name = subnet_info.data.display_name # Subnet-Name vcn_name = vnc_client.get_vcn(subnet_info.data.vcn_id).data.display_name # vcn-Name + ntk_compartment_id = vnc_client.get_vcn(subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = ntk_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + vs = network_compartment_name + "@" + vcn_name + "::" + sub_name + db_system_options = db_system_vm_bm.db_system_options maintenance_window = db_system_vm_bm.maintenance_window @@ -43,12 +51,13 @@ def print_dbsystem_vm_bm(region, db_system_vm_bm, count,db_home, database ,vnc_c connection_strings = database.connection_strings database_management_config = database.database_management_config - if (count ==1): - importCommands[region.lower()].write("\nterraform import \"module.dbsystems-vm-bm[\\\"" + db_system_vm_bm_tf_name + "\\\"].oci_database_db_system.database_db_system\" " + str(db_system_vm_bm.id)) + tf_resource = f'module.dbsystems-vm-bm[\\"{db_system_vm_bm_tf_name}\\"].oci_database_db_system.database_db_system' + if (count ==1) and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(db_system_vm_bm.id)}' if(count!=1): for col_header in values_for_column: - if col_header == 'Region' or col_header == 'Compartment Name' or col_header == 'Subnet Name' or "Availability Domain" in col_header or \ + if col_header == 'Region' or col_header == 'Compartment Name' or col_header == 'Network Details' or "Availability Domain" in col_header or \ col_header == 'Shape' or col_header == 'DB System Display Name' or col_header == 'Node Count' or col_header == 'CPU Core Count' or col_header == "Database Edition" or \ col_header == 'Data Storage in GB' or col_header == 'Data Storage Percentage' or col_header == 'Disk Redundancy' or col_header == 'License Model' or \ col_header == 'Hostname Prefix' or col_header == 'SSH Key Var Name' or col_header == 'Time Zone' or col_header == 'NSGs': @@ -70,8 +79,8 @@ def print_dbsystem_vm_bm(region, db_system_vm_bm, count,db_home, database ,vnc_c values_for_column[col_header].append(region) elif col_header == 'Compartment Name': values_for_column[col_header].append(ntk_compartment_name) - elif col_header == 'Subnet Name': - values_for_column[col_header].append(vcn_name + "_" + sub_name) + elif col_header == 'Network Details': + values_for_column[col_header].append(vs) elif col_header == 'DB Admin Password': values_for_column[col_header].append('nullval') elif col_header == 'SSH Key Var Name': @@ -102,7 +111,10 @@ def export_dbsystems_vm_bm(inputfile, outdir, service_dir, config, signer, ct, e global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -128,25 +140,29 @@ def export_dbsystems_vm_bm(inputfile, outdir, service_dir, config, signer, ct, e env = Environment(loader=file_loader, keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Block Volume Details print("\nFetching details of VM and BM DB Systems...") for reg in export_regions: var_data[reg] = "" - importCommands[reg].write("\n\n######### Writing import for DB System VM and DB System BM #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() db_client = oci.database.DatabaseClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -171,7 +187,7 @@ def export_dbsystems_vm_bm(inputfile, outdir, service_dir, config, signer, ct, e break databases = oci.pagination.list_call_get_all_results(db_client.list_databases,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name],db_home_id=db_home.id,system_id=db_system.id,lifecycle_state="AVAILABLE") for database in databases.data: - print_dbsystem_vm_bm(region, db_system, count,db_home, database, vnc_client, key_name,values_for_column, ntk_compartment_name) + print_dbsystem_vm_bm(region, db_system, count,db_home, database, vnc_client, key_name,values_for_column, ntk_compartment_name,state,ct) file = f'{outdir}/{reg}/{service_dir}/variables_{reg}.tf' # Read variables file data @@ -191,11 +207,14 @@ def export_dbsystems_vm_bm(inputfile, outdir, service_dir, config, signer, ct, e with open(file, "w") as f: f.write(var_data[reg]) - - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') - commonTools.write_to_cd3(values_for_column, cd3file, sheetName) - print("{0} Virtual Machine and Bare Metal DB Systems exported into CD3.\n".format(len(values_for_column["Region"]))) + # writing data + for reg in export_regions: + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + init_commands = f'\n######### Writing import for DB System VM and DB System BM #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Database/export_exa_infra_nonGreenField.py b/cd3_automation_toolkit/Database/export_exa_infra_nonGreenField.py index 830b2448d..5aaad0873 100644 --- a/cd3_automation_toolkit/Database/export_exa_infra_nonGreenField.py +++ b/cd3_automation_toolkit/Database/export_exa_infra_nonGreenField.py @@ -10,18 +10,19 @@ import oci import os +import subprocess as sp from commonTools import * importCommands = {} oci_obj_names = {} -def print_exa_infra(region, exa_infra, values_for_column, ntk_compartment_name): +def print_exa_infra(region, exa_infra, values_for_column, ntk_compartment_name,state): exa_infra_tf_name = commonTools.check_tf_variable(exa_infra.display_name) maintenance_window = exa_infra.maintenance_window - - #importCommands[region.lower()].write("\nterraform import oci_database_cloud_exadata_infrastructure." + exa_infra_tf_name + " " + str(exa_infra.id)) - importCommands[region.lower()].write("\nterraform import \"module.exa-infra[\\\"" + exa_infra_tf_name + "\\\"].oci_database_cloud_exadata_infrastructure.exa_infra\" " + str(exa_infra.id)) + tf_resource = f'module.exa-infra[\\"{exa_infra_tf_name}\\"].oci_database_cloud_exadata_infrastructure.exa_infra' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(exa_infra.id)}' for col_header in values_for_column: if col_header == 'Region': @@ -53,7 +54,10 @@ def export_exa_infra(inputfile, outdir, service_dir, config, signer, ct, export_ global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -72,24 +76,28 @@ def export_exa_infra(inputfile, outdir, service_dir, config, signer, ct, export_ print("Tabs- EXA-Infra will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Block Volume Details print("\nFetching details of Exadata Infra...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Exadata Infra #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() db_client = oci.database.DatabaseClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) @@ -97,13 +105,19 @@ def export_exa_infra(inputfile, outdir, service_dir, config, signer, ct, export_ for ntk_compartment_name in export_compartments: exa_infras = oci.pagination.list_call_get_all_results(db_client.list_cloud_exadata_infrastructures,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name], lifecycle_state="AVAILABLE") for exa_infra in exa_infras.data: - print_exa_infra(region, exa_infra,values_for_column, ntk_compartment_name) + print_exa_infra(region, exa_infra,values_for_column, ntk_compartment_name,state) + + + commonTools.write_to_cd3(values_for_column, cd3file, sheetName) + print("{0} Exadata Infra exported into CD3.\n".format(len(values_for_column["Region"]))) + # writing data for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') - commonTools.write_to_cd3(values_for_column, cd3file, sheetName) + init_commands = f'\n######### Writing import for Exadata Infra #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) - print("{0} Exadata Infra exported into CD3.\n".format(len(values_for_column["Region"]))) diff --git a/cd3_automation_toolkit/Database/export_exa_vmclusters_nonGreenField.py b/cd3_automation_toolkit/Database/export_exa_vmclusters_nonGreenField.py index 13ee92cdc..bc7d19678 100644 --- a/cd3_automation_toolkit/Database/export_exa_vmclusters_nonGreenField.py +++ b/cd3_automation_toolkit/Database/export_exa_vmclusters_nonGreenField.py @@ -12,6 +12,7 @@ import os import json import re +import subprocess as sp from pathlib import Path from commonTools import * from jinja2 import Environment, FileSystemLoader @@ -20,7 +21,7 @@ oci_obj_names = {} -def print_exa_vmcluster(region, vnc_client,exa_infra, exa_vmcluster, key_name,values_for_column, ntk_compartment_name, db_servers): +def print_exa_vmcluster(region, vnc_client,exa_infra, exa_vmcluster, key_name,values_for_column, ntk_compartment_name, db_servers,state,ct): exa_infra_tf_name = commonTools.check_tf_variable(exa_infra.display_name) exa_vmcluster_tf_name = commonTools.check_tf_variable(exa_vmcluster.display_name) @@ -28,11 +29,23 @@ def print_exa_vmcluster(region, vnc_client,exa_infra, exa_vmcluster, key_name,va client_subnet_info = vnc_client.get_subnet(exa_vmcluster_client_subnet_id) client_subnet_name = client_subnet_info.data.display_name # Subnet-Name client_vcn_name = vnc_client.get_vcn(client_subnet_info.data.vcn_id).data.display_name # vcn-Name + ntk_compartment_id = vnc_client.get_vcn(client_subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = ntk_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + client_network = network_compartment_name + "@" + client_vcn_name + "::" + client_subnet_name exa_vmcluster_backup_subnet_id = exa_vmcluster.backup_subnet_id backup_subnet_info = vnc_client.get_subnet(exa_vmcluster_backup_subnet_id) backup_subnet_name = backup_subnet_info.data.display_name # Subnet-Name backup_vcn_name = vnc_client.get_vcn(backup_subnet_info.data.vcn_id).data.display_name # vcn-Name + ntk_compartment_id = vnc_client.get_vcn(backup_subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = ntk_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + backup_network = network_compartment_name + "@" + backup_vcn_name + "::" + backup_subnet_name NSGs = exa_vmcluster.nsg_ids @@ -53,9 +66,9 @@ def print_exa_vmcluster(region, vnc_client,exa_infra, exa_vmcluster, key_name,va maintenance_window = exa_infra.maintenance_window - - - importCommands[region.lower()].write("\nterraform import \"module.exa-vmclusters[\\\"" + exa_vmcluster_tf_name + "\\\"].oci_database_cloud_vm_cluster.exa_vmcluster\" " + str(exa_vmcluster.id)) + tf_resource = f'module.exa-vmclusters[\\"{exa_vmcluster_tf_name}\\"].oci_database_cloud_vm_cluster.exa_vmcluster' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(exa_vmcluster.id)}' for col_header in values_for_column: if col_header == 'Region': @@ -66,10 +79,10 @@ def print_exa_vmcluster(region, vnc_client,exa_infra, exa_vmcluster, key_name,va values_for_column[col_header].append(exa_infra.display_name) elif col_header == 'SSH Key Var Name': values_for_column[col_header].append(key_name) - elif col_header == 'Client Subnet Name': - values_for_column[col_header].append(client_vcn_name+"_"+client_subnet_name) - elif col_header == 'Backup Subnet Name': - values_for_column[col_header].append(backup_vcn_name + "_" + backup_subnet_name) + elif col_header == 'Client Network Details': + values_for_column[col_header].append(client_network) + elif col_header == 'Backup Network Detailse': + values_for_column[col_header].append(backup_network) elif (col_header == "NSGs"): values_for_column[col_header].append(nsg_names) elif (col_header == "Backup Network NSGs"): @@ -91,7 +104,10 @@ def export_exa_vmclusters(inputfile, outdir, service_dir, config, signer, ct, ex global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -99,7 +115,6 @@ def export_exa_vmclusters(inputfile, outdir, service_dir, config, signer, ct, ex print("\nAcceptable cd3 format: .xlsx") exit() - sheetName = 'EXA-VMClusters' var_data ={} @@ -118,17 +133,14 @@ def export_exa_vmclusters(inputfile, outdir, service_dir, config, signer, ct, ex env = Environment(loader=file_loader, keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Block Volume Details print("\nFetching details of Exadata VM Clusters...") @@ -136,8 +148,15 @@ def export_exa_vmclusters(inputfile, outdir, service_dir, config, signer, ct, ex for reg in export_regions: var_data[reg] = "" - importCommands[reg].write("\n\n######### Writing import for Exadata VM Clusters #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() db_client = oci.database.DatabaseClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) @@ -162,8 +181,9 @@ def export_exa_vmclusters(inputfile, outdir, service_dir, config, signer, ct, ex for db_server in db_serverids: db_server_name = db_client.get_db_server(exa_infra.id, db_server).data.display_name db_servers = db_server_name +","+db_servers + db_servers=db_servers.removesuffix(',') - print_exa_vmcluster(region, vnc_client, exa_infra,exa_vmcluster,key_name, values_for_column, ntk_compartment_name_again,db_servers) + print_exa_vmcluster(region, vnc_client, exa_infra,exa_vmcluster,key_name, values_for_column, ntk_compartment_name_again,db_servers,state,ct) file = f'{outdir}/{reg}/{service_dir}/variables_{reg}.tf' # Read variables file data @@ -183,11 +203,15 @@ def export_exa_vmclusters(inputfile, outdir, service_dir, config, signer, ct, ex with open(file, "w") as f: f.write(var_data[reg]) - - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') - commonTools.write_to_cd3(values_for_column, cd3file, sheetName) - print("{0} Exadata VM Clusters exported into CD3.\n".format(len(values_for_column["Region"]))) + # writing data + for reg in export_regions: + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + init_commands = f'\n######### Writing import for Exadata VM Clusters #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/DeveloperServices/OKE/create_terraform_oke.py b/cd3_automation_toolkit/DeveloperServices/OKE/create_terraform_oke.py index 5fa5fe61c..30e95fc11 100644 --- a/cd3_automation_toolkit/DeveloperServices/OKE/create_terraform_oke.py +++ b/cd3_automation_toolkit/DeveloperServices/OKE/create_terraform_oke.py @@ -47,13 +47,13 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): # fill the empty values with that in previous row. dffill = df[ ['Region', 'Compartment Name', 'Cluster Name', 'Cluster Kubernetes Version','Network Type', 'Pod Security Policies Enforced', - 'Load Balancer Subnets', 'API Endpoint Subnet']] + 'Load Balancer Network Details', 'API Endpoint Network Details']] dffill = dffill.fillna(method='ffill') #Drop unnecessary columns dfdrop = df[ ['Region', 'Compartment Name', 'Cluster Name', 'Cluster Kubernetes Version','Network Type', 'Pod Security Policies Enforced', - 'Load Balancer Subnets', 'API Endpoint Subnet']] + 'Load Balancer Network Details', 'API Endpoint Network Details']] dfdrop = df.drop(dfdrop, axis=1) df = pd.concat([dffill, dfdrop], axis=1) @@ -62,11 +62,16 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): cluster_str[reg] = '' node_str[reg] = '' virtual_node_str[reg] = '' + resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + commonTools.backup_file(srcdir, resource, cluster_auto_tfvars_filename) + commonTools.backup_file(srcdir, resource, nodepool_auto_tfvars_filename) + commonTools.backup_file(srcdir, resource, virtual_nodepool_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) for i in df.index: @@ -97,24 +102,24 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): str(df.loc[i, 'Network Type']).lower() == 'nan' or \ str(df.loc[i, 'Cluster Kubernetes Version']).lower() == 'nan' or \ str(df.loc[i, 'Pod Security Policies Enforced']).lower() == 'nan' or \ - str(df.loc[i, 'Load Balancer Subnets']).lower() == 'nan' or \ - str(df.loc[i, 'API Endpoint Subnet']).lower() == 'nan': + str(df.loc[i, 'Load Balancer Network Details']).lower() == 'nan' or \ + str(df.loc[i, 'API Endpoint Network Details']).lower() == 'nan': print( - "\nRegion, Compartment Name, Cluster Name, Network Type, Cluster Kubernetes Version, Pod Security Policies, Load Balancer Subnets, API Endpoint Subnet fields are mandatory. Please enter a value and try again !!\n\nPlease fix it for row : {}".format( + "\nRegion, Compartment Name, Cluster Name, Network Type, Cluster Kubernetes Version, Pod Security Policies, Load Balancer Network Details, API Endpoint Network Details fields are mandatory. Please enter a value and try again !!\n\nPlease fix it for row : {}".format( i + 3)) print("\n** Exiting **") exit(1) - if str(df.loc[i, 'CompartmentName&Node Pool Name:Node Pool Type']).lower() != 'nan': - nodepool_tf_name_type = str(df.loc[i, 'CompartmentName&Node Pool Name:Node Pool Type']).strip().split("&")[1] + if str(df.loc[i, 'CompartmentName@Node Pool Name:Node Pool Type']).lower() != 'nan': + nodepool_tf_name_type = str(df.loc[i, 'CompartmentName@Node Pool Name:Node Pool Type']).strip().split("@")[1] if (":" in nodepool_tf_name_type): nodepool_type = nodepool_tf_name_type.split(":")[1] nodepool_type = nodepool_type.lower() else: nodepool_type = 'managed' - if str(df.loc[i, 'Worker Node Subnet']).lower() == 'nan' or \ + if str(df.loc[i, 'Worker Node Network Details']).lower() == 'nan' or \ str(df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).lower() == 'nan': - print("\nCompartmentName&Node Pool Name:Node Pool Type, Worker Node Subnet and Availability Domain(AD1|AD2|AD3) fields are mandatory. \n\nPlease fix it for row : {} and try again.".format(i+3)) + print("\nCompartmentName@Node Pool Name:Node Pool Type, Worker Node Network Details and Availability Domain(AD1|AD2|AD3) fields are mandatory. \n\nPlease fix it for row : {} and try again.".format(i+3)) print("\n** Exiting **") exit(1) if (nodepool_type == "managed"): @@ -122,9 +127,9 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): str(df.loc[i, 'Shape']).lower() == 'nan' or \ str(df.loc[i, 'Source Details']).lower() == 'nan' or \ str(df.loc[i, 'Number of Nodes']).lower() == 'nan' or \ - str(df.loc[i, 'Worker Node Subnet']).lower() == 'nan' or \ + str(df.loc[i, 'Worker Node Network Details']).lower() == 'nan' or \ str(df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).lower() == 'nan': - print("\nCompartmentName&Node Pool Name:Node Pool Type, Nodepool Kubernetes Version, Shape, Source Details, Number of Nodes, Worker Node Subnet and Availability Domain(AD1|AD2|AD3) fields are mandatory. \n\nPlease fix it for row : {} and try again.".format(i+3)) + print("\nCompartmentName@Node Pool Name:Node Pool Type, Nodepool Kubernetes Version, Shape, Source Details, Number of Nodes, Worker Node Network Details and Availability Domain(AD1|AD2|AD3) fields are mandatory. \n\nPlease fix it for row : {} and try again.".format(i+3)) print("\n** Exiting **") exit(1) @@ -152,8 +157,8 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): ''' if str(df.loc[i, 'Network Type']).lower() == 'oci_vcn_ip_native': - if str(df.loc[i, 'Pod Communication Subnet']).lower() == 'nan': - print("\nPod Communication Subnet required for cluster with networking type:OCI_VCN_IP_NATIVE") + if str(df.loc[i, 'Pod Communication Network Details']).lower() == 'nan': + print("\nPod Communication Network Details required for cluster with networking type:OCI_VCN_IP_NATIVE") print("\n** Exiting **") exit(1) ''' @@ -197,12 +202,12 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): cluster_tf_name = commonTools.check_tf_variable(columnvalue) tempdict = {'cluster_tf_name': cluster_tf_name, 'cluster_display_name': columnvalue} - if columnname == "CompartmentName&Node Pool Name:Node Pool Type": + if columnname == "CompartmentName@Node Pool Name:Node Pool Type": if columnvalue != '': try: - node_compartment = columnvalue.split("&")[0] + node_compartment = columnvalue.split("@")[0] node_compartment = commonTools.check_tf_variable(node_compartment) - nodepool_tf_name_type = columnvalue.split("&")[1] + nodepool_tf_name_type = columnvalue.split("@")[1] nodepool_tf_name = nodepool_tf_name_type.split(":")[0] nodepool_tf_name = commonTools.check_tf_variable(nodepool_tf_name) nodepool_display_name = nodepool_tf_name @@ -222,10 +227,6 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): columnvalue = columnvalue.strip() tempdict = {'shape': [columnvalue]} - oke_lb_subnets_list = [] - #network_compartment_id = '' - #vcn_name = '' - if columnname == "SSH Key Var Name": if columnvalue.strip() != '' and columnvalue.strip().lower() != 'nan': if "ssh-rsa" in columnvalue.strip(): @@ -242,111 +243,124 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): taints='nan' tempdict = {'taints': taints} - - if columnname == 'Load Balancer Subnets': - oke_lb_subnets = str(columnvalue).strip().split(",") - if len(oke_lb_subnets) == 1: - if len(oke_lb_subnets[0]) == 0: - pass - elif ("ocid1.subnet.oc1" in str(oke_lb_subnets[0]).strip()): - oke_lb_subnets_list.append(str(oke_lb_subnets[0]).strip()) - network_compartment_id = '' - vcn_name = '' - else: - subnet_tf_name = commonTools.check_tf_variable(str(oke_lb_subnets[0]).strip()) - try: - key = region, subnet_tf_name - network_compartment_id = commonTools.check_tf_variable(subnets.vcn_subnet_map[key][0]) - vcn_name = subnets.vcn_subnet_map[key][1] - oke_lb_subnets_list.append(subnets.vcn_subnet_map[key][2]) - except Exception as e: - print("Invalid Subnet Name specified for row {} and column \"{}\". It Doesnt exist in Subnets sheet. Exiting!!!".format(i+3,columnname)) - exit(1) - tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'oke_lb_subnets': json.dumps(oke_lb_subnets_list)} + oke_lb_subnets_list = [] + if columnname == 'Load Balancer Network Details': + if columnvalue!='': + oke_lb_subnets = str(columnvalue).strip().split(",") + if len(oke_lb_subnets) == 1: + columnvalue = str(oke_lb_subnets[0]).strip() + if ("ocid1.subnet.oc" in columnvalue): + subnet_id = columnvalue + oke_lb_subnets_list.append(subnet_id) + tempdict = {'oke_lb_subnets': json.dumps(oke_lb_subnets_list)} + + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") + exit(1) + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + oke_lb_subnets_list.append(subnet_id) + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'oke_lb_subnets': json.dumps(oke_lb_subnets_list)} elif len(oke_lb_subnets) > 1: for subnet in oke_lb_subnets: - if "ocid1.subnet.oc1" in subnet: - oke_lb_subnets_list.append(str(subnet).strip()) - else: - subnet_tf_name = commonTools.check_tf_variable(str(subnet).strip()) - try: - key = region, subnet_tf_name - network_compartment_id = commonTools.check_tf_variable(subnets.vcn_subnet_map[key][0]) - vcn_name = subnets.vcn_subnet_map[key][1] - oke_lb_subnets_list.append(subnets.vcn_subnet_map[key][2]) - except Exception as e: - print("Invalid Subnet Name specified for row {} and column \"{}\". It Doesnt exist in Subnets sheet. Exiting!!!".format(i+3,columnname)) + columnvalue = subnet + if ("ocid1.subnet.oc" in columnvalue): + subnet_id = columnvalue + oke_lb_subnets_list.append(subnet_id) + tempdict = {'oke_lb_subnets': json.dumps(oke_lb_subnets_list)} + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable( + columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'oke_lb_subnets': json.dumps(oke_lb_subnets_list) } - - if columnname == 'API Endpoint Subnet': - subnet_tf_name = str(columnvalue).strip().split() - if len(subnet_tf_name) == 1: - if len(subnet_tf_name[0]) == 0: - pass - elif ("ocid1.subnet.oc1" in str(subnet_tf_name[0]).strip()): - api_endpoint_subnet = str(subnet_tf_name[0]).strip() - network_compartment_id = '' - vcn_name = '' + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + oke_lb_subnets_list.append(subnet_id) + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, + 'oke_lb_subnets': json.dumps(oke_lb_subnets_list)} + + if columnname == 'API Endpoint Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id="root" + vcn_name="" + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() else: - try: - key = region, str(subnet_tf_name[0]).strip() - network_compartment_id = commonTools.check_tf_variable(subnets.vcn_subnet_map[key][0]) - vcn_name = subnets.vcn_subnet_map[key][1] - api_endpoint_subnet = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row {} and column \"{}\". It Doesnt exist in Subnets sheet. Exiting!!!".format(i+3,columnname)) - exit(1) - tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'api_endpoint_subnet': api_endpoint_subnet} - elif len(subnet_tf_name) > 1: - print("Invalid Subnet Values for row {} and column \"{}\". Only one subnet allowed".format(i+3,columnname)) - exit(1) + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") + exit(1) + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name, + 'api_endpoint_subnet': subnet_id} - if columnname == 'Worker Node Subnet': - subnet_tf_name = str(columnvalue).strip().split() - if len(subnet_tf_name) == 1: - if len(subnet_tf_name[0]) == 0: - pass - elif subnet_tf_name != "": - if ("ocid1.subnet.oc1" in str(subnet_tf_name[0]).strip()): - worker_node_subnet = str(subnet_tf_name[0]).strip() - network_compartment_id = '' - vcn_name = '' - else: - try: - key = region, str(subnet_tf_name[0]).strip() - network_compartment_id = commonTools.check_tf_variable(subnets.vcn_subnet_map[key][0]) - vcn_name = subnets.vcn_subnet_map[key][1] - worker_node_subnet = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row {} and column \"{}\". It Doesnt exist in Subnets sheet. Exiting!!!".format(i+3,columnname)) - exit(1) + if columnname == 'Worker Node Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + subnet_id = columnvalue + tempdict = {'worker_node_subnet': subnet_id} + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() else: - worker_node_subnet = "" - tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'worker_node_subnet': worker_node_subnet} - elif len(subnet_tf_name) > 1: - print("Invalid Subnet Values for row {} and column \"{}\". Only one subnet allowed".format(i+3,columnname)) - exit(1) + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") + exit(1) + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name, + 'worker_node_subnet': subnet_id} - if columnname == 'Pod Communication Subnet': - subnet_tf_name = columnvalue.strip() - if subnet_tf_name != "": - if ("ocid1.subnet.oc1" in subnet_tf_name): - pod_communication_subnet = subnet_tf_name - network_compartment_id = '' - vcn_name = '' + if columnname == 'Pod Communication Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + subnet_id = columnvalue + tempdict = {'pod_communication_subnet': subnet_id} + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() else: - try: - key = region, subnet_tf_name - network_compartment_id = commonTools.check_tf_variable(subnets.vcn_subnet_map[key][0]) - vcn_name = subnets.vcn_subnet_map[key][1] - pod_communication_subnet = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row {} and column \"{}\". It Doesnt exist in Subnets sheet. Exiting!!!".format(i+3,columnname)) - exit(1) - else: - pod_communication_subnet = "" - tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'pod_communication_subnet': pod_communication_subnet} + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") + exit(1) + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name, + 'pod_communication_subnet': subnet_id} if columnname == "API Endpoint NSGs": if columnvalue != '' and columnvalue.strip().lower() != 'nan': @@ -402,6 +416,7 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): node_str[region] = node_str[region] + node.render(tempStr) elif nodepool_type=='virtual': virtual_node_str[region] = virtual_node_str[region] + virtual_node.render(tempStr) + if i!=0 and (df.loc[i, 'Cluster Name'] == df.loc[i-1, 'Cluster Name']) and (df.loc[i, 'Region'] == df.loc[i-1, 'Region']): continue cluster_str[region] = cluster_str[region] + cluster.render(tempStr) @@ -417,7 +432,6 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): cluster_str[reg] = cluster.render(skeleton=True, count=0, region=reg).replace(src,cluster_str[reg]+"\n"+src) cluster_str[reg] = "".join([s for s in cluster_str[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) resource = sheetName.lower() - commonTools.backup_file(reg_out_dir, resource, cluster_auto_tfvars_filename) # Write to TF file outfile = reg_out_dir + "/" + cluster_auto_tfvars_filename @@ -433,7 +447,7 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): node_str[reg] = node.render(skeleton=True, count=0, region=reg).replace(src,node_str[reg]+"\n"+src) node_str[reg] = "".join([s for s in node_str[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) resource = sheetName.lower() - commonTools.backup_file(reg_out_dir, resource, nodepool_auto_tfvars_filename) + # Write to TF file outfile = reg_out_dir + "/" + nodepool_auto_tfvars_filename @@ -449,7 +463,6 @@ def create_terraform_oke(inputfile, outdir, service_dir, prefix, ct): virtual_node_str[reg] = virtual_node.render(skeleton=True, count=0, region=reg).replace(src,virtual_node_str[reg]+"\n"+src) virtual_node_str[reg] = "".join([s for s in virtual_node_str[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) resource = sheetName.lower() - commonTools.backup_file(reg_out_dir, resource, virtual_nodepool_auto_tfvars_filename) # Write to TF file outfile = reg_out_dir + "/" + virtual_nodepool_auto_tfvars_filename diff --git a/cd3_automation_toolkit/DeveloperServices/OKE/export_oke_nonGreenField.py b/cd3_automation_toolkit/DeveloperServices/OKE/export_oke_nonGreenField.py index c76ab0322..d00f490da 100644 --- a/cd3_automation_toolkit/DeveloperServices/OKE/export_oke_nonGreenField.py +++ b/cd3_automation_toolkit/DeveloperServices/OKE/export_oke_nonGreenField.py @@ -11,6 +11,7 @@ import oci import os import re +import subprocess as sp from oci.core.virtual_network_client import VirtualNetworkClient from oci.container_engine import ContainerEngineClient from oci.config import DEFAULT_LOCATION @@ -18,7 +19,7 @@ sys.path.append(os.getcwd() + "/..") -def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nodepool,nodepool_count, nodepool_info,cluster_info,network,nodepool_type): +def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nodepool,nodepool_count, nodepool_info,cluster_info,network,nodepool_type,ct): image_policy_config = cluster_info.image_policy_config for col_header in values_for_column_oke.keys(): if (col_header == "Region"): @@ -61,26 +62,40 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod cluster_info.options.admission_controller_options.is_pod_security_policy_enabled) else: values_for_column_oke[col_header].append(None) - elif col_header == 'Load Balancer Subnets': + elif col_header == 'Load Balancer Network Details': if nodepool_count <=1: subnets = [] for id in cluster_info.options.service_lb_subnet_ids: try: vcn = network.get_vcn(vcn_id=(network.get_subnet(subnet_id=id).data.vcn_id)).data.display_name subnet = network.get_subnet(subnet_id=id).data.display_name - combined = vcn + "_" + subnet + + ntk_compartment_id = network.get_vcn(vcn_id=(network.get_subnet(subnet_id=id).data.vcn_id)).data.compartment_id # compartment-id + network_compartment_name = compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + combined = network_compartment_name + "@" + vcn + "::" + subnet except Exception as e: combined = id subnets.append(combined) values_for_column_oke[col_header].append(','.join(subnets)) else: values_for_column_oke[col_header].append(None) - elif col_header == 'API Endpoint Subnet': + elif col_header == 'API Endpoint Network Details': if nodepool_count <= 1: try: vcn = network.get_vcn(vcn_id=(network.get_subnet(subnet_id=cluster_info.endpoint_config.subnet_id).data.vcn_id)).data.display_name subnet = network.get_subnet(subnet_id=cluster_info.endpoint_config.subnet_id).data.display_name - combined = vcn + "_" + subnet + ntk_compartment_id = network.get_vcn( + vcn_id=(network.get_subnet(subnet_id=cluster_info.endpoint_config.subnet_id).data.vcn_id)).data.compartment_id # compartment-id + network_compartment_name = compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + combined = network_compartment_name + "@" + vcn + "::" + subnet except Exception as e: combined = id values_for_column_oke[col_header].append(combined) @@ -115,13 +130,13 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod values_for_column_oke[col_header].append(','.join(nsgs)) else: values_for_column_oke[col_header].append(None) - elif (col_header == "CompartmentName&Node Pool Name:Node Pool Type"): + elif (col_header == "CompartmentName@Node Pool Name:Node Pool Type"): if (nodepool_info != None): if nodepool_type=="managed": - comp_np_value = compartment_name_nodepool + "&" + nodepool_info.name+":Managed" + comp_np_value = compartment_name_nodepool + "@" + nodepool_info.name+":Managed" values_for_column_oke[col_header].append(comp_np_value) elif nodepool_type == "virtual": - comp_np_value = compartment_name_nodepool + "&" + nodepool_info.display_name + ":Virtual" + comp_np_value = compartment_name_nodepool + "@" + nodepool_info.display_name + ":Virtual" values_for_column_oke[col_header].append(comp_np_value) else: @@ -193,7 +208,7 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod else: values_for_column_oke[col_header].append(None) - elif (col_header == "Worker Node Subnet"): + elif (col_header == "Worker Node Network Details"): if (nodepool_info != None): subnet_id = "" if (nodepool_type=='managed'): @@ -203,7 +218,14 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod try: vcn = network.get_vcn(vcn_id=(network.get_subnet(subnet_id=subnet_id).data.vcn_id)).data.display_name subnet = network.get_subnet(subnet_id=subnet_id).data.display_name - combined = vcn + "_" + subnet + ntk_compartment_id = network.get_vcn( + vcn_id=(network.get_subnet(subnet_id=subnet_id).data.vcn_id)).data.compartment_id # compartment-id + network_compartment_name = compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + combined = network_compartment_name + "@" + vcn + "::" + subnet except Exception as e: combined = id values_for_column_oke[col_header].append(combined) @@ -272,7 +294,7 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod values_for_column_oke[col_header].append(','.join(nsgs)) else: values_for_column_oke[col_header].append(None) - elif (col_header == "Pod Communication Subnet"): + elif (col_header == "Pod Communication Network Details"): if (nodepool_info != None): if nodepool_type == "managed": if nodepool_info.node_config_details.node_pool_pod_network_option_details.cni_type == "OCI_VCN_IP_NATIVE": @@ -281,7 +303,14 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod try: vcn = network.get_vcn(vcn_id=(network.get_subnet(subnet_id=id).data.vcn_id)).data.display_name subnet = network.get_subnet(subnet_id=id).data.display_name - combined = vcn + "_" + subnet + ntk_compartment_id = network.get_vcn(vcn_id=( + network.get_subnet(subnet_id=id).data.vcn_id)).data.compartment_id # compartment-id + network_compartment_name = compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + combined = network_compartment_name + "@" + vcn + "::" + subnet except Exception as e: combined = id subnets.append(combined) @@ -293,7 +322,14 @@ def print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nod try: vcn = network.get_vcn(vcn_id=(network.get_subnet(subnet_id=pod_subnet_id).data.vcn_id)).data.display_name subnet = network.get_subnet(subnet_id=pod_subnet_id).data.display_name - combined = vcn + "_" + subnet + ntk_compartment_id = network.get_vcn( + vcn_id=(network.get_subnet(subnet_id=pod_subnet_id).data.vcn_id)).data.compartment_id # compartment-id + network_compartment_name = compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + combined = network_compartment_name + "@" + vcn + "::" + subnet except Exception as e: combined = id values_for_column_oke[col_header].append(combined) @@ -402,7 +438,9 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart global importCommands global tf_import_cmd global values_for_column_oke - global sheet_dict_oke + global sheet_dict_oke,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -410,12 +448,11 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart exit() sheetName = "OKE" - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' importCommands={} - df, values_for_column_oke = commonTools.read_cd3(cd3file, "OKE") # Get dict for columns from Excel_Columns @@ -427,23 +464,27 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart # Create backups for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - if os.path.exists(script_file): - commonTools.backup_file(outdir + "/" + reg+"/"+service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + if (os.path.exists(script_file)): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + importCommands[reg] = '' # Fetch OKE Details print("\nFetching details of OKE...") tempImageDict = {} tempsshDict = {} + total_resources = 0 for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - importCommands[reg].write("\n\n######### Writing import for OKE Objects #########\n\n") - importCommands[reg].write("\n\n######### Writing import for OKE Objects #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass oke = ContainerEngineClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) network = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -454,16 +495,18 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart compartment_name], lifecycle_state=["ACTIVE"],sort_by="TIME_CREATED") clusterList.extend(clusterResponse.data) + total_resources +=len(clusterList) for cluster_info in clusterList: empty_cluter = True nodepool_count = 0 nodepool_info = None nodepool_type="" - importCommands[reg] = open(script_file, "a") cluster_display_name = cluster_info.name cluster_tf_name = commonTools.check_tf_variable(cluster_display_name) - importCommands[reg].write("\nterraform import \"module.clusters[\\\"" + str(cluster_tf_name) + "\\\"].oci_containerengine_cluster.cluster\" " + cluster_info.id) + tf_resource = f'module.clusters[\\"{str(cluster_tf_name)}\\"].oci_containerengine_cluster.cluster' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {cluster_info.id}' for compartment_name_nodepool in export_compartments: nodepoolList = [] @@ -486,13 +529,14 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart empty_cluter = False nodepool_count=nodepool_count+1 - importCommands[reg] = open(script_file, "a") #Virtual NodePool if ("ocid1.virtualnodepool.oc1" in nodepool_info.id): nodepool_display_name = nodepool_info.display_name np_tf_name = commonTools.check_tf_variable(nodepool_display_name) - importCommands[reg].write("\nterraform import \"module.virtual-nodepools[\\\"" + str(cluster_tf_name) + "_" + str(np_tf_name) + "\\\"].oci_containerengine_virtual_node_pool.virtual_nodepool\" " + nodepool_info.id) + tf_resource = f'module.virtual-nodepools[\\"{cluster_tf_name}_{np_tf_name}\\"].oci_containerengine_virtual_node_pool.virtual_nodepool' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {nodepool_info.id}' nodepool_type = "virtual" # Managed NodePool @@ -500,8 +544,9 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart nodepool_display_name = nodepool_info.name np_tf_name = commonTools.check_tf_variable(nodepool_display_name) nodepool_type = "managed" - importCommands[reg].write("\nterraform import \"module.nodepools[\\\"" + str(cluster_tf_name) + "_" + str( - np_tf_name) + "\\\"].oci_containerengine_node_pool.nodepool\" " + nodepool_info.id) + tf_resource = f'module.nodepools[\\"{cluster_tf_name}_{np_tf_name}\\"].oci_containerengine_node_pool.nodepool' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {nodepool_info.id}' # Extract the image details tempImageDict[reg + "::" + commonTools.check_tf_variable(nodepool_info.node_source.source_name)] = nodepool_info.node_source.image_id @@ -511,10 +556,10 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart elif nodepool_info.ssh_public_key: tempsshDict[reg + "::" + commonTools.check_tf_variable(cluster_display_name + "_" + nodepool_info.name) + "_" + nodepool_info.id[-6:]] = nodepool_info.ssh_public_key - print_oke(values_for_column_oke,reg, compartment_name, compartment_name_nodepool,nodepool_count,nodepool_info,cluster_info,network,nodepool_type) + print_oke(values_for_column_oke,reg, compartment_name, compartment_name_nodepool,nodepool_count,nodepool_info,cluster_info,network,nodepool_type,ct) if(empty_cluter==True): - print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nodepool,nodepool_count, nodepool_info,cluster_info,network,nodepool_type) + print_oke(values_for_column_oke, reg, compartment_name, compartment_name_nodepool,nodepool_count, nodepool_info,cluster_info,network,nodepool_type,ct) # write oke image ocids and ssh keys @@ -571,11 +616,13 @@ def export_oke(inputfile, outdir,service_dir, config, signer, ct, export_compart # writing data for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/tf_import_commands_oke_nonGF.sh' - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + init_commands = f'\n######### Writing import for OKE #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) commonTools.write_to_cd3(values_for_column_oke, cd3file, "OKE") - - print("{0} OKE exported into CD3.\n".format(len(values_for_column_oke["Region"]))) + print("{0} OKE clusters exported into CD3.\n".format(total_resources)) diff --git a/cd3_automation_toolkit/DeveloperServices/ResourceManager/create_resource_manager_stack.py b/cd3_automation_toolkit/DeveloperServices/ResourceManager/create_resource_manager_stack.py index 106dc6359..1377eab63 100644 --- a/cd3_automation_toolkit/DeveloperServices/ResourceManager/create_resource_manager_stack.py +++ b/cd3_automation_toolkit/DeveloperServices/ResourceManager/create_resource_manager_stack.py @@ -34,7 +34,7 @@ def create_rm(service_rm_name, comp_id,ocs_stack,svcs): stackdetails.description = "Created by Automation ToolKit" else: stackdetails.description = "Created by Automation ToolKit for services - "+ ','.join(svcs) - stackdetails.terraform_version = "1.0.x" + stackdetails.terraform_version = "1.5.x" stackdetails.compartment_id = comp_id stackdetails.display_name = service_rm_name @@ -63,7 +63,7 @@ def update_rm(service_rm_name,service_rm_ocid,ocs_stack,svcs): zipConfigSource.config_source_type = 'ZIP_UPLOAD' zipConfigSource.zip_file_base64_encoded = encodedZip updatestackdetails.config_source = zipConfigSource - updatestackdetails.terraform_version = "1.0.x" + updatestackdetails.terraform_version = "1.5.x" if svcs == []: updatestackdetails.description = "Updated by Automation ToolKit" else: @@ -136,10 +136,10 @@ def create_resource_manager(outdir,var_file, outdir_struct,prefix,auth_mechanism for line in origfile: if 'version' in line or 'tenancy_ocid' in line or "user_ocid" in line or "fingerprint" in line or "private_key_path" in line: pass - elif 'terraform {' in line: - experimental_line = "experiments = [module_variable_optional_attrs]" - line = line + "\n " + experimental_line + "\n " - newfile.write(line) + #elif 'terraform {' in line: + # experimental_line = "experiments = [module_variable_optional_attrs]" + # line = line + "\n " + experimental_line + "\n " + # newfile.write(line) else: newfile.write(line) except FileNotFoundError as e: @@ -150,10 +150,12 @@ def create_resource_manager(outdir,var_file, outdir_struct,prefix,auth_mechanism try: with open(region_dir + '/variables_' + region + '.tf') as origfile, open(rm_dir + '/variables_' + region + '.tf', 'w') as newfile: for line in origfile: + ''' if 'gateway_route_table = optional(bool,false)' in line: line = line.replace('gateway_route_table = optional(bool,false)','gateway_route_table = optional(bool)') if 'default_route_table = optional(bool,false)' in line: line = line.replace('default_route_table = optional(bool,false)','default_route_table = optional(bool)') + ''' if "user_ocid" in line or "fingerprint" in line or "private_key_path" in line: skipline = True if not skipline: @@ -171,10 +173,11 @@ def create_resource_manager(outdir,var_file, outdir_struct,prefix,auth_mechanism for line in origfile: if 'version' in line or 'tenancy_ocid' in line or "user_ocid" in line or "fingerprint" in line or "private_key_path" in line: pass - elif 'terraform {' in line: - experimental_line = "experiments = [module_variable_optional_attrs]" - line = line+"\n "+experimental_line+"\n " - newfile.write(line) + + #elif 'terraform {' in line: + # experimental_line = "experiments = [module_variable_optional_attrs]" + # line = line+"\n "+experimental_line+"\n " + # newfile.write(line) else: newfile.write(line) except FileNotFoundError as e: @@ -185,12 +188,14 @@ def create_resource_manager(outdir,var_file, outdir_struct,prefix,auth_mechanism try: with open(region_dir+'/'+service_dir+'/variables_' + region + '.tf') as origfile, open(rm_dir + '/'+ service_dir +'/variables_' + region + '.tf','w') as newfile: for line in origfile: + ''' if 'gateway_route_table = optional(bool,false)' in line: line = line.replace('gateway_route_table = optional(bool,false)', 'gateway_route_table = optional(bool)') if 'default_route_table = optional(bool,false)' in line: line = line.replace('default_route_table = optional(bool,false)', 'default_route_table = optional(bool)') + ''' if "user_ocid" in line or "fingerprint" in line or "private_key_path" in line: skipline = True if not skipline: diff --git a/cd3_automation_toolkit/Excel_Columns b/cd3_automation_toolkit/Excel_Columns index 9bd2b229f..045eff600 100644 --- a/cd3_automation_toolkit/Excel_Columns +++ b/cd3_automation_toolkit/Excel_Columns @@ -106,7 +106,7 @@ }, "LB-BackendSet-BackendServer" : { - "Backend ServerComp&ServerName:Port" : "backend_server_name:port", + "Backend ServerComp@ServerName:Port" : "backend_server_name:port", "Backend Set Name" : "backend_set_name", "Certificate Name or OCID" : "certificates", "Backend Policy(LEAST_CONNECTIONS|ROUND_ROBIN|IP_HASH)" : "policy", @@ -144,6 +144,10 @@ "LB-PathRouteSet": { "Path Route Set Name" : "name" + }, + "LB-RoutingPolicy": + { + "Display Name" : "display_name" }, "Common-LBR-Headers" : { @@ -165,7 +169,7 @@ "Service CIDR Block" : "services_cidr", "Pod CIDR Block" : "pods_cidr", "API Endpoint NSGs" : "nsg_ids", - "CompartmentName&Node Pool Name" : "nodepool_display_name", + "CompartmentName@Node Pool Name" : "nodepool_display_name", "Policy KMS Key ID" : "image_policy_config.key_details.kms_key_id" }, @@ -236,7 +240,7 @@ "NLB-BackendSets-BackendServers" : { "Is Preserve Source(True|False)" : "is_preserve_source", - "Backend ServerComp&ServerName:Port" : "backend_server_name:port", + "Backend ServerComp@ServerName:Port" : "backend_server_name:port", "Backend Set Name" : "backend_set_name", "Backend Policy(FIVE_TUPLE|THREE_TUPLE|TWO_TUPLE)" : "policy", "Backend HealthCheck Protocol(HTTP|HTTPS|TCP|UDP|DNS)" : "protocol", diff --git a/cd3_automation_toolkit/Governance/Quota/create_terraform_quotas.py b/cd3_automation_toolkit/Governance/Quota/create_terraform_quotas.py index 32855f4e0..bbe55bae7 100644 --- a/cd3_automation_toolkit/Governance/Quota/create_terraform_quotas.py +++ b/cd3_automation_toolkit/Governance/Quota/create_terraform_quotas.py @@ -45,6 +45,10 @@ def create_terraform_quotas(inputfile, outdir, service_dir, prefix, ct): # Initialise empty TF string for each region tfStr[ct.home_region] = '' + resource = sheetName.lower() + reg = ct.home_region + reg_out_dir = outdir + "/" + reg + "/" + service_dir + commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) # Iterate over rows for i in df.index: @@ -125,10 +129,6 @@ def create_terraform_quotas(inputfile, outdir, service_dir, prefix, ct): src = "##Add New quota-policy for "+reg.lower()+" here##" tfStr[reg] = quota_template.render(count=0, region=reg).replace(src, tfStr[reg]) tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - - resource = sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) - tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) oname[reg] = open(outfile[reg], 'w') oname[reg].write(tfStr[reg]) diff --git a/cd3_automation_toolkit/Governance/Quota/export_quotas_nonGreenField.py b/cd3_automation_toolkit/Governance/Quota/export_quotas_nonGreenField.py index 33a32d490..b324502c5 100644 --- a/cd3_automation_toolkit/Governance/Quota/export_quotas_nonGreenField.py +++ b/cd3_automation_toolkit/Governance/Quota/export_quotas_nonGreenField.py @@ -9,6 +9,7 @@ import sys import oci import os +import subprocess as sp from commonTools import * sys.path.append(os.getcwd()+"/..") @@ -35,9 +36,11 @@ def export_quotas_nongreenfield(inputfile, outdir, service_dir, config, signer, global tf_import_cmd global values_for_column_quotas global sheet_dict_quotas - global importCommands + global importCommands,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] sheet_name = 'Quotas' - script_file = f'{outdir}/{ct.home_region}/{service_dir}/tf_import_commands_'+sheet_name.lower()+'_nonGF.sh' + script_file = f'{outdir}/{ct.home_region}/{service_dir}/import_commands_'+sheet_name.lower()+'.sh' cd3file = inputfile importCommands = "" if ('.xls' not in cd3file): @@ -55,21 +58,26 @@ def export_quotas_nongreenfield(inputfile, outdir, service_dir, config, signer, # Create backups if os.path.exists(script_file): - commonTools.backup_file(os.path.dirname(script_file), "tf_import_"+sheet_name.lower(), os.path.basename(script_file)) + commonTools.backup_file(os.path.dirname(script_file), "import_"+sheet_name.lower(), os.path.basename(script_file)) # Fetch quotas print("\nFetching quotas...") - config.__setitem__("region", ct.region_dict[ct.home_region]) + reg = (ct.home_region).lower() + config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass tenancy_id = config["tenancy"] quotas_client = oci.limits.QuotasClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = ct.home_region.lower() quotas_list = oci.pagination.list_call_get_all_results(quotas_client.list_quotas,compartment_id=tenancy_id,lifecycle_state="ACTIVE") if quotas_list.data != []: - importCommands += "\n######### Writing import for quotas #########\n\n" - importCommands += "#!/bin/bash" - importCommands += "\n" - importCommands += "terraform init" for quota_info in quotas_list.data: quota_policy = "" quota = quotas_client.get_quota(quota_id=quota_info.id).data @@ -78,14 +86,17 @@ def export_quotas_nongreenfield(inputfile, outdir, service_dir, config, signer, print_quotas(values_for_column_quotas, region, quota,quota_policy[1:]) quota_tf_name = commonTools.check_tf_variable(quota_info.name) - importCommands += "\nterraform import \"module.quota_policies[\\\"" + quota_tf_name+ "\\\"].oci_limits_quota.quota\" " + str(quota_info.id) + tf_resource = f'module.quota_policies[\\"{quota_tf_name}\\"].oci_limits_quota.quota' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {str(quota_info.id)}' - importCommands += "\nterraform plan" commonTools.write_to_cd3(values_for_column_quotas, cd3file, sheet_name) print("{0} quotas exported into CD3.\n".format(len(values_for_column_quotas["Region"]))) + init_commands = f'\n######### Writing import for Quota #########\n\n#!/bin/bash\n{tf_or_tofu} init' if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' with open(script_file, 'a') as importCommandsfile: - importCommandsfile.write(importCommands) + importCommandsfile.write(init_commands + importCommands) diff --git a/cd3_automation_toolkit/Governance/Tagging/export_tags_nonGreenField.py b/cd3_automation_toolkit/Governance/Tagging/export_tags_nonGreenField.py index 9d4a9e500..003e27372 100644 --- a/cd3_automation_toolkit/Governance/Tagging/export_tags_nonGreenField.py +++ b/cd3_automation_toolkit/Governance/Tagging/export_tags_nonGreenField.py @@ -11,12 +11,12 @@ import oci from oci.identity import IdentityClient import os +import subprocess as sp from commonTools import * sys.path.append(os.getcwd()+"/..") compartment_ids={} -importCommands={} tf_name_namespace_list = [] def add_values_in_dict(sample_dict, key, list_of_values): @@ -27,7 +27,7 @@ def add_values_in_dict(sample_dict, key, list_of_values): sample_dict[key].extend(list_of_values) return sample_dict -def print_tags(values_for_column_tags,region, ntk_compartment_name, tag, tag_key, tag_default_value): +def print_tags(values_for_column_tags,region, ntk_compartment_name, tag, tag_key, tag_default_value,reg,state): validator = '' tag_key_name = '' tag_key_description = '' @@ -84,15 +84,20 @@ def print_tags(values_for_column_tags,region, ntk_compartment_name, tag, tag_ke tf_name_namespace = commonTools.check_tf_variable(tagname) tf_name_key = commonTools.check_tf_variable(tag_key_name) - if (tag.id not in tf_name_namespace_list): - importCommands[region].write("\nterraform import \"module.tag-namespaces[\\\"" + tf_name_namespace + "\\\"].oci_identity_tag_namespace.tag_namespace\" " + str(tag.id)) + tf_resource = f'module.tag-namespaces[\\"{tf_name_namespace}\\"].oci_identity_tag_namespace.tag_namespace' + if tag.id not in tf_name_namespace_list and tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {str(tag.id)}' tf_name_namespace_list.append(tag.id) - if ( str(tag_key) != "Nan" ): - importCommands[region].write("\nterraform import \"module.tag-keys[\\\""+tf_name_namespace + '_' + tf_name_key + '\\\"].oci_identity_tag.tag\" ' + "tagNamespaces/"+ str(tag.id) +"/tags/\"" + str(tag_key_name) + "\"") - if ( tag_default_value != []): + tf_resource = f'module.tag-keys[\\"{tf_name_namespace}_{tf_name_key}\\"].oci_identity_tag.tag' + if str(tag_key) != "Nan" and tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" tagNamespaces/{str(tag.id)}/tags/{str(tag_key_name)}' + if tag_default_value != []: if len(tag_default_value) != 0: for value in tag_default_value: - importCommands[region].write("\nterraform import \"module.tag-defaults[\\\""+ tf_name_namespace+'_' +tf_name_key + '_' +commonTools.check_tf_variable(value.split("=")[0]).strip()+ '-default'+ '\\\"].oci_identity_tag_default.tag_default\" ' + str(defaultcomp_to_tagid_map[tf_name_key+"-"+commonTools.check_tf_variable(value.split("=")[0])])) + tf_resource = f'module.tag-defaults[\\"{tf_name_namespace}_{tf_name_key}_{commonTools.check_tf_variable(value.split("=")[0]).strip()}-default\\"].oci_identity_tag_default.tag_default' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {str(defaultcomp_to_tagid_map[tf_name_key+"-"+commonTools.check_tf_variable(value.split("=")[0])])}' + # Execution of the code begins here def export_tags_nongreenfield(inputfile, outdir, service_dir, config, signer, ct, export_compartments): @@ -101,40 +106,51 @@ def export_tags_nongreenfield(inputfile, outdir, service_dir, config, signer, ct global sheet_dict_tags global importCommands global tag_default_comps_map - global defaultcomp_to_tagid_map + global defaultcomp_to_tagid_map,tf_or_tofu + importCommands = {} + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile + sheetName="Tags" if ('.xls' not in cd3file): print("\nAcceptable cd3 format: .xlsx") exit() # Read CD3 - df, values_for_column_tags = commonTools.read_cd3(cd3file, "Tags") + df, values_for_column_tags = commonTools.read_cd3(cd3file, sheetName) tag_default_comps_map = {} tag_name_id_map = {} defaultcomp_to_tagid_map = {} # Get dict for columns from Excel_Columns - sheet_dict_tags = ct.sheet_dict["Tags"] + sheet_dict_tags = ct.sheet_dict[sheetName] print("\nCD3 excel file should not be opened during export process!!!") print("Tabs- Tags would be overwritten during export process!!!\n") - # Create backups - if (os.path.exists(outdir + "/" + ct.home_region + "/" + service_dir + "/tf_import_commands_tags_nonGF.sh")): - commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, "tf_import_tags", "tf_import_commands_tags_nonGF.sh") - importCommands[ct.home_region] = open(outdir + "/" + ct.home_region + "/" + service_dir + "/tf_import_commands_tags_nonGF.sh", "w") - importCommands[ct.home_region].write("#!/bin/bash") - importCommands[ct.home_region].write("\n") - importCommands[ct.home_region].write("terraform init") + # Create backup + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' + script_file = f'{outdir}/{ct.home_region}/{service_dir}/' + file_name + if (os.path.exists(script_file)): + commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, resource, file_name) + importCommands[ct.home_region] = '' # Fetch Tags print("\nFetching Tags...") - importCommands[ct.home_region].write("\n\n######### Writing import for Tags #########\n\n") config.__setitem__("region", ct.region_dict[ct.home_region]) + state = {'path': f'{outdir}/{ct.home_region}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass identity = IdentityClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = ct.home_region.lower() comp_ocid_done = [] @@ -181,8 +197,7 @@ def export_tags_nongreenfield(inputfile, outdir, service_dir, config, signer, ct tag_default_check.append(str(tag_key.id)) tag_default_value = tag_default_comps_map[tag_key.id+"="+tag_key.name] tag_namespace_check.append(str(tag.id)) - print_tags(values_for_column_tags, region, ntk_compartment_name, tag, tag_key,tag_default_value) - + print_tags(values_for_column_tags, region, ntk_compartment_name, tag, tag_key,tag_default_value,ct.home_region,state) check_non_default_tags = [i for i in tag_key_check + tag_default_check if i not in tag_key_check or i not in tag_default_check] for tag_check in check_non_default_tags: for tag_key in tag_keys.data: @@ -191,8 +206,7 @@ def export_tags_nongreenfield(inputfile, outdir, service_dir, config, signer, ct tag_key = tag_key.data tag_default_value = '' tag_namespace_check.append(str(tag.id)) - print_tags(values_for_column_tags, region, ntk_compartment_name, tag, tag_key,tag_default_value) - + print_tags(values_for_column_tags, region, ntk_compartment_name, tag, tag_key,tag_default_value,ct.home_region,state) tag_namespace_check = list(dict.fromkeys(tag_namespace_check)) check_non_key_tags = [i for i in tag_list + tag_namespace_check if i not in tag_list or i not in tag_namespace_check] for tag_check in check_non_key_tags: @@ -201,12 +215,14 @@ def export_tags_nongreenfield(inputfile, outdir, service_dir, config, signer, ct for tag in tags.data: if (tag_check in tag.id): tag = identity.get_tag_namespace(tag.id).data - print_tags(values_for_column_tags, region, ntk_compartment_name, tag, tag_key,tag_default_value) + print_tags(values_for_column_tags, region, ntk_compartment_name, tag, tag_key,tag_default_value,ct.home_region,state) commonTools.write_to_cd3(values_for_column_tags, cd3file, "Tags") - print("{0} Tags exported into CD3.\n".format(len(values_for_column_tags["Region"]))) + print("{0} rows exported into CD3 for Tagging Resources.\n".format(len(values_for_column_tags["Region"]))) - script_file = f'{outdir}/{ct.home_region}/{service_dir}/tf_import_commands_tags_nonGF.sh' - with open(script_file, 'a') as importCommands[ct.home_region]: - importCommands[ct.home_region].write('\n\nterraform plan\n') + init_commands = f'\n######### Writing import for Tagging #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[ct.home_region] != "": + importCommands[ct.home_region] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[ct.home_region]) diff --git a/cd3_automation_toolkit/Identity/Groups/create_terraform_groups.py b/cd3_automation_toolkit/Identity/Groups/create_terraform_groups.py index 48822f13b..d7d80b053 100644 --- a/cd3_automation_toolkit/Identity/Groups/create_terraform_groups.py +++ b/cd3_automation_toolkit/Identity/Groups/create_terraform_groups.py @@ -6,7 +6,7 @@ # # Author: Suruchi Singla # Oracle Consulting -# Modified (TF Upgrade): Shruthi Subramanian +# Modified by: Ranjini Rajendran # import os from pathlib import Path @@ -33,6 +33,9 @@ def create_terraform_groups(inputfile, outdir, service_dir, prefix, ct): file_loader = FileSystemLoader(f'{Path(__file__).parent}/templates') env = Environment(loader=file_loader, keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) groups_template = env.get_template('groups-template') + identity_domain_groups_template = env.get_template('identity-domain-groups-template') + + selected_template = identity_domain_groups_template if ct.identity_domain_enabled else groups_template # Read cd3 using pandas dataframe df, col_headers = commonTools.read_cd3(filename, sheetName) @@ -47,7 +50,6 @@ def create_terraform_groups(inputfile, outdir, service_dir, prefix, ct): # Initialise empty TF string for each region tfStr[ct.home_region] = '' - # Take backup of files srcdir = outdir + "/" + ct.home_region + "/" + service_dir + "/" resource = sheetName.lower() @@ -76,10 +78,37 @@ def create_terraform_groups(inputfile, outdir, service_dir, prefix, ct): print("\nThe values for Region and Name cannot be left empty. Please enter a value and try again !!") exit(1) - for columnname in dfcolumns: + # Initialize domain variable + domain = str(df.loc[i, 'Domain Name']).strip() + compartment_id = "" + + if not ct.identity_domain_enabled: + domain='' + if ct.identity_domain_enabled and domain.lower() == 'nan': + domain = 'DEFAULT' + compartment_id = 'root' + if ct.identity_domain_enabled and domain.lower() != 'nan': + domain = str(domain).strip() + split_domain = domain.split('@', 1) + if len(split_domain) == 2: + compartmentVarName, domain = split_domain + if compartmentVarName.lower() == 'root' or compartmentVarName == '': + compartment_id = 'root' + else: + if compartmentVarName.startswith('root::'): + compartmentVarName = compartmentVarName[len('root::'):] + compartment_id = compartmentVarName.strip() + compartment_id = commonTools.check_tf_variable(compartment_id) + compartment_id = str(compartment_id) + if domain.lower() == 'default': + domain = 'DEFAULT' + else: + domain = domain + compartment_id = 'root' + for columnname in dfcolumns: # Column value - if 'description' in columnname.lower(): + if 'Description' in columnname.lower(): columnvalue = str(df[columnname][i]) tempdict = {'description': columnvalue} else: @@ -93,18 +122,39 @@ def create_terraform_groups(inputfile, outdir, service_dir, prefix, ct): tempdict = commonTools.split_tag_values(columnname, columnvalue, tempdict) if columnname == 'Name': - columnvalue = columnvalue.strip() - group_tf_name = commonTools.check_tf_variable(columnvalue) - tempdict = {'group_tf_name': group_tf_name} - - # If description field is empty; put name as description - if columnname == 'Description': - if columnvalue == "" or columnvalue == 'nan': - columnvalue = df.loc[i,'Name'] - tempdict = {'description': columnvalue } + #columnvalue = columnvalue.strip() + group_tf_name = f"{domain}_{commonTools.check_tf_variable(columnvalue)}" + if group_tf_name.startswith('_'): + group_tf_name = group_tf_name[1:] + tempdict = {'group_tf_name': group_tf_name,'domain': domain , 'compartment_id': compartment_id} + + if columnname == 'Members': + members='' + if columnvalue.lower()!='nan' and columnvalue!='': + members=[x.strip() for x in columnvalue.split(',')] + members = ','.join(members) + tempdict = {'members': members} + + # Process Defined and Freeform Tags based on columnname and 'Domain Name' + if columnname.lower() in commonTools.tagColumns: + # for IDCS tenancies + if not ct.identity_domain_enabled: + # Process tags using the existing code + tempdict = commonTools.split_tag_values(columnname, columnvalue, tempdict) else: - columnvalue = commonTools.check_columnvalue(columnvalue) - tempdict = {'description': columnvalue} + if columnname == 'Defined Tags': + defined_tags = columnvalue.strip() + tag_strings = defined_tags.split(';') + + defined_tags_list = [] + for tag_string in tag_strings: + parts = tag_string.split('=') + if len(parts) == 2: + namespace_key = parts[0] + value = parts[1] + namespace, key = namespace_key.split('.') + tempdict = {'namespace': namespace, 'key': key, 'value': value} + defined_tags_list.append(tempdict) # Check for boolean/null in column values columnvalue = commonTools.check_columnvalue(columnvalue) @@ -114,7 +164,7 @@ def create_terraform_groups(inputfile, outdir, service_dir, prefix, ct): tempStr.update(tempdict) # Write all info to TF string - tfStr[region]= tfStr[region][:-1] + groups_template.render(tempStr) + tfStr[region]= tfStr[region].rsplit('}',1)[0] + selected_template.render(tempStr) # Write TF string to the file in respective region directory reg=ct.home_region diff --git a/cd3_automation_toolkit/Identity/Groups/templates/groups-template b/cd3_automation_toolkit/Identity/Groups/templates/groups-template index b7148d74d..0c098551c 100644 --- a/cd3_automation_toolkit/Identity/Groups/templates/groups-template +++ b/cd3_automation_toolkit/Identity/Groups/templates/groups-template @@ -23,6 +23,13 @@ groups = { EOF {% endif %} {% endif %} + {% if members %} + members = [ + {% for member in members.split(',') %} + "{{ member }}", + {% endfor %} + ] + {% endif %} {# ##Do not modify below this line## #} {# #} diff --git a/cd3_automation_toolkit/Identity/Groups/templates/identity-domain-groups-template b/cd3_automation_toolkit/Identity/Groups/templates/identity-domain-groups-template new file mode 100644 index 000000000..489b3fb68 --- /dev/null +++ b/cd3_automation_toolkit/Identity/Groups/templates/identity-domain-groups-template @@ -0,0 +1,66 @@ +{% if count == 0 %} +// Copyright (c) 2021, 2022, Oracle and/or its affiliates. + +############################ +# Identity +# Groups - tfvars +# Sample import command for groups: +# terraform import "module.groups[\"<>\"].oci_identity_domains_group.group[0]" idcsEndpoint/<>/groups/<> +# terraform import "module.groups[\"<>\"].oci_identity_domains_dynamic_resource_group.dynamic_group[0]" idcsEndpoint/<>/dynamicResourceGroups/<> +############################ + +identity_domain_groups = { +{% endif %} + {{ group_tf_name }} = { + group_name = "{{ name }}" + group_description = "{{ description }}" + idcs_endpoint = "{{ domain }}" + compartment_id = "{{compartment_id}}" + {% if matching_rule != "" %} + {% if '\n' not in matching_rule %} + matching_rule = "{{ matching_rule }}" + {% else %} + matching_rule = <<-EOF + {{ matching_rule }} + EOF + {% endif %} + {% endif %} + {% if members %} + members = [ + {% for member in members.split(',') %} + "{{ member }}", + {% endfor %} + ] + {% endif %} + + {# ##Do not modify below this line## #} + {# #} + {# ###Section for adding Defined and Freeform Tags### #} + {% if defined_tags and defined_tags != 'nan' and defined_tags != '' and defined_tags != [['nan']] %} + defined_tags = [ + {% for tag_string in defined_tags.split(';') %} + {% set parts = tag_string.split('=') %} + {% if parts|length == 2 %} + { + key = "{{ parts[0].split('.')[1] }}" + namespace = "{{ parts[0].split('.')[0] }}" + value = "{{ parts[1] }}" + }{% if not loop.last %}, + {% endif %} + {% endif %} + {% endfor %} + ] + {% endif %} + + {% if freeform_tags and freeform_tags != 'nan' and freeform_tags != '' and freeform_tags != [['nan']] %} + {% if freeform_tags[0] %} + freeform_tags = { + key = "{{ key }}" + value = "{{ value }}" + } + {% endif %} + {% endif %} + {# ###Section for adding Defined and Freeform Tags ends here### #} + }, + + } \ No newline at end of file diff --git a/cd3_automation_toolkit/Identity/NetworkSources/export_networkSources_nonGreenField.py b/cd3_automation_toolkit/Identity/NetworkSources/export_networkSources_nonGreenField.py index ec4f56741..352be8894 100644 --- a/cd3_automation_toolkit/Identity/NetworkSources/export_networkSources_nonGreenField.py +++ b/cd3_automation_toolkit/Identity/NetworkSources/export_networkSources_nonGreenField.py @@ -12,13 +12,16 @@ import oci from oci.identity import IdentityClient import os +import subprocess as sp sys.path.append(os.getcwd()+"/..") from commonTools import * # Execution of the code begins here def export_networkSources(inputfile, outdir, service_dir, config, signer, ct): global values_for_column_networkSources - global cd3file + global cd3file,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -26,7 +29,7 @@ def export_networkSources(inputfile, outdir, service_dir, config, signer, ct): print("\nAcceptable cd3 format: .xlsx") exit() - importCommands={} + importCommands = "" sheetName = "NetworkSources" @@ -37,22 +40,25 @@ def export_networkSources(inputfile, outdir, service_dir, config, signer, ct): print("Tab- Network Sources would be overwritten during export process!!!\n") # Create backup - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' script_file = f'{outdir}/{ct.home_region}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, resource, file_name) - importCommands[ct.home_region] = open(script_file, "w") - importCommands[ct.home_region].write("#!/bin/bash") - importCommands[ct.home_region].write("\n") - importCommands[ct.home_region].write("terraform init") config.__setitem__("region", ct.region_dict[ct.home_region]) + state = {'path': f'{outdir}/{ct.home_region}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass idc=IdentityClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) # Fetch Network Sources print("\nFetching Network Sources...") - importCommands[ct.home_region].write("\n######### Writing import for Network Sources #########\n") network_sources = oci.pagination.list_call_get_all_results(idc.list_network_sources ,compartment_id=config['tenancy']) compIDvsName = {} @@ -61,14 +67,17 @@ def export_networkSources(inputfile, outdir, service_dir, config, signer, ct): compIDvsName[ct.ntk_compartment_ids[key]] = key index = 0 + total_resource = 0 + for network_source in network_sources.data: + total_resource = total_resource+1 network_source_info = network_source name = network_source_info.name tf_name = commonTools.check_tf_variable(name) - - importCommands[ct.home_region].write("\nterraform import \"module.iam-network-sources[\\\"" + str( - tf_name) + "\\\"].oci_identity_network_source.network_source \" " + network_source_info.id) + tf_resource = f'module.iam-network-sources[\\"{tf_name}\\"].oci_identity_network_source.network_source' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {str(network_source_info.id)}' index = index + 1 for col_header in values_for_column_networkSources.keys(): @@ -104,8 +113,10 @@ def export_networkSources(inputfile, outdir, service_dir, config, signer, ct): values_for_column_networkSources = commonTools.export_tags(network_source_info, col_header, values_for_column_networkSources) commonTools.write_to_cd3(values_for_column_networkSources, cd3file, sheetName) - print("{0} Network Sources exported into CD3.\n".format(len(values_for_column_networkSources["Region"]))) - - with open(script_file, 'a') as importCommands[ct.home_region]: - importCommands[ct.home_region].write('\n\nterraform plan\n') + print("{0} Network Sources exported into CD3.\n".format(total_resource)) + if importCommands != "": + init_commands = f'\n######### Writing import for Network Sources #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands) diff --git a/cd3_automation_toolkit/Identity/Users/create_terraform_users.py b/cd3_automation_toolkit/Identity/Users/create_terraform_users.py index 9e98e79e6..51ecf2305 100644 --- a/cd3_automation_toolkit/Identity/Users/create_terraform_users.py +++ b/cd3_automation_toolkit/Identity/Users/create_terraform_users.py @@ -6,6 +6,7 @@ # # Author: Gaurav Goyal # Oracle Consulting +# Modified by: Ranjini Rajendran # import os from pathlib import Path @@ -32,6 +33,8 @@ def create_terraform_users(inputfile, outdir, service_dir, prefix, ct): file_loader = FileSystemLoader(f'{Path(__file__).parent}/templates') env = Environment(loader=file_loader, keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) users_template = env.get_template('users-template') + identity_domain_users_template = env.get_template('identity-domain-users-template') + selected_template = identity_domain_users_template if ct.identity_domain_enabled else users_template # Read cd3 using pandas dataframe df, col_headers = commonTools.read_cd3(filename, sheetName) @@ -74,11 +77,37 @@ def create_terraform_users(inputfile, outdir, service_dir, prefix, ct): print("\nThe values for Region and Name cannot be left empty. Please enter a value and try again !!") exit(1) + # Initialize domain variable + domain = str(df.loc[i, 'Domain Name']).strip() + compartment_id = "" + if not ct.identity_domain_enabled: + domain='' + + if ct.identity_domain_enabled and domain.lower() == 'nan': + domain = 'DEFAULT' + compartment_id = 'root' + if ct.identity_domain_enabled and domain.lower() != 'nan': + domain = str(domain).strip() + split_domain = domain.split('@', 1) + if len(split_domain) == 2: + compartmentVarName, domain = split_domain + if compartmentVarName.lower() == 'root' or compartmentVarName == '': + compartment_id = 'root' + else: + if compartmentVarName.startswith('root::'): + compartmentVarName = compartmentVarName[len('root::'):] + compartment_id = compartmentVarName.strip() + compartment_id = commonTools.check_tf_variable(compartment_id) + compartment_id = str(compartment_id) + if domain.lower() == 'default': + domain = 'DEFAULT' + else: + domain = domain + compartment_id = 'root' for columnname in dfcolumns: - # Column value - if 'description' in columnname.lower(): + if 'Description' in columnname.lower(): columnvalue = str(df[columnname][i]) tempdict = {'description': columnvalue} else: @@ -91,74 +120,58 @@ def create_terraform_users(inputfile, outdir, service_dir, prefix, ct): if columnname.lower() in commonTools.tagColumns: tempdict = commonTools.split_tag_values(columnname, columnvalue, tempdict) - if columnname == 'User Name': columnvalue = columnvalue.strip() - user_tf_name = commonTools.check_tf_variable(columnvalue) - tempdict = {'user_tf_name': user_tf_name} - tempdict['name'] = columnvalue + user_tf_name = f"{domain}_{commonTools.check_tf_variable(columnvalue)}" + if user_tf_name.startswith('_'): + user_tf_name = user_tf_name[1:] + tempdict = {'user_tf_name': user_tf_name, 'domain': domain, 'compartment_id':compartment_id} - # If description field is empty; put name as description - if columnname == 'User Description': - columnvalue = commonTools.check_columnvalue(columnvalue) - tempdict = {'description': columnvalue} + if columnname == 'Family Name': + columnvalue = columnvalue.strip() + tempdict = {'last_name': columnvalue} - if columnname == 'User email': - columnvalue = commonTools.check_columnvalue(columnvalue) - tempdict = {'email': columnvalue} + if columnname == 'User Email': + email = commonTools.check_columnvalue(columnvalue) + tempdict['email'] = email - if columnname == 'Group Names': + if columnname == 'Enable Capabilities': if columnvalue != '' and columnvalue.strip().lower() != 'nan': - group_str = "" - Groups = columnvalue.split(",") - k = 0 - while k < len(Groups): - if Groups[k].strip()=="": - k += 1 - continue - if "ocid" in Groups[k].strip(): - group = "\"" + Groups[k].strip() + "\"" - else: - group = "\"" + Groups[k].strip() + "\"" - - group_str = group_str + str(group) - if (k != len(Groups) - 1): - group_str = group_str + "," - k += 1 - tempdict = {'groups_names': group_str} + capabilities = [x.strip() for x in columnvalue.split(',')] + tempdict = {'enabled_capabilities': capabilities} tempStr.update(tempdict) - continue + # Process Defined and Freeform Tags based on columnname and 'Domain Name' + if columnname.lower() in commonTools.tagColumns: + if not ct.identity_domain_enabled: + # Process tags using the existing code + tempdict = commonTools.split_tag_values(columnname, columnvalue, tempdict) + else: + # When 'Domain Name' is not 'nan', process 'Defined Tags' differently + if columnname == 'Defined Tags': + defined_tags = columnvalue.strip() + tag_strings = defined_tags.split(';') + + defined_tags_list = [] + for tag_string in tag_strings: + parts = tag_string.split('=') + if len(parts) == 2: + namespace_key = parts[0] + value = parts[1] + namespace, key = namespace_key.split('.') + tempdict = {'namespace': namespace, 'key': key, 'value': value} + defined_tags_list.append(tempdict) - if columnname == 'Disable Capabilities': - if columnvalue != '' and columnvalue.strip().lower() != 'nan': - capability_str = "" - capabilities = columnvalue.split(",") - k = 0 - while k < len(capabilities): - if capabilities[k].strip()=="": - k += 1 - continue - capability = "\"" + capabilities[k].strip() + "\"" - capability_str = capability_str + str(capability) - if (k != len(capabilities) - 1): - capability_str = capability_str + "," - k += 1 - tempdict = {'capabilities_to_disable': capability_str} - tempStr.update(tempdict) - continue # Check for boolean/null in column values columnvalue = commonTools.check_columnvalue(columnvalue) columnname = commonTools.check_column_headers(columnname) tempStr[columnname] = str(columnvalue).strip() - - tempStr.update(tempdict) # Write all info to TF string - tfStr[region]= tfStr[region][:-1] + users_template.render(tempStr) + tfStr[region]= tfStr[region][:-1] + selected_template.render(tempStr) # Write TF string to the file in respective region directory reg=ct.home_region diff --git a/cd3_automation_toolkit/Identity/Users/export_users_nonGreenField.py b/cd3_automation_toolkit/Identity/Users/export_users_nonGreenField.py index 81d5ec034..16645fc7c 100644 --- a/cd3_automation_toolkit/Identity/Users/export_users_nonGreenField.py +++ b/cd3_automation_toolkit/Identity/Users/export_users_nonGreenField.py @@ -6,170 +6,195 @@ # Author: Gaurav # Oracle Consulting -# +#Modified By: Ranjini Rajendran import sys import oci from oci.identity import IdentityClient import os -sys.path.append(os.getcwd()+"/..") +import subprocess as sp + +sys.path.append(os.getcwd() + "/..") from commonTools import * -# Execution of the code begins here -def export_users(inputfile, outdir, service_dir, config, signer, ct): +def append_user_info(values_for_column_users, ct, user_info, username, family_name, description, email, domain_key, user_defined_tags): + capabilities = [] + if hasattr(user_info, 'urn_ietf_params_scim_schemas_oracle_idcs_extension_capabilities_user'): + cap_ext = user_info.urn_ietf_params_scim_schemas_oracle_idcs_extension_capabilities_user + elif hasattr(user_info, 'capabilities'): + cap_ext = user_info.capabilities + else: + cap_ext = None + + if cap_ext: + if cap_ext.can_use_api_keys: + capabilities.append("api_keys") + if cap_ext.can_use_auth_tokens: + capabilities.append("auth_tokens") + if cap_ext.can_use_console_password: + capabilities.append("console_password") + if cap_ext.can_use_customer_secret_keys: + capabilities.append("customer_secret_keys") + if cap_ext.can_use_db_credentials: + capabilities.append("db_credentials") + if cap_ext.can_use_o_auth2_client_credentials: + capabilities.append("oauth2client_credentials") + if cap_ext.can_use_smtp_credentials: + capabilities.append("smtp_credentials") + + for col_header in values_for_column_users.keys(): + if col_header == "Region": + values_for_column_users[col_header].append(ct.home_region.capitalize()) + elif col_header == "User Name": + values_for_column_users[col_header].append(username) + elif col_header == "Family Name": + values_for_column_users[col_header].append(family_name) + elif col_header == "Description": + values_for_column_users[col_header].append(description) + elif col_header == "User Email": + values_for_column_users[col_header].append(email) + elif col_header == "Domain Name": + values_for_column_users[col_header].append(domain_key) + elif col_header == "Defined Tags" and user_defined_tags: + values_for_column_users[col_header].append(str(user_defined_tags)) + elif col_header == "Enable Capabilities": + values_for_column_users[col_header].append(",".join(capabilities)) + +# Execution start here +def export_users(inputfile, outdir, service_dir, config, signer, ct,export_domains={}): global values_for_column_comps global values_for_column_groups global values_for_column_policies global sheet_dict_comps global sheet_dict_groups global sheet_dict_policies - global cd3file + global cd3file,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile - if('.xls' not in cd3file): + if '.xls' not in cd3file: print("\nAcceptable cd3 format: .xlsx") exit() - - importCommands={} - + importCommands = "" sheetName_users = "Users" + count_u = 0 # Read CD3 Identity Sheets df, values_for_column_users = commonTools.read_cd3(cd3file, sheetName_users) - print("\nCD3 excel file should not be opened during export process!!!") print("Tab - Users would be overwritten during export process!!!\n") - # Create backup - resource = 'tf_import_users' - file_name='tf_import_commands_users_nonGF.sh' - script_file = f'{outdir}/{ct.home_region}/{service_dir}/'+file_name - if(os.path.exists(script_file)): - commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir,resource,file_name) - importCommands[ct.home_region] = open(script_file, "w") - importCommands[ct.home_region].write("#!/bin/bash") - importCommands[ct.home_region].write("\n") - importCommands[ct.home_region].write("terraform init") - config.__setitem__("region", ct.region_dict[ct.home_region]) + state = {'path': f'{outdir}/{ct.home_region}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass idc=IdentityClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) - #retrieve group information..this is required to get group name for user-groupmembership - groups = oci.pagination.list_call_get_all_results(idc.list_groups, compartment_id=config['tenancy']) - dyngroups = oci.pagination.list_call_get_all_results(idc.list_dynamic_groups, compartment_id=config['tenancy']) - index = 0 - groupsDict = {} - - for group in groups.data: - grp_info = group - if (grp_info.lifecycle_state == "ACTIVE"): - groupsDict[grp_info.id] = grp_info.name - - for group in dyngroups.data: - grp_info = group - if (grp_info.lifecycle_state == "ACTIVE"): - groupsDict[grp_info.id] = grp_info.name + # Create backup + resource = 'import_' + sheetName_users.lower() + file_name = 'import_commands_' + sheetName_users.lower() + ".sh" + script_file = f'{outdir}/{ct.home_region}/{service_dir}/' + file_name + if (os.path.exists(script_file)): + commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, resource, file_name) - # Fetch Users print("\nFetching Users...") - importCommands[ct.home_region].write("\n######### Writing import for Users #########\n") - users = oci.pagination.list_call_get_all_results(idc.list_users, compartment_id=config['tenancy']) - - index = 0 - for user in users.data: - user_info = user - if (user_info.identity_provider_id != None): - continue - if (user_info.lifecycle_state == "ACTIVE"): - username = user_info.name - tf_name = commonTools.check_tf_variable(username) - importCommands[ct.home_region].write("\nterraform import \"module.iam-users[\\\"" + str( - tf_name) + "\\\"].oci_identity_user.user\" " + user_info.id) - user_group_memberships = None - user_group_memberships = idc.list_user_group_memberships(user_id= user_info.id ,compartment_id=config['tenancy']) - - index = index + 1 + if ct.identity_domain_enabled: + for domain_key, idcs_endpoint in export_domains.items(): + domain_name = domain_key.split("@")[1] + + # retrieve group information. This is required to get group name for user-group membership + domain_client = oci.identity_domains.IdentityDomainsClient(config, idcs_endpoint) + users = domain_client.list_users() + index = 0 + + for user in users.data.resources: + defined_tags_info = user.urn_ietf_params_scim_schemas_oracle_idcs_extension_oci_tags + user_defined_tags = [] + + if defined_tags_info is not None: + defined_tags = defined_tags_info.defined_tags + for tag in defined_tags: + namespace = tag.namespace + key = tag.key + value = tag.value + if namespace is not None and key is not None and value is not None: + user_defined_tags.append(f"{namespace}.{key}={value}") + + user_defined_tags = ";".join(user_defined_tags) + + user_info = user + if user_info.urn_ietf_params_scim_schemas_oracle_idcs_extension_user_user.is_federated_user != "True" and user_info.active !="False": + username = user_info.user_name + family_name = user_info.name.family_name + description = user_info.description + email = None + + for email_info in user_info.emails: + if email_info.primary: + email = email_info.value + break + + tf_name = commonTools.check_tf_variable(username) + if domain_name == "Default" or domain_name == "default": + domain_name = "DEFAULT" + tf_name = domain_name + "_" + tf_name + import_user_id = "idcsEndpoint/" + str(idcs_endpoint) + "/users/" + str(user_info.id) + tf_resource = f'module.users[\\"{str(tf_name)}\\"].oci_identity_domains_user.user' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" "{import_user_id}"' + count_u += 1 + append_user_info(values_for_column_users, ct, user_info, username, family_name, description, email, domain_key,user_defined_tags) + + else: + users = oci.pagination.list_call_get_all_results(idc.list_users, compartment_id=config['tenancy']).data + index=0 + for user in users: + user_info = user + if (user_info.identity_provider_id != None): + continue + if (user_info.lifecycle_state == "ACTIVE"): + username = user_info.name + description = user_info.description + email = user_info.email + tf_name = commonTools.check_tf_variable(username) + import_user_id = user_info.id + tf_resource = f'module.iam-users[\\"{str(tf_name)}\\"].oci_identity_user.user' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" "{import_user_id}"' + + # Pass empty strings for domain_name and domain_key + count_u += 1 + append_user_info(values_for_column_users, ct, user_info, username, "", description, email, "", []) + + if user.capabilities: + tf_resource = f'module.iam-users[\\"{str(tf_name)}\\"].oci_identity_user_capabilities_management.user_capabilities_management[0]' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" capabilities/{user_info.id}' + for col_header in values_for_column_users.keys(): - if (col_header == "Region"): - values_for_column_users[col_header].append(ct.home_region.capitalize()) - elif (col_header == "User Name"): - values_for_column_users[col_header].append(username) - elif (col_header == "User email"): - values_for_column_users[col_header].append(user_info.email) - elif (col_header == "User Description"): - values_for_column_users[col_header].append(user_info.description) - elif (col_header == "Disable Capabilities"): - #check if any of the capability is set to false - # generate comma separated list of capability which are disabled for user - capabilities = "" - if(not user_info.capabilities.can_use_api_keys): - if(capabilities == ""): - capabilities = "can_use_api_keys" - else: - capabilities = capabilities + "," + "can_use_api_keys" - if(not user_info.capabilities.can_use_auth_tokens): - if (capabilities == ""): - capabilities = "can_use_auth_tokens" - else: - capabilities = capabilities + "," + "can_use_auth_tokens" - if (not user_info.capabilities.can_use_console_password): - if (capabilities == ""): - capabilities = "can_use_console_password" - else: - capabilities = capabilities + "," + "can_use_console_password" - if (not user_info.capabilities.can_use_customer_secret_keys): - if(capabilities == ""): - capabilities = "can_use_customer_secret_keys" - else: - capabilities = capabilities + "," + "can_use_customer_secret_keys" - if (not user_info.capabilities.can_use_db_credentials): - if (capabilities == ""): - capabilities = "can_use_db_credentials" - else: - capabilities = capabilities + "," + "can_use_db_credentials" - if (not user_info.capabilities.can_use_o_auth2_client_credentials): - if (capabilities == ""): - capabilities = "can_use_o_auth2_client_credentials" - else: - capabilities = capabilities + "," + "can_use_o_auth2_client_credentials" - if (not user_info.capabilities.can_use_smtp_credentials): - if (capabilities == ""): - capabilities = "can_use_smtp_credentials" - else: - capabilities = capabilities + "," + "can_use_smtp_credentials" - values_for_column_users[col_header].append(capabilities) - if(not capabilities == ""): - importCommands[ct.home_region].write("\nterraform import \"module.iam-users[\\\"" + str( - tf_name) + "\\\"].oci_identity_user_capabilities_management.user_capabilities_management[0]\" capabilities/" + user_info.id) - - elif col_header.lower() in commonTools.tagColumns: - values_for_column_users = commonTools.export_tags(user_info, col_header, values_for_column_users) - elif (col_header == "Group Names"): - if(user_group_memberships.data != []): - groups_name = "" - count = 0 - for membership in user_group_memberships.data: - if (count == 0): - groups_name = groupsDict[membership.group_id] - else: - groups_name = groups_name + "," + groupsDict[membership.group_id] - - - importCommands[ct.home_region].write("\nterraform import \"module.iam-users[\\\"" + str( - tf_name) + "\\\"].oci_identity_user_group_membership.user_group_membership["+ str(count)+"]\" " + membership.id) - - count = count + 1 - - values_for_column_users[col_header].append(groups_name) - - else: - values_for_column_users[col_header].append("") + if col_header.lower() in commonTools.tagColumns: + values_for_column_users = commonTools.export_tags(user, col_header, values_for_column_users) + + max_list_length = max(len(lst) for lst in values_for_column_users.values()) + for col_name in values_for_column_users: + lst = values_for_column_users[col_name] + lst.extend([""] * (max_list_length - len(lst))) commonTools.write_to_cd3(values_for_column_users, cd3file, sheetName_users) - print("{0} Users exported into CD3.\n".format(len(values_for_column_users["Region"]))) + print("{0} Users exported into CD3.\n".format(count_u)) + + init_commands = f'\n######### Writing import for Identity Users #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands) - with open(script_file, 'a') as importCommands[ct.home_region]: - importCommands[ct.home_region].write('\n\nterraform plan\n') diff --git a/cd3_automation_toolkit/Identity/Users/templates/identity-domain-users-template b/cd3_automation_toolkit/Identity/Users/templates/identity-domain-users-template new file mode 100644 index 000000000..28904dd15 --- /dev/null +++ b/cd3_automation_toolkit/Identity/Users/templates/identity-domain-users-template @@ -0,0 +1,57 @@ +{% if count == 0 %} +// Copyright (c) 2021, 2022, Oracle and/or its affiliates. + +############################ +# Identity +# Users - tfvars +# Sample import command for users: +# terraform import "module.iam-users[\"<>\"].oci_identity_user.user" <> +############################ + +identity_domain_users = { +{% endif %} + {{ user_tf_name }} = { + family_name = "{{last_name}}" + idcs_endpoint = "{{ domain }}" + description = "{{ description }}" + user_name = "{{user_name}}" + compartment_id = "{{compartment_id}}" + email = "{{email}}" + {% if groups_names %} + groups = [{{ groups_names }}] + {% endif %} + {% if enabled_capabilities %} + enabled_capabilities = {{ enabled_capabilities | tojson }} + {% endif %} + + + {# ##Do not modify below this line## #} + {# #} + {# ###Section for adding Defined and Freeform Tags### #} + {% if defined_tags and defined_tags != 'nan' and defined_tags != '' and defined_tags != [['nan']] %} + defined_tags = [ + {% for tag_string in defined_tags.split(';') %} + {% set parts = tag_string.split('=') %} + {% if parts|length == 2 %} + { + key = "{{ parts[0].split('.')[1] }}" + namespace = "{{ parts[0].split('.')[0] }}" + value = "{{ parts[1] }}" + }{% if not loop.last %}, + {% endif %} + {% endif %} + {% endfor %} + ] + {% endif %} + + {% if freeform_tags and freeform_tags != 'nan' and freeform_tags != '' and freeform_tags != [['nan']] %} + {% if freeform_tags[0] %} + freeform_tags = { + key = "{{ key }}" + value = "{{ value }}" + } + {% endif %} + {% endif %} + {# ###Section for adding Defined and Freeform Tags ends here### #} + }, + } \ No newline at end of file diff --git a/cd3_automation_toolkit/Identity/Users/templates/users-template b/cd3_automation_toolkit/Identity/Users/templates/users-template index f19fbb616..3e994b52a 100644 --- a/cd3_automation_toolkit/Identity/Users/templates/users-template +++ b/cd3_automation_toolkit/Identity/Users/templates/users-template @@ -11,14 +11,11 @@ users = { {% endif %} {{ user_tf_name }} = { - name = "{{ name }}" + name = "{{ user_name }}" description = "{{ description }}" email = "{{ email }}" - {% if groups_names %} - group_membership = [{{ groups_names }}] - {% endif %} - {% if capabilities_to_disable %} - disable_capabilities = [{{ capabilities_to_disable }}] + {% if enabled_capabilities %} + enabled_capabilities = {{ enabled_capabilities | tojson }} {% endif %} {# ##Do not modify below this line## #} diff --git a/cd3_automation_toolkit/Identity/export_identity_nonGreenField.py b/cd3_automation_toolkit/Identity/export_identity_nonGreenField.py index 31b261a16..1864e85f0 100644 --- a/cd3_automation_toolkit/Identity/export_identity_nonGreenField.py +++ b/cd3_automation_toolkit/Identity/export_identity_nonGreenField.py @@ -14,6 +14,7 @@ import oci from oci.identity import IdentityClient import os +import subprocess as sp sys.path.append(os.getcwd()+"/..") from commonTools import * @@ -26,7 +27,9 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, global sheet_dict_groups global sheet_dict_policies global cd3file - global importCommands + global importCommands,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -35,8 +38,15 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, print("\nAcceptable cd3 format: .xlsx") exit() - importCommands={} config.__setitem__("region", ct.region_dict[ct.home_region]) + state = {'path': f'{outdir}/{ct.home_region}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass idc = IdentityClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) if resource == "Compartments": @@ -48,14 +58,11 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, sheet_dict_comps = ct.sheet_dict[sheetName_comps] print("Tabs- Compartments would be overwritten during export process!!!\n") # Create backup - resource = 'tf_import_' + sheetName_comps.lower() - file_name = 'tf_import_commands_' + sheetName_comps.lower() + '_nonGF.sh' + resource = 'import_' + sheetName_comps.lower() + file_name = 'import_commands_' + sheetName_comps.lower()+".sh" script_file = f'{outdir}/{ct.home_region}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, resource, file_name) - importCommands += "#!/bin/bash\n" - importCommands += "terraform init\n" - importCommands += "\n######### Writing import for Compartments #########\n\n" # Fetch Compartments print("\nFetching Compartments...") @@ -68,15 +75,19 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, sub_comp_l4_index = 0 sub_comp_l5_index = 0 + compartments={} + if ct.ntk_compartment_ids: compartments = ct.ntk_compartment_ids.items() else: ct.get_network_compartment_ids(config['tenancy'], "root", config, signer) compartments = ct.ntk_compartment_ids.items() + total_c = 0 for c_name, c_id in compartments: + total_c = total_c+1 c_details = idc.get_compartment(c_id).data - + tf_resource = "" # write child comps info if ("::" in c_name): c_names = c_name.rsplit("::", 1) @@ -84,29 +95,19 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, comp_parent_name = c_names[0] tf_name = commonTools.check_tf_variable(c_name) if len(c_name.split("::")) == 2: - importCommands += "\nterraform import \"module.sub-compartments-level1[\\\"" + str(tf_name - ) + "\\\"].oci_identity_compartment.compartment\" " + c_id - + tf_resource = f'module.sub-compartments-level1[\\"{tf_name}\\"].oci_identity_compartment.compartment' sub_comp_l1_index = sub_comp_l1_index + 1 - if len(c_name.split("::")) == 3: - importCommands += "\nterraform import \"module.sub-compartments-level2[\\\"" + str(tf_name - ) + "\\\"].oci_identity_compartment.compartment\" " + c_id - + elif len(c_name.split("::")) == 3: + tf_resource = f'module.sub-compartments-level2[\\"{tf_name}\\"].oci_identity_compartment.compartment' sub_comp_l2_index = sub_comp_l2_index + 1 - if len(c_name.split("::")) == 4: - importCommands += "\nterraform import \"module.sub-compartments-level3[\\\"" + str(tf_name - ) + "\\\"].oci_identity_compartment.compartment\" " + c_id - + elif len(c_name.split("::")) == 4: + tf_resource = f'module.sub-compartments-level3[\\"{tf_name}\\"].oci_identity_compartment.compartment' sub_comp_l3_index = sub_comp_l3_index + 1 - if len(c_name.split("::")) == 5: - importCommands += "\nterraform import \"module.sub-compartments-level4[\\\"" + str(tf_name - ) + "\\\"].oci_identity_compartment.compartment\" " + c_id - + elif len(c_name.split("::")) == 5: + tf_resource = f'module.sub-compartments-level4[\\"{tf_name}\\"].oci_identity_compartment.compartment' sub_comp_l4_index = sub_comp_l4_index + 1 - if len(c_name.split("::")) == 6: - importCommands += "\nterraform import \"module.sub-compartments-level5[\\\"" + str(tf_name - ) + "\\\"].oci_identity_compartment.compartment\" " + c_id - + elif len(c_name.split("::")) == 6: + tf_resource = f'module.sub-compartments-level5[\\"{tf_name}\\"].oci_identity_compartment.compartment' sub_comp_l5_index = sub_comp_l5_index + 1 # write parent comp info(at root) @@ -117,13 +118,12 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, comp_display_name = c_name comp_parent_name = "root" tf_name = commonTools.check_tf_variable(c_name) - importCommands += "\nterraform import \"module.iam-compartments[\\\"" + str( - tf_name - ) + "\\\"].oci_identity_compartment.compartment\" " + c_id - + tf_resource = f'module.iam-compartments[\\"{tf_name}\\"].oci_identity_compartment.compartment' root_index = root_index + 1 else: continue + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {c_id}' if (c_id not in comp_ocids_done): comp_ocids_done.append(c_id) for col_header in values_for_column_comps.keys(): @@ -143,12 +143,14 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, sheet_dict_comps, values_for_column_comps ) - importCommands += "\nterraform plan" + + init_commands = f'\n######### Writing import for Compartments #########\n\n#!/bin/bash\n{tf_or_tofu} init' if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' with open(script_file, 'a') as importCommandsfile: - importCommandsfile.write(importCommands) + importCommandsfile.write(init_commands + importCommands) commonTools.write_to_cd3(values_for_column_comps, cd3file, sheetName_comps) - print("{0} Compartments exported into CD3.\n".format(len(values_for_column_comps["Region"]))) + print("{0} Compartments exported into CD3.\n".format(total_c)) elif resource == "IAM Policies": importCommands = "" @@ -157,18 +159,16 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, sheet_dict_policies = ct.sheet_dict[sheetName_policies] print("Tabs- Policies would be overwritten during export process!!!\n") # Create backup - resource = 'tf_import_' + sheetName_policies.lower() - file_name = 'tf_import_commands_' + sheetName_policies.lower() + '_nonGF.sh' + resource = 'import_' + sheetName_policies.lower() + file_name = 'import_commands_' + sheetName_policies.lower() + '.sh' script_file = f'{outdir}/{ct.home_region}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, resource, file_name) - importCommands += "#!/bin/bash\n" - importCommands += "terraform init\n" - importCommands += "\n######### Writing import for Policies #########\n\n" # Fetch Policies print("\nFetching Policies...") comp_ocid_done = [] index = 0 + total_p = 0 for ntk_compartment_name in export_compartments: if ct.ntk_compartment_ids[ntk_compartment_name] not in comp_ocid_done: comp_ocid_done.append(ct.ntk_compartment_ids[ntk_compartment_name]) @@ -177,6 +177,7 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, ntk_compartment_name] ) for policy in policies.data: + total_p = total_p+1 policy_name = policy.name policy_comp_id = policy.compartment_id if (policy_comp_id == config['tenancy']): @@ -200,8 +201,9 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, tf_name = policy_name tf_name = commonTools.check_tf_variable(tf_name) - importCommands += "\nterraform import \"module.iam-policies[\\\"" + str(tf_name - ) + "\\\"].oci_identity_policy.policy\" " + policy.id + tf_resource = f'module.iam-policies[\\"{str(tf_name)}\\"].oci_identity_policy.policy' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {policy.id}' index = index + 1 count = 1 @@ -250,12 +252,13 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, values_for_column_policies[col_header].append("") count = count + 1 - importCommands += "\nterraform plan" + init_commands = f'\n######### Writing import for Policies #########\n\n#!/bin/bash\n{tf_or_tofu} init' if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' with open(script_file, 'a') as importCommandsfile: - importCommandsfile.write(importCommands) + importCommandsfile.write(init_commands + importCommands) commonTools.write_to_cd3(values_for_column_policies, cd3file, sheetName_policies) - print("{0} Policies exported into CD3.\n".format(len(values_for_column_policies["Region"]))) + print("{0} Policies exported into CD3.\n".format(total_p)) elif resource == "IAM Groups": importCommands = "" @@ -264,63 +267,131 @@ def export_identity(inputfile, outdir, service_dir,resource, config, signer, ct, sheet_dict_groups = ct.sheet_dict[sheetName_groups] print("Tabs- Groups would be overwritten during export process!!!\n") - config.__setitem__("region", ct.region_dict[ct.home_region]) - idc = IdentityClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) - # Create backup - resource = 'tf_import_'+ sheetName_groups.lower() - file_name = 'tf_import_commands_' + sheetName_groups.lower() + '_nonGF.sh' + resource = 'import_'+ sheetName_groups.lower() + file_name = 'import_commands_' + sheetName_groups.lower() + '.sh' script_file = f'{outdir}/{ct.home_region}/{service_dir}/' + file_name if os.path.exists(script_file): commonTools.backup_file(outdir + "/" + ct.home_region + "/" + service_dir, resource, file_name) - importCommands += "#!/bin/bash\n" - importCommands += "terraform init\n" - importCommands += "\n######### Writing import for Groups #########\n\n" # Fetch Groups print("\nFetching Groups...") - - groups = oci.pagination.list_call_get_all_results(idc.list_groups,compartment_id=config['tenancy']) - dyngroups=oci.pagination.list_call_get_all_results(idc.list_dynamic_groups,compartment_id=config['tenancy']) - index = 0 - groupsDict = {} - - for group in groups.data: - grp_info=group - if(grp_info.lifecycle_state == "ACTIVE"): - groupsDict[grp_info.id] = grp_info.name - grp_display_name=grp_info.name - tf_name=commonTools.check_tf_variable(grp_display_name) - importCommands += "\nterraform import \"module.iam-groups[\\\""+str(tf_name)+"\\\"].oci_identity_group.group[0]\" "+grp_info.id - index = index + 1 - for col_header in values_for_column_groups.keys(): - if (col_header == "Region"): - values_for_column_groups[col_header].append(ct.home_region.capitalize()) - elif col_header.lower() in commonTools.tagColumns: - values_for_column_groups = commonTools.export_tags(grp_info, col_header, values_for_column_groups) - else: - oci_objs=[grp_info] - values_for_column_groups = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_groups,values_for_column_groups) - - for group in dyngroups.data: - grp_info=group - if(grp_info.lifecycle_state == "ACTIVE"): - groupsDict[grp_info.id] = grp_info.name - grp_display_name=grp_info.name - tf_name=commonTools.check_tf_variable(grp_display_name) - importCommands += "\nterraform import \"module.iam-groups[\\\""+str(tf_name)+"\\\"].oci_identity_dynamic_group.dynamic_group[0]\" "+grp_info.id - index = index + 1 - for col_header in values_for_column_groups.keys(): - if (col_header == "Region"): - values_for_column_groups[col_header].append(ct.home_region.capitalize()) - elif col_header.lower() in commonTools.tagColumns: - values_for_column_groups = commonTools.export_tags(grp_info, col_header, values_for_column_groups) - else: - oci_objs=[grp_info] - values_for_column_groups = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_groups,values_for_column_groups) - - importCommands += "\nterraform plan" + total_g = 0 + def process_group(grp_info, members_list,membership_id_list, domain_name, is_dynamic=False, importCommands="", values_for_column_groups={}, non_domain=False): + group_description = "" + if non_domain: + group_name = grp_info.name + group_description = grp_info.description + tf_name = commonTools.check_tf_variable(group_name) + resource_id = grp_info.id + if is_dynamic: + tf_resource = f'module.iam-groups[\\"{str(tf_name)}\\"].oci_identity_dynamic_group.dynamic_group[0]' + else: + tf_resource = f'module.iam-groups[\\"{str(tf_name)}\\"].oci_identity_group.group[0]' + count = 0 + for id in membership_id_list: + user_name = members_list[membership_id_list.index(id)] + membership_resource = f'module.iam-groups[\\"{str(tf_name)}\\"].oci_identity_user_group_membership.user_group_membership[\\"{user_name}\\"]' + if membership_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{membership_resource}" {id}' + count = count + 1 + else: + group_name = grp_info.display_name + tf_name = commonTools.check_tf_variable(group_name) + domain_name = domain_name.upper() if domain_name.lower() == "default" else domain_name + tf_name = domain_name + "_" + tf_name + if is_dynamic: + group_description = grp_info.description + resource_id = f"idcsEndpoint/{idcs_endpoint}/dynamicResourceGroups/{grp_info.id}" + tf_resource = f'module.groups[\\"{str(tf_name)}\\"].oci_identity_domains_dynamic_resource_group.dynamic_group[0]' + else: + if hasattr(grp_info, 'urn_ietf_params_scim_schemas_oracle_idcs_extension_group_group'): + group_description = getattr(grp_info.urn_ietf_params_scim_schemas_oracle_idcs_extension_group_group, + 'description', "") + resource_id = f"idcsEndpoint/{idcs_endpoint}/groups/{grp_info.id}" + tf_resource = f'module.groups[\\"{str(tf_name)}\\"].oci_identity_domains_group.group[0]' + + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" "{resource_id}"' + + for col_header in values_for_column_groups.keys(): + if col_header == "Region": + values_for_column_groups[col_header].append(ct.home_region.capitalize()) + elif col_header == "Name": + values_for_column_groups[col_header].append(group_name) + elif col_header == "Members": + members_string = ','.join(members_list) + values_for_column_groups[col_header].append(members_string) + elif col_header == "Description": + values_for_column_groups[col_header].append(group_description) + elif col_header == "Domain Name" and not non_domain: + values_for_column_groups[col_header].append(domain_key) + elif col_header == "Matching Rule": + values_for_column_groups[col_header].append(grp_info.matching_rule if is_dynamic else "") + elif col_header == "Defined Tags" and not non_domain: + defined_tags_info = grp_info.urn_ietf_params_scim_schemas_oracle_idcs_extension_oci_tags + grp_defined_tags = [] + if defined_tags_info is not None: + defined_tags = defined_tags_info.defined_tags + for tag in defined_tags: + namespace = tag.namespace + key = tag.key + value = tag.value + if namespace is not None and key is not None and value is not None: + grp_defined_tags.append(f"{namespace}.{key}={value}") + grp_defined_tags = ";".join(grp_defined_tags) + values_for_column_groups[col_header].append(grp_defined_tags if grp_defined_tags else "") + elif col_header == "Defined Tags" and non_domain: + values_for_column_groups = commonTools.export_tags(grp_info, col_header, values_for_column_groups) + else: + oci_objs = [grp_info] + values_for_column_groups = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_groups, values_for_column_groups) + + return importCommands, values_for_column_groups + + if ct.identity_domain_enabled: + for domain_key, idcs_endpoint in export_domains.items(): + domain_name = domain_key.split("@")[1] + domain_client = oci.identity_domains.IdentityDomainsClient(config, idcs_endpoint) + groups = domain_client.list_groups(attributes=['members'], attribute_sets=['all']) + dyngroups = domain_client.list_dynamic_resource_groups(attributes=['matching_rule'], attribute_sets=['all']) + + for grp_info in groups.data.resources: + if grp_info.display_name in ["Domain_Administrators", "All Domain Users", "Administrators"]: + continue + total_g +=1 + members_list = [section.name for section in grp_info.members if section and section.name] if grp_info.members else [] + importCommands, values_for_column_groups = process_group(grp_info, members_list,[], domain_name, is_dynamic=False, importCommands=importCommands, values_for_column_groups=values_for_column_groups) + + for dg in dyngroups.data.resources: + total_g += 1 + importCommands, values_for_column_groups = process_group(dg, [],[], domain_name, is_dynamic=True, importCommands=importCommands, values_for_column_groups=values_for_column_groups) + else: + groups = oci.pagination.list_call_get_all_results(idc.list_groups, compartment_id=config['tenancy']) + dyngroups = oci.pagination.list_call_get_all_results(idc.list_dynamic_groups, compartment_id=config['tenancy']) + + for group in groups.data: + total_g += 1 + if group.lifecycle_state == "ACTIVE": + group_membership = oci.pagination.list_call_get_all_results(idc.list_user_group_memberships, compartment_id=config['tenancy'], group_id=group.id) + members_list = [str(idc.get_user(membership.user_id).data.name).strip() for membership in group_membership.data] + membership_id_list = [str(membership.id) for membership in group_membership.data] + importCommands, values_for_column_groups = process_group(group, members_list,membership_id_list, domain_name="", is_dynamic=False, importCommands=importCommands, values_for_column_groups=values_for_column_groups, non_domain=True) + + for group in dyngroups.data: + total_g += 1 + if group.lifecycle_state == "ACTIVE": + importCommands, values_for_column_groups = process_group(group, [],[], domain_name="", is_dynamic=True, importCommands=importCommands, values_for_column_groups=values_for_column_groups, non_domain=True) + + max_list_length = max(len(lst) for lst in values_for_column_groups.values()) + for col_name in values_for_column_groups: + lst = values_for_column_groups[col_name] + lst.extend([""] * (max_list_length - len(lst))) + + commonTools.write_to_cd3(values_for_column_groups, cd3file, sheetName_groups) + + init_commands = f'\n######### Writing import for Identity Groups #########\n\n#!/bin/bash\n{tf_or_tofu} init' if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' with open(script_file, 'a') as importCommandsfile: - importCommandsfile.write(importCommands) - commonTools.write_to_cd3(values_for_column_groups,cd3file,sheetName_groups) - print("{0} Groups exported into CD3.\n".format(len(values_for_column_groups["Region"]))) + importCommandsfile.write(init_commands + importCommands) + print("{0} rows exported into CD3 for Groups and Dynamic Groups.\n".format(total_g)) diff --git a/cd3_automation_toolkit/ManagementServices/EventsAndNotifications/export_events_notifications_nonGreenField.py b/cd3_automation_toolkit/ManagementServices/EventsAndNotifications/export_events_notifications_nonGreenField.py index f8ee99793..171884d33 100644 --- a/cd3_automation_toolkit/ManagementServices/EventsAndNotifications/export_events_notifications_nonGreenField.py +++ b/cd3_automation_toolkit/ManagementServices/EventsAndNotifications/export_events_notifications_nonGreenField.py @@ -10,19 +10,20 @@ import sys import oci import json +import subprocess as sp +import os from oci.ons import NotificationControlPlaneClient from oci.events import EventsClient from oci.ons import NotificationDataPlaneClient from oci.functions import FunctionsManagementClient from oci.config import DEFAULT_LOCATION -import os -sys.path.append(os.getcwd() + "/..") from commonTools import * +sys.path.append(os.getcwd() + "/..") compartment_ids={} importCommands={} -def print_notifications(values_for_column_notifications,region, ntk_compartment_name, sbpn, nftn_info, i, fun): +def print_notifications(values_for_column_notifications,region, ntk_compartment_name, sbpn, nftn_info, i, fun,state): tf_name_nftn = commonTools.check_tf_variable(str(nftn_info.name)) sbpn_name = nftn_info.name + "_" + "sub" + str(i) @@ -61,16 +62,16 @@ def print_notifications(values_for_column_notifications,region, ntk_compartment else: oci_objs = [nftn_info,sbpn] values_for_column_notifications = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_notifications,values_for_column_notifications) + tf_resource = f'module.notifications-topics[\\"{tf_name_nftn}\\"].oci_ons_notification_topic.topic' + if (i ==0 or i == 1) and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(nftn_info.topic_id)}' - if (i ==0 or i == 1): - importCommands[region.lower()].write("\nterraform import \"module.notifications-topics[\\\"" + str(tf_name_nftn) + "\\\"].oci_ons_notification_topic.topic\" " + str(nftn_info.topic_id)) + tf_resource = f'module.notifications-subscriptions[\\"{tf_name_sbpn}\\"].oci_ons_subscription.subscription' + if(i!=0) and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(sbpn.id)}' - if(i!=0): - importCommands[region.lower()].write("\nterraform import \"module.notifications-subscriptions[\\\"" + str(tf_name_sbpn) + "\\\"].oci_ons_subscription.subscription\" " + str(sbpn.id)) - - -def print_events(values_for_column_events, region, ntk_compartment_name, event, event_info, ncpc, fun): +def print_events(values_for_column_events, region, ntk_compartment_name, event, event_info, ncpc, fun,state): tf_name = commonTools.check_tf_variable(str(event.display_name)) event_name = event.display_name action_type = "" @@ -131,9 +132,9 @@ def print_events(values_for_column_events, region, ntk_compartment_name, event, if ( i > 0 and action_name != ""): events_rows(values_for_column_events, region, ntk_compartment_name, event_name, event_desc, action_type, action_is_enabled, action_description, event_prod, event_res,data, event_is_enabled, action_name, event, event_info) i = i + 1 - if ( action_name != "" ): - #importCommands[region.lower()].write("\nterraform import oci_events_rule." + tf_name + " " + str(event.id)) - importCommands[region.lower()].write("\nterraform import \"module.events[\\\"" + str(tf_name) + "\\\"].oci_events_rule.event\" " + str(event.id)) + tf_resource = f'module.events[\\"{tf_name}\\"].oci_events_rule.event' + if ( action_name != "" ) and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {event.id}' def events_rows(values_for_column_events, region, ntk_compartment_name, event_name, event_desc, action_type, action_is_enabled, action_description, event_prod, event_res,data, event_is_enabled, action_name, event, event_info): for col_header in values_for_column_events.keys(): @@ -175,7 +176,9 @@ def export_events(inputfile, outdir, service_dir, config, signer, ct,export_comp global values_for_column_notifications global sheet_dict_events global sheet_dict_notifications - global importCommands + global importCommands,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] sheetName = "Events" @@ -195,23 +198,27 @@ def export_events(inputfile, outdir, service_dir, config, signer, ct,export_comp print("Tabs- Events would be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg +"/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Events print("\nFetching Events...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Events #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass # comp_ocid_done = [] ncpc = NotificationControlPlaneClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) fun = FunctionsManagementClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -220,21 +227,29 @@ def export_events(inputfile, outdir, service_dir, config, signer, ct,export_comp for ntk_compartment_name in export_compartments: evts = oci.pagination.list_call_get_all_results(evt.list_rules, compartment_id=ct.ntk_compartment_ids[ ntk_compartment_name], lifecycle_state="ACTIVE") + for event in evts.data: event_info = evt.get_rule(event.id).data - print_events(values_for_column_events, region, ntk_compartment_name, event, event_info, ncpc, fun) + print_events(values_for_column_events, region, ntk_compartment_name, event, event_info, ncpc, fun,state) + ievts = oci.pagination.list_call_get_all_results(evt.list_rules, compartment_id=ct.ntk_compartment_ids[ ntk_compartment_name], lifecycle_state="INACTIVE") + for event in ievts.data: event_info = evt.get_rule(event.id).data - print_events(values_for_column_events, region, ntk_compartment_name, event, event_info, ncpc, fun) + print_events(values_for_column_events, region, ntk_compartment_name, event, event_info, ncpc, fun,state) commonTools.write_to_cd3(values_for_column_events, cd3file, sheetName) print("{0} Events exported into CD3.\n".format(len(values_for_column_events["Region"]))) + # writing data for reg in export_regions: - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for Events #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) # Execution for Notifications export starts here def export_notifications(inputfile, outdir, service_dir, config, signer, ct, export_compartments=[], export_regions=[]): @@ -244,7 +259,9 @@ def export_notifications(inputfile, outdir, service_dir, config, signer, ct, exp global values_for_column_notifications global sheet_dict_events global sheet_dict_notifications - global importCommands + global importCommands,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] sheetName = "Notifications" @@ -263,42 +280,48 @@ def export_notifications(inputfile, outdir, service_dir, config, signer, ct, exp print("Tabs- Notifications would be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg +"/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Notifications & Subscriptions print("\nFetching Notifications - Topics & Subscriptions...") + total_resources=0 for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Notifications #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass ncpc = NotificationControlPlaneClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) ndpc = NotificationDataPlaneClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) fun = FunctionsManagementClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() for ntk_compartment_name in export_compartments: - topics = oci.pagination.list_call_get_all_results(ncpc.list_topics,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name]) + topics = oci.pagination.list_call_get_all_results(ncpc.list_topics,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name],lifecycle_state='ACTIVE') #sbpns = oci.pagination.list_call_get_all_results(ndpc.list_subscriptions,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name]) for topic in topics.data: + total_resources+=1 #subscriptions get created in same comp as topic sbpns = oci.pagination.list_call_get_all_results(ndpc.list_subscriptions,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name],topic_id = topic.topic_id) i=0 sbpn = None for sbpn in sbpns.data: i=i+1 - print_notifications(values_for_column_notifications, region, ntk_compartment_name, sbpn,topic, i, fun) + print_notifications(values_for_column_notifications, region, ntk_compartment_name, sbpn,topic, i, fun,state) # Empty Topic - No Subscription in the same compartment as Topic's if(i==0): - print_notifications(values_for_column_notifications, region, ntk_compartment_name, sbpn, topic,i, fun) + print_notifications(values_for_column_notifications, region, ntk_compartment_name, sbpn, topic,i, fun,state) ''' @@ -319,9 +342,14 @@ def export_notifications(inputfile, outdir, service_dir, config, signer, ct, exp commonTools.write_to_cd3(values_for_column_notifications, cd3file, sheetName) - print("{0} Notifications exported into CD3.\n".format(len(values_for_column_notifications["Region"]))) - + print("{0} Notifications exported into CD3.\n".format(total_resources)) + # writing data for reg in export_regions: - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for Notifications #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/ManagementServices/Logging/templates/logging-template b/cd3_automation_toolkit/ManagementServices/Logging/templates/logging-template index 4a228677e..343cfb7f9 100644 --- a/cd3_automation_toolkit/ManagementServices/Logging/templates/logging-template +++ b/cd3_automation_toolkit/ManagementServices/Logging/templates/logging-template @@ -8,8 +8,9 @@ # Allowed Values: # compartment_id can be the ocid or the name of the compartment hierarchy delimited by double hiphens "--" # Example : compartment_id = "ocid1.compartment.oc1..aaaaaaaahwwiefb56epvdlzfic6ah6jy3xf3c" or compartment_id = "Security--Prod" where "Security" is the parent of "Prod" compartment +# terraform import "module.vcn-log-groups[\"<>\"].oci_logging_log_group.log_group" <> +# terraform import "module.vcn-logs[\"<>\"].oci_logging_log.log" logGroupId/<>/logId/<> ############################ - {{ oci_service }}_log_groups = { # Log Group map # ##Add New Log Groups for {{ region.lower() }} here## diff --git a/cd3_automation_toolkit/ManagementServices/Monitoring/export_alarms_nonGreenField.py b/cd3_automation_toolkit/ManagementServices/Monitoring/export_alarms_nonGreenField.py index e55e13044..3d8922064 100644 --- a/cd3_automation_toolkit/ManagementServices/Monitoring/export_alarms_nonGreenField.py +++ b/cd3_automation_toolkit/ManagementServices/Monitoring/export_alarms_nonGreenField.py @@ -10,6 +10,7 @@ import oci import os +import subprocess as sp from commonTools import * @@ -19,7 +20,7 @@ oci_obj_names = {} -def print_alarms(region, alarm, ncpclient,values_for_column, ntk_compartment_name,ct): +def print_alarms(region, alarm, ncpclient,values_for_column, ntk_compartment_name,ct,state): alarm_tf_name = commonTools.check_tf_variable(alarm.display_name) comp_tf_name = commonTools.check_tf_variable(ntk_compartment_name) suppression = alarm.suppression @@ -65,9 +66,9 @@ def print_alarms(region, alarm, ncpclient,values_for_column, ntk_compartment_nam oci_objs = [alarm,suppression] values_for_column = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict, values_for_column) - if(skip_row == 0): - #importCommands[region.lower()].write("\nterraform import oci_monitoring_alarm." + alarm_tf_name + " " + str(alarm.id)) - importCommands[region.lower()].write("\nterraform import \"module.alarms[\\\"" + str(comp_tf_name+"_"+alarm_tf_name) + "\\\"].oci_monitoring_alarm.alarm\" " + str(alarm.id)) + tf_resource = f'module.alarms[\\"{comp_tf_name}_{alarm_tf_name}\\"].oci_monitoring_alarm.alarm' + if skip_row == 0 and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {alarm.id}' # Execution of the code begins here def export_alarms(inputfile, outdir, service_dir, config, signer, ct, export_compartments=[],export_regions=[]): @@ -76,7 +77,9 @@ def export_alarms(inputfile, outdir, service_dir, config, signer, ct, export_com global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -97,23 +100,27 @@ def export_alarms(inputfile, outdir, service_dir, config, signer, ct, export_com print("Tabs- Alarms will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg +"/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Block Volume Details print("\nFetching details of Alarms...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Alarms #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() mclient = oci.monitoring.MonitoringClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -124,13 +131,18 @@ def export_alarms(inputfile, outdir, service_dir, config, signer, ct, export_com for alarmSummary in alarms.data: alarm=mclient.get_alarm(alarmSummary.id).data - print_alarms(region, alarm,ncpclient,values_for_column, ntk_compartment_name,ct) - - - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + print_alarms(region, alarm,ncpclient,values_for_column, ntk_compartment_name,ct,state) commonTools.write_to_cd3(values_for_column, cd3file, sheetName) print("{0} Alarms exported into CD3.\n".format(len(values_for_column["Region"]))) + # writing data + for reg in export_regions: + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for Alarms #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/ManagementServices/ServiceConnectorHub/export_sch_nonGreenField.py b/cd3_automation_toolkit/ManagementServices/ServiceConnectorHub/export_sch_nonGreenField.py index 7d4d9d8a1..9e99ba6e6 100755 --- a/cd3_automation_toolkit/ManagementServices/ServiceConnectorHub/export_sch_nonGreenField.py +++ b/cd3_automation_toolkit/ManagementServices/ServiceConnectorHub/export_sch_nonGreenField.py @@ -10,6 +10,7 @@ import oci import os +import subprocess as sp from commonTools import * importCommands = {} @@ -17,7 +18,7 @@ def get_service_connectors(config, region, SCH_LIST, sch_client, log_client, la_client, stream_client, - notification_client, func_client, ct, values_for_column, ntk_compartment_name): + notification_client, func_client, ct, values_for_column, ntk_compartment_name,state): volume_comp = "" log_source_list = [] target_la_string = "" @@ -247,10 +248,9 @@ def get_comp_details(comp_data): if sch_compartment_id == comp_id and sch_compartment_id not in comp_done_ids: volume_comp = comp_name comp_done_ids.append(sch_compartment_id) - - importCommands[region.lower()].write( - "\nterraform import \"module.service-connectors[\\\"" + sch_tf_name + "\\\"].oci_sch_service_connector.service_connector\" " + str( - sch_id)) + tf_resource = f'module.service-connectors[\\"{sch_tf_name}\\"].oci_sch_service_connector.service_connector' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(sch_id)}' for col_header in values_for_column: if col_header == 'Region': @@ -304,7 +304,9 @@ def export_service_connectors(inputfile, outdir, service_dir, config, signer, ct global importCommands global cd3file global reg - global valuesforcolumn + global valuesforcolumn,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -322,23 +324,27 @@ def export_service_connectors(inputfile, outdir, service_dir, config, signer, ct print("Tab- ServiceConnectors will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Service Connector Hub Details print("\nFetching details of Service Connectors...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Service Connectors #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() sch_client = oci.sch.ServiceConnectorClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) @@ -362,14 +368,17 @@ def export_service_connectors(inputfile, outdir, service_dir, config, signer, ct sort_by="timeCreated") get_service_connectors(config, region, SCH_LIST, sch_client, log_client, la_client, stream_client, notification_client, func_client, ct, values_for_column, - ntk_compartment_name) + ntk_compartment_name,state) commonTools.write_to_cd3(values_for_column, cd3file, sheetName) print("{0} Service Connectors exported into CD3.\n".format(len(values_for_column["Region"]))) - # writing data for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for Service Connectors #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/Network/BaseNetwork/exportNSG.py b/cd3_automation_toolkit/Network/BaseNetwork/exportNSG.py index 11d3b6c3c..434da8d0f 100644 --- a/cd3_automation_toolkit/Network/BaseNetwork/exportNSG.py +++ b/cd3_automation_toolkit/Network/BaseNetwork/exportNSG.py @@ -4,6 +4,7 @@ import oci from oci.core.virtual_network_client import VirtualNetworkClient import os +import subprocess as sp sys.path.append(os.getcwd()+"/../../..") from commonTools import * @@ -13,7 +14,7 @@ def convertNullToNothing(input): return EMPTY_STRING else: return str(input) -def print_nsgsl(values_for_column_nsgs,vnc,region, comp_name, vcn_name, nsg, nsgsl,i): +def print_nsgsl(values_for_column_nsgs,vnc,region, comp_name, vcn_name, nsg, nsgsl,i,state): tf_name = commonTools.check_tf_variable(str(vcn_name)+"_"+str(nsg.display_name)) sportmin = "" sportmax = "" @@ -133,13 +134,14 @@ def print_nsgsl(values_for_column_nsgs,vnc,region, comp_name, vcn_name, nsg, nsg values_for_column_nsgs = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_nsgs,values_for_column_nsgs) nsg_rule_tf_name = tf_name + "_security_rule" + str(i) - if tf_import_cmd: - importCommands[region.lower()].write("\nterraform import \"module.nsg-rules[\\\""+nsg_rule_tf_name+"\\\"].oci_core_network_security_group_security_rule.nsg_rule\" " + "networkSecurityGroups/" + str(nsg.id) + "/securityRules/" + str(nsgsl.id)) + tf_resource = f'module.nsg-rules[\\"{nsg_rule_tf_name}\\"].oci_core_network_security_group_security_rule.nsg_rule' + if tf_import_cmd and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" networkSecurityGroups/{str(nsg.id)}/securityRules/{str(nsgsl.id)}' # importCommands[region.lower()].write("\nterraform import oci_core_network_security_group_security_rule." + tf_name + "_security_rule" + str(i) + " " + "networkSecurityGroups/" + str(nsg.id) + "/securityRules/" + str(nsgsl.id)) -def print_nsg(values_for_column_nsgs,region, comp_name, vcn_name, nsg): +def print_nsg(values_for_column_nsgs,region, comp_name, vcn_name, nsg,state): tf_name = commonTools.check_tf_variable(str(vcn_name)+"_"+str(nsg.display_name)) for col_header in values_for_column_nsgs.keys(): @@ -154,17 +156,21 @@ def print_nsg(values_for_column_nsgs,region, comp_name, vcn_name, nsg): else: oci_objs = [nsg] values_for_column_nsgs = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_nsgs,values_for_column_nsgs) - if tf_import_cmd: - importCommands[region.lower()].write("\nterraform import \"module.nsgs[\\\"" + tf_name + "\\\"].oci_core_network_security_group.network_security_group\" " + str(nsg.id)) + tf_resource = f'module.nsgs[\\"{tf_name}\\"].oci_core_network_security_group.network_security_group' + if tf_import_cmd and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(nsg.id)}' # Execution of the code begins here def export_nsg(inputfile, outdir, service_dir,config,signer, ct, export_compartments,export_regions,_tf_import_cmd): global tf_import_cmd global values_for_column_nsgs global sheet_dict_nsgs - global importCommands + global importCommands,tf_or_tofu cd3file = inputfile + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] + if '.xls' not in cd3file: print("\nAcceptable cd3 format: .xlsx") exit() @@ -184,18 +190,22 @@ def export_nsg(inputfile, outdir, service_dir,config,signer, ct, export_compartm if tf_import_cmd: importCommands={} for reg in export_regions: - if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_network_nsg_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "tf_import_network", - "tf_import_commands_network_nsg_nonGF.sh") - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_nsg_nonGF.sh", "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - importCommands[reg].write("\n\n######### Writing import for NSG #########\n\n") + if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/import_commands_network_nsg.sh")): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "import_network", + "import_commands_network_nsg.sh") + importCommands[reg] = "" for reg in export_regions: config.__setitem__("region", commonTools().region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass vnc = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() nsglist = [""] @@ -213,28 +223,34 @@ def export_nsg(inputfile, outdir, service_dir,config,signer, ct, export_compartm lifecycle_state="AVAILABLE") for nsg in NSGs.data: - NSGSLs = vnc.list_network_security_group_security_rules(nsg.id, sort_by="TIMECREATED") + NSGSLs = oci.pagination.list_call_get_all_results(vnc.list_network_security_group_security_rules, network_security_group_id= nsg.id, sort_by="TIMECREATED") i = 1 for nsgsl in NSGSLs.data: nsglist.append(nsg.id) print_nsgsl(values_for_column_nsgs, vnc, region, ntk_compartment_name_again, - vcn_info.display_name, nsg, nsgsl, i) + vcn_info.display_name, nsg, nsgsl, i,state) i = i + 1 if (nsg.id not in nsglist): print_nsg(values_for_column_nsgs, region, ntk_compartment_name_again, vcn_info.display_name, - nsg) + nsg,state) else: tf_name = commonTools.check_tf_variable(str(vcn_info.display_name)+"_"+str(nsg.display_name)) - if tf_import_cmd: - importCommands[region.lower()].write("\nterraform import \"module.nsgs[\\\"" + tf_name + "\\\"].oci_core_network_security_group.network_security_group\" " + str( - nsg.id)) + tf_resource = f'module.nsgs[\\"{tf_name}\\"].oci_core_network_security_group.network_security_group' + if tf_import_cmd and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(nsg.id)}' + commonTools.write_to_cd3(values_for_column_nsgs, cd3file, "NSGs") print("NSGs exported to CD3\n") if tf_import_cmd: for reg in export_regions: - importCommands[reg].write('\n\nterraform plan\n') - importCommands[reg].close() + script_file = f'{outdir}/{reg}/{service_dir}/import_commands_network_nsg.sh' + init_commands = f'\n#!/bin/bash\n{tf_or_tofu} init\n######### Writing import for NSGs #########\n' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/Network/BaseNetwork/exportRoutetable.py b/cd3_automation_toolkit/Network/BaseNetwork/exportRoutetable.py index 50e1044b3..f86deef41 100644 --- a/cd3_automation_toolkit/Network/BaseNetwork/exportRoutetable.py +++ b/cd3_automation_toolkit/Network/BaseNetwork/exportRoutetable.py @@ -4,10 +4,10 @@ import oci from oci.core.virtual_network_client import VirtualNetworkClient import os +import subprocess as sp sys.path.append(os.getcwd()+"/../../..") from commonTools import * - def get_network_entity_name(config,signer,network_identity_id): vcn1 = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) if('internetgateway' in network_identity_id): @@ -111,7 +111,7 @@ def insert_values_drg(routetable,import_drg_route_distribution_name,values_for_c -def print_drg_routerules(drg_rt_info,drg_display_name,drg_route_table_name,import_drg_route_distribution_name,drg_rules,region,comp_name): +def print_drg_routerules(drg_rt_info,drg_display_name,drg_route_table_name,import_drg_route_distribution_name,drg_rules,region,comp_name,state): drg_rt_name = drg_display_name + "_" + drg_route_table_name drg_rt_tf_name = commonTools.check_tf_variable(drg_rt_name) if (not drg_rules.data): @@ -125,10 +125,12 @@ def print_drg_routerules(drg_rt_info,drg_display_name,drg_route_table_name,impor print(drg_route_table_name) else: if rule.route_type.lower()=='static': - importCommands_drg[region.lower()].write("\nterraform import \"module.drg-route-rules[\\\"" + drg_rt_tf_name+ "_route_rule" + str(i) + "\\\"].oci_core_drg_route_table_route_rule.drg_route_rule\" drgRouteTables/"+str(drg_rt_info.id)+"/routeRules/"+str(rule.id)) + tf_resource = f'module.drg-route-rules[\\"{drg_rt_tf_name}_route_rule{str(i)}\\"].oci_core_drg_route_table_route_rule.drg_route_rule' + if tf_resource not in state["resources"]: + importCommands_drg[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" drgRouteTables/{str(drg_rt_info.id)}/routeRules/{str(rule.id)}' i=i+1 -def print_routetables(routetables,region,vcn_name,comp_name,gw_route_table_ids): +def print_routetables(routetables,region,vcn_name,comp_name,gw_route_table_ids,state): for routetable in routetables.data: rules = routetable.route_rules display_name = routetable.display_name @@ -139,14 +141,17 @@ def print_routetables(routetables,region,vcn_name,comp_name,gw_route_table_ids): if routetable.id in gw_route_table_ids: if ("Default Route Table for " in dn): - importCommands[region.lower()].write("\nterraform import \"module.gateway-route-tables[\\\"" + tf_name + "\\\"].oci_core_default_route_table.default_route_table[0]\" " + str(routetable.id)) + tf_resource = f'module.gateway-route-tables[\\"{tf_name}\\"].oci_core_default_route_table.default_route_table[0]' else: - importCommands[region.lower()].write("\nterraform import \"module.gateway-route-tables[\\\"" + tf_name + "\\\"].oci_core_route_table.route_table[0]\" " + str(routetable.id)) + tf_resource = f'module.gateway-route-tables[\\"{tf_name}\\"].oci_core_route_table.route_table[0]' else: if ("Default Route Table for " in dn): - importCommands[region.lower()].write("\nterraform import \"module.route-tables[\\\"" + tf_name + "\\\"].oci_core_default_route_table.default_route_table[0]\" " + str(routetable.id)) + tf_resource = f'module.route-tables[\\"{tf_name}\\"].oci_core_default_route_table.default_route_table[0]' else: - importCommands[region.lower()].write("\nterraform import \"module.route-tables[\\\"" + tf_name + "\\\"].oci_core_route_table.route_table[0]\" " + str(routetable.id)) + tf_resource = f'module.route-tables[\\"{tf_name}\\"].oci_core_route_table.route_table[0]' + + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(routetable.id)}' if(not rules): insert_values(routetable, values_for_column, region, comp_name, vcn_name,None) @@ -170,9 +175,12 @@ def export_drg_routetable(inputfile, outdir, service_dir,config1,signer1, ct, ex global importCommands_drg global config config=config1 - global signer + global signer,tf_or_tofu signer=signer1 + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] + cd3file = inputfile if '.xls' not in cd3file: print("\nAcceptable cd3 format: .xlsx") @@ -194,17 +202,21 @@ def export_drg_routetable(inputfile, outdir, service_dir,config1,signer1, ct, ex if tf_import_cmd_drg: importCommands_drg = {} for reg in export_regions: - if (os.path.exists(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_drg_routerules_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg+ "/" + service_dir, "tf_import_network", - "tf_import_commands_network_drg_routerules_nonGF.sh") - importCommands_drg[reg] = open(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_drg_routerules_nonGF.sh", "w") - importCommands_drg[reg].write("#!/bin/bash") - importCommands_drg[reg].write("\n") - importCommands_drg[reg].write("terraform init") - importCommands_drg[reg].write("\n\n######### Writing import for DRG Route Tables #########\n\n") + if (os.path.exists(outdir + "/" + reg + "/" + service_dir+ "/import_commands_network_drg_routerules.sh")): + commonTools.backup_file(outdir + "/" + reg+ "/" + service_dir, "import_network", + "import_commands_network_drg_routerules.sh") + importCommands_drg[reg] = "" for reg in export_regions: config.__setitem__("region", commonTools().region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass vcn = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer,timeout=(30,120)) region = reg.capitalize() #comp_ocid_done = [] @@ -234,23 +246,28 @@ def export_drg_routetable(inputfile, outdir, service_dir,config1,signer1, ct, ex drg_rt_tf_name = commonTools.check_tf_variable(drg_rt_name) if tf_import_cmd_drg: if drg_route_table_name not in commonTools.drg_auto_RTs: - importCommands_drg[reg].write("\nterraform import \"module.drg-route-tables[\\\"" + drg_rt_tf_name + "\\\"].oci_core_drg_route_table.drg_route_table\" " + drg_route_table_id) - - + tf_resource = f'module.drg-route-tables[\\"{drg_rt_tf_name}\\"].oci_core_drg_route_table.drg_route_table' + if tf_resource not in state["resources"]: + importCommands_drg[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {drg_route_table_id}' #drg_rt_rules = vcn.list_drg_route_rules(drg_route_table_id) drg_rt_rules = oci.pagination.list_call_get_all_results(vcn.list_drg_route_rules, drg_route_table_id,route_type="STATIC") #drg_rt_rules = None print_drg_routerules(drg_route_table_info, drg_display_name,drg_route_table_name, import_drg_route_distribution_name, - drg_rt_rules, region, ntk_compartment_name) + drg_rt_rules, region, ntk_compartment_name,state) commonTools.write_to_cd3(values_for_column_drg, cd3file, "DRGRouteRulesinOCI") print("DRG RouteRules exported to CD3\n") if tf_import_cmd_drg: for reg in export_regions: - importCommands_drg[reg].write('\n\nterraform plan\n') - importCommands_drg[reg].close() + script_file = f'{outdir}/{reg}/{service_dir}/import_commands_network_drg_routerules.sh' + init_commands = f'\n#!/bin/bash\n{tf_or_tofu} init\n######### Writing import for DRG Route Tables #########\n' + if importCommands_drg[reg] != "": + importCommands_drg[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands_drg[reg]) + # Execution of the code begins here for route table export @@ -263,9 +280,12 @@ def export_routetable(inputfile, outdir, service_dir,config1,signer1, ct, export global values_for_vcninfo global config config=config1 - global signer + global signer,tf_or_tofu signer=signer1 + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] + cd3file = inputfile if '.xls' not in cd3file: print("\nAcceptable cd3 format: .xlsx") @@ -291,17 +311,21 @@ def export_routetable(inputfile, outdir, service_dir,config1,signer1, ct, export if tf_import_cmd: importCommands={} for reg in export_regions: - if (os.path.exists(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_routerules_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg+ "/" + service_dir, "tf_import_network", - "tf_import_commands_network_routerules_nonGF.sh") - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_routerules_nonGF.sh", "a") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - importCommands[reg].write("\n\n######### Writing import for Route Tables #########\n\n") + if (os.path.exists(outdir + "/" + reg + "/" + service_dir+ "/import_commands_network_routerules.sh")): + commonTools.backup_file(outdir + "/" + reg+ "/" + service_dir, "import_network", + "import_commands_network_routerules.sh") + importCommands[reg] = '' for reg in export_regions: config.__setitem__("region", commonTools().region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass vcn = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() #comp_ocid_done = [] @@ -336,13 +360,18 @@ def export_routetable(inputfile, outdir, service_dir,config1,signer1, ct, export for ntk_compartment_name_again in export_compartments: routetables = oci.pagination.list_call_get_all_results(vcn.list_route_tables, compartment_id=ct.ntk_compartment_ids[ntk_compartment_name_again], vcn_id=vcn_id, lifecycle_state='AVAILABLE') - print_routetables(routetables,region,vcn_name,ntk_compartment_name_again,gw_route_table_ids) + print_routetables(routetables,region,vcn_name,ntk_compartment_name_again,gw_route_table_ids,state) commonTools.write_to_cd3(values_for_column,cd3file,"RouteRulesinOCI") print("RouteRules exported to CD3\n") if tf_import_cmd: commonTools.write_to_cd3(values_for_vcninfo, cd3file, "VCN Info") for reg in export_regions: - importCommands[reg].write('\n\nterraform plan\n') - importCommands[reg].close() + script_file = f'{outdir}/{reg}/{service_dir}/import_commands_network_routerules.sh' + init_commands = f'\n#!/bin/bash\n{tf_or_tofu} init\n######### Writing import for Route Tables #########\n' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/Network/BaseNetwork/exportSeclist.py b/cd3_automation_toolkit/Network/BaseNetwork/exportSeclist.py index ad5c00708..2c56d935a 100644 --- a/cd3_automation_toolkit/Network/BaseNetwork/exportSeclist.py +++ b/cd3_automation_toolkit/Network/BaseNetwork/exportSeclist.py @@ -4,6 +4,7 @@ import oci from oci.core.virtual_network_client import VirtualNetworkClient import os +import subprocess as sp sys.path.append(os.getcwd()+"/../../..") from commonTools import * @@ -44,7 +45,7 @@ def insert_values(values_for_column,oci_objs, region, comp_name, vcn_name, rulet values_for_column = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict,values_for_column) -def print_secrules(seclists,region,vcn_name,comp_name): +def print_secrules(seclists,region,vcn_name,comp_name,state): for seclist in seclists.data: isec_rules = seclist.ingress_security_rules esec_rules = seclist.egress_security_rules @@ -53,11 +54,13 @@ def print_secrules(seclists,region,vcn_name,comp_name): if tf_import_cmd: tf_name = vcn_name + "_" + dn - tf_name=commonTools.check_tf_variable(tf_name) + tf_name = commonTools.check_tf_variable(tf_name) if("Default Security List for " in dn): - importCommands[region.lower()].write("\nterraform import \"module.security-lists[\\\"" + tf_name + "\\\"].oci_core_default_security_list.default_security_list[0]\" " + str(seclist.id)) + tf_resource = f'module.security-lists[\\"{tf_name}\\"].oci_core_default_security_list.default_security_list[0]' else: - importCommands[region.lower()].write("\nterraform import \"module.security-lists[\\\"" + tf_name + "\\\"].oci_core_security_list.security_list[0]\" " + str(seclist.id)) + tf_resource = f'module.security-lists[\\"{tf_name}\\"].oci_core_security_list.security_list[0]' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(seclist.id)}' if(len(isec_rules)==0 and len(esec_rules)==0): @@ -211,7 +214,10 @@ def export_seclist(inputfile, outdir, service_dir,config,signer, ct, export_comp global tf_import_cmd global values_for_column global sheet_dict - global importCommands + global importCommands,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile @@ -234,18 +240,22 @@ def export_seclist(inputfile, outdir, service_dir,config,signer, ct, export_comp if tf_import_cmd: importCommands={} for reg in export_regions: - if (os.path.exists(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_secrules_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg+ "/" + service_dir, "tf_import_network", - "tf_import_commands_network_secrules_nonGF.sh") - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir+ "/tf_import_commands_network_secrules_nonGF.sh", "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - importCommands[reg].write("\n\n######### Writing import for Security Lists #########\n\n") + if (os.path.exists(outdir + "/" + reg + "/" + service_dir+ "/import_commands_network_secrules.sh")): + commonTools.backup_file(outdir + "/" + reg+ "/" + service_dir, "import_network", + "import_commands_network_secrules.sh") + importCommands[reg] = '' for reg in export_regions: config.__setitem__("region", commonTools().region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass vcn = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() #comp_ocid_done = [] @@ -256,11 +266,16 @@ def export_seclist(inputfile, outdir, service_dir,config,signer, ct, export_comp vcn_name=v.display_name for ntk_compartment_name_again in export_compartments: seclists = oci.pagination.list_call_get_all_results(vcn.list_security_lists,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name_again], vcn_id=vcn_id, lifecycle_state='AVAILABLE',sort_by='DISPLAYNAME') - print_secrules(seclists,region,vcn_name,ntk_compartment_name_again) + print_secrules(seclists,region,vcn_name,ntk_compartment_name_again,state) commonTools.write_to_cd3(values_for_column,cd3file,"SecRulesinOCI") print("SecRules exported to CD3\n") if tf_import_cmd: for reg in export_regions: - importCommands[reg].write('\n\nterraform plan\n') - importCommands[reg].close() + script_file = f'{outdir}/{reg}/{service_dir}/import_commands_network_secrules.sh' + init_commands = f'\n#!/bin/bash\n{tf_or_tofu} init\n######### Writing import for Security Lists #########\n' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/Network/BaseNetwork/export_network_nonGreenField.py b/cd3_automation_toolkit/Network/BaseNetwork/export_network_nonGreenField.py index 5a7cb75b7..fae4465c6 100644 --- a/cd3_automation_toolkit/Network/BaseNetwork/export_network_nonGreenField.py +++ b/cd3_automation_toolkit/Network/BaseNetwork/export_network_nonGreenField.py @@ -8,13 +8,16 @@ from .exportRoutetable import export_drg_routetable from .exportSeclist import export_seclist from .exportNSG import export_nsg +import subprocess as sp sys.path.append(os.getcwd() + "/..") from commonTools import * importCommands = {} +importCommands_dhcp = {} importCommands_rpc = {} importCommands_vlan = {} +importCommands_subnet = {} oci_obj_names = {} @@ -87,7 +90,7 @@ def print_drgv2(values_for_column_drgv2, region, comp_name, vcn_info, drg_info, def print_vcns(values_for_column_vcns, region, comp_name, vnc,vcn_info, drg_attachment_info, igw_info, ngw_info, sgw_info, - lpg_display_names): + lpg_display_names,state): drg_info=None for col_header in values_for_column_vcns.keys(): @@ -161,11 +164,12 @@ def print_vcns(values_for_column_vcns, region, comp_name, vnc,vcn_info, drg_atta values_for_column_vcns) tf_name = commonTools.check_tf_variable(vcn_info.display_name) - importCommands[region.lower()].write( - "\nterraform import \"module.vcns[\\\"" + tf_name + "\\\"].oci_core_vcn.vcn\" " + str(vcn_info.id)) + tf_resource = f'module.vcns[\\"{tf_name}\\"].oci_core_vcn.vcn' + if tf_resource not in state["resources"]: + importCommands[region.lower()].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(vcn_info.id)}') -def print_dhcp(values_for_column_dhcp, region, comp_name, vcn_name, dhcp_info): +def print_dhcp(values_for_column_dhcp, region, comp_name, vcn_name, dhcp_info,state): tf_name = vcn_name + "_" + str(dhcp_info.display_name) tf_name = commonTools.check_tf_variable(tf_name) @@ -206,27 +210,26 @@ def print_dhcp(values_for_column_dhcp, region, comp_name, vcn_name, dhcp_info): values_for_column_dhcp = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict_dhcp, values_for_column_dhcp) if ("Default DHCP Options for " in dhcp_info.display_name): - importCommands[region.lower()].write( - "\nterraform import \"module.default-dhcps[\\\"" + tf_name + "\\\"].oci_core_default_dhcp_options.default_dhcp_option\" " + str( - dhcp_info.id)) + tf_resource = f'module.default-dhcps[\\"{tf_name}\\"].oci_core_default_dhcp_options.default_dhcp_option' else: - importCommands[region.lower()].write( - "\nterraform import \"module.custom-dhcps[\\\"" + tf_name + "\\\"].oci_core_dhcp_options.custom_dhcp_option\" " + str( - dhcp_info.id)) + tf_resource = f'module.custom-dhcps[\\"{tf_name}\\"].oci_core_dhcp_options.custom_dhcp_option' + if tf_resource not in state["resources"]: + importCommands_dhcp[region.lower()].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(dhcp_info.id)}') def print_subnets_vlans(values_for_column_subnets_vlans, region, comp_name, vcn_name, subnet_vlan_info, dhcp_name, - rt_name, sl_nsg_names, add_def_seclist, subnet_vlan_in_excel): + rt_name, sl_nsg_names, add_def_seclist, subnet_vlan_in_excel,state): tf_name = vcn_name + "_" + str(subnet_vlan_info.display_name) tf_name = commonTools.check_tf_variable(tf_name) if subnet_vlan_in_excel == 'Subnet': - importCommands[region.lower()].write( - "\nterraform import \"module.subnets[\\\"" + tf_name + "\\\"].oci_core_subnet.subnet\" " + str( - subnet_vlan_info.id)) + tf_resource = f'module.subnets[\\"{tf_name}\\"].oci_core_subnet.subnet' + if tf_resource not in state["resources"]: + importCommands_subnet[region.lower()].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(subnet_vlan_info.id)}') + elif subnet_vlan_in_excel == 'VLAN': - importCommands_vlan[region.lower()].write( - "\nterraform import \"module.vlans[\\\"" + tf_name + "\\\"].oci_core_vlan.vlan\" " + str( - subnet_vlan_info.id)) + tf_resource = f'module.vlans[\\"{tf_name}\\"].oci_core_vlan.vlan' + if tf_resource not in state["resources"]: + importCommands_vlan[region.lower()].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(subnet_vlan_info.id)}') for col_header in values_for_column_subnets_vlans.keys(): if (col_header == "Region"): @@ -322,7 +325,7 @@ def get_drg_rt_name(drg_rpc_attachment_list, source_rpc_id, rpc_source_client): def get_rpc_resources(source_region, SOURCE_RPC_LIST, dest_rpc_dict, rpc_source_client, ct, values_for_column, - ntk_compartment_name, outdir): + ntk_compartment_name, outdir,drg_info, drg_attachment_info,state_rpc): # Variables dest_rpc_drg_name = "" src_drg_rt_name = "" @@ -381,6 +384,7 @@ def get_comp_details(comp_data): src_drg_rt_import_dist_id = getattr(src_drg_rt_dist.data, 'import_drg_route_distribution_id') if (src_drg_rt_import_dist_id!=None): import_rt_info = rpc_source_client.get_drg_route_distribution(drg_route_distribution_id=src_drg_rt_import_dist_id) + src_drg_rt_dist_info = import_rt_info drg_rt_import_dist_name = getattr(import_rt_info.data, "display_name") import_rt_statements = rpc_source_client.list_drg_route_distribution_statements(drg_route_distribution_id=src_drg_rt_import_dist_id) @@ -406,6 +410,7 @@ def get_comp_details(comp_data): dest_rpc_details = client.get_remote_peering_connection( remote_peering_connection_id=source_rpc_peer_id) dest_rpc_drg_id = dest_rpc.drg_id + dest_drg_info=client.get_drg(drg_id=dest_rpc_drg_id).data dest_rpc_drg_name = getattr(client.get_drg(drg_id=dest_rpc_drg_id).data, 'display_name') dest_drg_comp_name = get_comp_details(getattr(client.get_drg(drg_id=dest_rpc_drg_id).data, 'compartment_id')) dest_rpc_display_name = dest_rpc.display_name @@ -428,16 +433,18 @@ def get_comp_details(comp_data): 'import_drg_route_distribution_id') if dest_drg_rt_import_dist_id!=None: dest_import_rt_info = client.get_drg_route_distribution(drg_route_distribution_id=dest_drg_rt_import_dist_id) + dest_drg_rt_dist_info=dest_import_rt_info dest_drg_rt_import_dist_name = getattr(dest_import_rt_info.data, "display_name") dest_import_rt_statements = client.list_drg_route_distribution_statements(drg_route_distribution_id=dest_drg_rt_import_dist_id) - importCommands_rpc["global"].write( - "\nterraform import \"module.rpcs[\\\"" + rpc_tf_name + f"\\\"].oci_core_remote_peering_connection.{source_region.lower()}_{region.lower()}_requester_rpc[\\\"region\\\"]\" " + str( - source_rpc_id)) - importCommands_rpc["global"].write( - "\nterraform import \"module.rpcs[\\\"" + rpc_tf_name + f"\\\"].oci_core_remote_peering_connection.{source_region.lower()}_{region.lower()}_accepter_rpc[\\\"region\\\"]\" " + str( - dest_rpc_id)) - importCommands_rpc["global"].write("\nterraform plan") + tf_resource = f'module.rpcs[\\"{rpc_tf_name}\\"].oci_core_remote_peering_connection.{source_region.lower()}_{region.lower()}_requester_rpc[\\"region\\"]' + if tf_resource not in state_rpc["resources"]: + importCommands_rpc["global"].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(source_rpc_id)}') + tf_resource = f'module.rpcs[\\"{rpc_tf_name}\\"].oci_core_remote_peering_connection.{source_region.lower()}_{region.lower()}_accepter_rpc[\\"region\\"]' + if tf_resource not in state_rpc["resources"]: + importCommands_rpc["global"].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(dest_rpc_id)}') + + importCommands_rpc["global"].write(f'\n{tf_or_tofu} plan') for col_header in values_for_column: if col_header == 'Region': values_for_column[col_header].append(source_region) @@ -480,9 +487,10 @@ def get_comp_details(comp_data): values_for_column[col_header].append(statement_val) elif col_header.lower() in commonTools.tagColumns: - values_for_column = commonTools.export_tags(new_rpc, col_header, values_for_column) + values_for_column = commonTools.export_tags(drg_info, col_header, values_for_column) else: - oci_objs = [new_rpc] + oci_objs = [new_rpc, drg_info, drg_attachment_info, src_drg_rt_dist, + src_drg_rt_dist_info] values_for_column = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict, values_for_column) @@ -529,9 +537,10 @@ def get_comp_details(comp_data): values_for_column[col_header].append(statement_val) elif col_header.lower() in commonTools.tagColumns: - values_for_column = commonTools.export_tags(new_rpc, col_header, values_for_column) + values_for_column = commonTools.export_tags(dest_drg_info, col_header, values_for_column) else: - oci_objs = [new_rpc] + oci_objs = [new_rpc, dest_drg_info, dest_drg_rt_dist, + dest_drg_rt_dist_info] values_for_column = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict, values_for_column) @@ -544,7 +553,9 @@ def get_comp_details(comp_data): def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, export_compartments=[], export_regions=[]): global sheet_dict_vcns - global sheet_dict_drgv2 + global sheet_dict_drgv2,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -563,7 +574,7 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp # For RPCs import file. # Create backups - rpc_file_name = 'tf_import_commands_' + "rpcs" + '_nonGF.sh' + rpc_file_name = 'import_commands_' + "rpcs" + '.sh' rpc_script_file = f'{outdir}/global/rpc/{rpc_file_name}' os.makedirs(os.path.dirname(rpc_script_file), exist_ok=True) importCommands_rpc["global"] = open(rpc_script_file, "w+") @@ -571,6 +582,14 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp importCommands_rpc["global"].write("\n") importCommands_rpc["global"].write("terraform init") importCommands_rpc["global"].write("\n\n######### Writing import for RPC #########\n\n") + state_rpc = {'path': f'{outdir}/global/rpc/', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state_rpc["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state_rpc["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass # Remove existing rpc.safe file if exists. file_path = f'{outdir}/global/rpc/' + "rpc.safe" @@ -579,16 +598,23 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp # Create backups for reg in export_regions: - if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_network_major-objects_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "tf_import_network", - "tf_import_commands_network_major-objects_nonGF.sh") + file_name = "import_commands_network_major-objects.sh" + if (os.path.exists(outdir + "/" + reg + "/" + service_dir +"/"+ file_name)): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "import_network",file_name) if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/obj_names.safe")): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "obj_names", "obj_names.safe") - importCommands[reg] = open( - outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_network_major-objects_nonGF.sh", "w") + importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir +"/"+ file_name, "w") + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass importCommands[reg].write("#!/bin/bash") importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg].write(f'{tf_or_tofu} init') oci_obj_names[reg] = open(outdir + "/" + reg + "/" + service_dir + "/obj_names.safe", "w") print("Tabs- VCNs and DRGs would be overwritten during export process!!!\n") @@ -632,8 +658,9 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp tf_name = commonTools.check_tf_variable(drg_display_name) if (drg_id not in drg_ocid): oci_obj_names[reg].write("\nDRG Version::::" + drg_display_name + "::::" + drg_version) - importCommands[reg].write( - "\nterraform import \"module.drgs[\\\"" + tf_name + "\\\"].oci_core_drg.drg\" " + drg_info.id) + tf_resource = f'module.drgs[\\"{tf_name}\\"].oci_core_drg.drg' + if tf_resource not in state["resources"]: + importCommands[reg].write( f'\n{tf_or_tofu} import "{tf_resource}" {str(drg_info.id)}') drg_ocid.append(drg_id) # Get Attachment Details @@ -647,8 +674,6 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp attach_type = "VCN" attach_id = drg_attachment_info.vcn_id - - vcn_info = None if (attach_type.upper() == "VCN"): vcn_drgattach_route_table_id = drg_attachment_info.route_table_id @@ -656,9 +681,9 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp # tf_name = vcn_info.display_name + "_" + drg_attachment_name tf_name = commonTools.check_tf_variable(drg_attachment_name) - - importCommands[reg].write( - "\nterraform import \"module.drg-attachments[\\\"" + tf_name + "\\\"].oci_core_drg_attachment.drg_attachment\" " + drg_attachment_info.id) + tf_resource = f'module.drg-attachments[\\"{tf_name}\\"].oci_core_drg_attachment.drg_attachment' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(drg_attachment_info.id)}') #oci_obj_names[reg].write( #"\ndrgattachinfo::::" + vcn_info.display_name + "::::" + drg_display_name + "::::" + drg_attachment_name) @@ -683,14 +708,15 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp tf_name = commonTools.check_tf_variable( drg_display_name + "_" + import_drg_route_distribution_info.display_name) if (import_drg_route_distribution_info.display_name not in commonTools.drg_auto_RDs): - importCommands[reg].write( - "\nterraform import \"module.drg-route-distributions[\\\"" + tf_name + "\\\"].oci_core_drg_route_distribution.drg_route_distribution\" " + import_drg_route_distribution_info.id) + tf_resource = f'module.drg-route-distributions[\\"{tf_name}\\"].oci_core_drg_route_distribution.drg_route_distribution' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(import_drg_route_distribution_info.id)}') k = 1 for stmt in drg_route_distribution_statements.data: - importCommands[reg].write( - "\nterraform import \"module.drg-route-distribution-statements[\\\"" + tf_name + "_statement" + str( - k) + "\\\"].oci_core_drg_route_distribution_statement.drg_route_distribution_statement\" drgRouteDistributions/" + import_drg_route_distribution_info.id + "/statements/" + stmt.id) + tf_resource = f'module.drg-route-distribution-statements[\\"{tf_name}_statement{str(k)}\\"].oci_core_drg_route_distribution_statement.drg_route_distribution_statement' + if tf_resource not in state["resources"]: + importCommands[reg].write( f'\n{tf_or_tofu} import "{tf_resource}" drgRouteDistributions/{str(import_drg_route_distribution_info.id)}/statements/{stmt.id}') k = k + 1 print_drgv2(values_for_column_drgv2, region, drg_comp_name, vcn_info, drg_info, drg_attachment_info, @@ -721,14 +747,14 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp tf_name = commonTools.check_tf_variable( drg_display_name + "_" + import_drg_route_distribution_info.display_name) if (import_drg_route_distribution_info.display_name not in commonTools.drg_auto_RDs): - importCommands[reg].write( - "\nterraform import \"module.drg-route-distributions[\\\"" + tf_name + "\\\"].oci_core_drg_route_distribution.drg_route_distribution\" " + import_drg_route_distribution_info.id) - + tf_resource = f'module.drg-route-distributions[\\"{tf_name}\\"].oci_core_drg_route_distribution.drg_route_distribution' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(import_drg_route_distribution_info.id)}') k = 1 for stmt in drg_route_distribution_statements.data: - importCommands[reg].write( - "\nterraform import \"module.drg-route-distribution-statements[\\\"" + tf_name + "_statement" + str( - k) + "\\\"].oci_core_drg_route_distribution_statement.drg_route_distribution_statement\" drgRouteDistributions/" + import_drg_route_distribution_info.id + "/statements/" + stmt.id) + tf_resource = f'module.drg-route-distribution-statements[\\"{tf_name}_statement{str(k)}\\"].oci_core_drg_route_distribution_statement.drg_route_distribution_statement' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" drgRouteDistributions/{str(import_drg_route_distribution_info.id)}/statements/{stmt.id}') k = k + 1 dest_rpc_dict = {} @@ -746,7 +772,7 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp ntk_compartment_name]) get_rpc_resources(region, SOURCE_RPC_LIST, dest_rpc_dict, vnc, - ct, values_for_column_drgv2, ntk_compartment_name, outdir) + ct, values_for_column_drgv2, ntk_compartment_name, outdir,drg_info, drg_attachment_info,state_rpc) rpc_execution = False # Get All Other RTs for this DRG only if it is DRGv2 @@ -779,14 +805,15 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp tf_name = commonTools.check_tf_variable( drg_display_name + "_" + import_drg_route_distribution_info.display_name) if (import_drg_route_distribution_info.display_name not in commonTools.drg_auto_RDs): - importCommands[reg].write( - "\nterraform import \"module.drg-route-distributions[\\\"" + tf_name + "\\\"].oci_core_drg_route_distribution.drg_route_distribution\" " + import_drg_route_distribution_info.id) - + tf_resource = f'module.drg-route-distributions[\\"{tf_name}\\"].oci_core_drg_route_distribution.drg_route_distribution' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(import_drg_route_distribution_info.id)}') k = 1 for stmt in drg_route_distribution_statements.data: - importCommands[reg].write( - "\nterraform import \"module.drg-route-distribution-statements[\\\"" + tf_name + "_statement" + str( - k) + "\\\"].oci_core_drg_route_distribution_statement.drg_route_distribution_statement\" drgRouteDistributions/" + import_drg_route_distribution_info.id + "/statements/" + stmt.id) + tf_resource = f'module.drg-route-distribution-statements[\\"{tf_name}_statement{str(k)}\\"].oci_core_drg_route_distribution_statement.drg_route_distribution_statement' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" drgRouteDistributions/{str(import_drg_route_distribution_info.id)}/statements/{stmt.id}') + k = k + 1 print_drgv2(values_for_column_drgv2, region, drg_comp_name, vcn_info, drg_info, drg_attachment_info, drg_route_table_info, @@ -799,6 +826,14 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp # Fetch VCNs for reg in export_regions: + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass importCommands[reg].write("\n######### Writing import for VCNs #########\n") config.__setitem__("region", ct.region_dict[reg]) vnc = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -834,9 +869,9 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp igw_display_name = igw_info.display_name tf_name = vcn_info.display_name + "_" + igw_display_name tf_name = commonTools.check_tf_variable(tf_name) - importCommands[reg].write( - "\nterraform import \"module.igws[\\\"" + tf_name + "\\\"].oci_core_internet_gateway.internet_gateway\" " + igw_info.id) - + tf_resource = f'module.igws[\\"{tf_name}\\"].oci_core_internet_gateway.internet_gateway' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(igw_info.id)}') # ngw_display_name = "n" NGWs = oci.pagination.list_call_get_all_results(vnc.list_nat_gateways, @@ -848,9 +883,9 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp ngw_display_name = ngw_info.display_name tf_name = vcn_info.display_name + "_" + ngw_display_name tf_name = commonTools.check_tf_variable(tf_name) - - importCommands[reg].write( - "\nterraform import \"module.ngws[\\\"" + tf_name + "\\\"].oci_core_nat_gateway.nat_gateway\" " + ngw_info.id) + tf_resource = f'module.ngws[\\"{tf_name}\\"].oci_core_nat_gateway.nat_gateway' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(ngw_info.id)}') # sgw_display_name = "n" SGWs = oci.pagination.list_call_get_all_results(vnc.list_service_gateways, @@ -862,8 +897,9 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp sgw_display_name = sgw_info.display_name tf_name = vcn_info.display_name + "_" + sgw_display_name tf_name = commonTools.check_tf_variable(tf_name) - importCommands[reg].write( - "\nterraform import \"module.sgws[\\\"" + tf_name + "\\\"].oci_core_service_gateway.service_gateway\" " + sgw_info.id) + tf_resource = f'module.sgws[\\"{tf_name}\\"].oci_core_service_gateway.service_gateway' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(sgw_info.id)}') lpg_display_names = "" LPGs = oci.pagination.list_call_get_all_results(vnc.list_local_peering_gateways, @@ -884,8 +920,9 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp tf_name = vcn_info.display_name + "_" + lpg_info.display_name tf_name = commonTools.check_tf_variable(tf_name) - importCommands[reg].write( - "\nterraform import \"module.exported-lpgs[\\\"" + tf_name + "\\\"].oci_core_local_peering_gateway.local_peering_gateway\" " + lpg_info.id) + tf_resource = f'module.exported-lpgs[\\"{tf_name}\\"].oci_core_local_peering_gateway.local_peering_gateway' + if tf_resource not in state["resources"]: + importCommands[reg].write(f'\n{tf_or_tofu} import "{tf_resource}" {str(lpg_info.id)}') if (lpg_display_names == ""): lpg_display_names = "n" @@ -894,19 +931,22 @@ def export_major_objects(inputfile, outdir, service_dir, config, signer, ct, exp # Fill VCNs Tab print_vcns(values_for_column_vcns, region, ntk_compartment_name, vnc,vcn_info, drg_attachment_info, igw_info, ngw_info, - sgw_info, lpg_display_names) + sgw_info, lpg_display_names,state) commonTools.write_to_cd3(values_for_column_vcns, cd3file, "VCNs") print("VCNs exported to CD3\n") for reg in export_regions: - importCommands[reg].write('\n\nterraform plan\n') + importCommands[reg].write(f'\n\n{tf_or_tofu} plan\n') importCommands[reg].close() oci_obj_names[reg].close() def export_dhcp(inputfile, outdir, service_dir, config, signer, ct, export_compartments=[], export_regions=[]): - global sheet_dict_dhcp + global sheet_dict_dhcp,tf_or_tofu + + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -923,19 +963,26 @@ def export_dhcp(inputfile, outdir, service_dir, config, signer, ct, export_compa # Create backups for reg in export_regions: - if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_network_dhcp_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "tf_import_network", - "tf_import_commands_network_dhcp_nonGF.sh") - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_network_dhcp_nonGF.sh", - "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + dhcp_file_name = "import_commands_network_dhcp.sh" + if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/"+dhcp_file_name)): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, "import_network",dhcp_file_name) + importCommands_dhcp[reg] = open(outdir + "/" + reg + "/" + service_dir + "/"+dhcp_file_name,"w") + importCommands_dhcp[reg].write("#!/bin/bash") + importCommands_dhcp[reg].write("\n") + importCommands_dhcp[reg].write(f'{tf_or_tofu} init') print("Tab- DHCP would be overwritten during export process!!!") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for DHCP #########\n\n") + importCommands_dhcp[reg].write("\n\n######### Writing import for DHCP #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass vnc = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() # comp_ocid_done = [] @@ -954,17 +1001,20 @@ def export_dhcp(inputfile, outdir, service_dir, config, signer, ct, export_compa for dhcp in DHCPs.data: dhcp_info = dhcp print_dhcp(values_for_column_dhcp, region, ntk_compartment_name_again, vcn_info.display_name, - dhcp_info) + dhcp_info,state) commonTools.write_to_cd3(values_for_column_dhcp, cd3file, "DHCP") print("DHCP exported to CD3\n") for reg in export_regions: - importCommands[reg].write('\n\nterraform plan\n') - importCommands[reg].close() + importCommands_dhcp[reg].write(f'\n\n{tf_or_tofu} plan\n') + importCommands_dhcp[reg].close() def export_subnets_vlans(inputfile, outdir, service_dir, config, signer, ct, export_compartments=[], export_regions=[]): - global sheet_dict_subnets_vlans + global sheet_dict_subnets_vlans,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] + skip_vlans = {} cd3file = inputfile if ('.xls' not in cd3file): @@ -987,41 +1037,44 @@ def export_subnets_vlans(inputfile, outdir, service_dir, config, signer, ct, exp # Create backups for subnets/vlans tf import shell script files for reg in export_regions: - if (os.path.exists( - outdir + "/" + reg + "/" + service_dir_network + "/tf_import_commands_network_subnets_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir_network, "tf_import_network", - "tf_import_commands_network_subnets_nonGF.sh") - importCommands[reg] = open( - outdir + "/" + reg + "/" + service_dir_network + "/tf_import_commands_network_subnets_nonGF.sh", "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + subnet_file_name = "import_commands_network_subnets.sh" + if (os.path.exists(outdir + "/" + reg + "/" + service_dir_network + "/"+subnet_file_name)): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir_network, "import_network",subnet_file_name) + importCommands_subnet[reg] = open(outdir + "/" + reg + "/" + service_dir_network + "/"+subnet_file_name, "w") + importCommands_subnet[reg].write("#!/bin/bash") + importCommands_subnet[reg].write("\n") + importCommands_subnet[reg].write(f'{tf_or_tofu} init') + + vlan_file_name = "import_commands_network_vlans.sh" - if (os.path.exists(outdir + "/" + reg + "/" + service_dir_vlan + "/tf_import_commands_network_vlans_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir_vlan, "tf_import_network", - "tf_import_commands_network_vlans_nonGF.sh") - importCommands_vlan[reg] = open( - outdir + "/" + reg + "/" + service_dir_vlan + "/tf_import_commands_network_vlans_nonGF.sh", "w") - importCommands_vlan[reg].write("#!/bin/bash") - importCommands_vlan[reg].write("\n") - importCommands_vlan[reg].write("terraform init") + if (os.path.exists(outdir + "/" + reg + "/" + service_dir_vlan + "/"+vlan_file_name)): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir_vlan, "import_network",vlan_file_name) + importCommands_vlan[reg] = open(outdir + "/" + reg + "/" + service_dir_vlan + "/" + vlan_file_name, "w") print("Tab- 'SubnetsVLANs' would be overwritten during export process!!!") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Subnets #########\n\n") - importCommands_vlan[reg].write("\n\n######### Writing import for VLANs #########\n\n") + importCommands_subnet[reg].write("\n\n######### Writing import for Subnets #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + # check resources in subnet state + state = {'path': f'{outdir}/{reg}/{service_dir_network}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass vnc = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() - skip_vlans = 0 + skip_vlans['reg'] = 0 try: VLANs = oci.pagination.list_call_get_all_results(vnc.list_vlans, compartment_id=ct.ntk_compartment_ids['root']) except Exception as e: if ('Tenancy is NOT whitelisted for VMware SKU' in str(e)): print('Tenancy is NOT whitelisted for VMware SKU..skipping export of VLANs') - skip_vlans = 1 + skip_vlans['reg'] = 1 for ntk_compartment_name in export_compartments: vcns = oci.pagination.list_call_get_all_results(vnc.list_vcns, @@ -1065,12 +1118,24 @@ def export_subnets_vlans(inputfile, outdir, service_dir, config, signer, ct, exp # Fill Subnets tab print_subnets_vlans(values_for_column_subnets_vlans, region, ntk_compartment_name_again, vcn_info.display_name, subnet_info, dhcp_name, - rt_name, sl_names, add_def_seclist, subnet_vlan_in_excel) + rt_name, sl_names, add_def_seclist, subnet_vlan_in_excel,state) # VLAN Data - if skip_vlans == 1: + if skip_vlans['reg'] == 1: continue - + importCommands_vlan[reg].write("#!/bin/bash") + importCommands_vlan[reg].write("\n") + importCommands_vlan[reg].write(f'{tf_or_tofu} init') + importCommands_vlan[reg].write("\n\n######### Writing import for VLANs #########\n\n") + # check resources in vlan state + state_vlan = {'path': f'{outdir}/{reg}/{service_dir_vlan}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state_vlan["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state_vlan["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass subnet_vlan_in_excel = "VLAN" VLANs = oci.pagination.list_call_get_all_results(vnc.list_vlans, compartment_id=ct.ntk_compartment_ids[ @@ -1098,15 +1163,17 @@ def export_subnets_vlans(inputfile, outdir, service_dir, config, signer, ct, exp # Fill Subnets tab print_subnets_vlans(values_for_column_subnets_vlans, region, ntk_compartment_name_again, vcn_info.display_name, vlan_info, dhcp_name, - rt_name, nsg_names, add_def_seclist, subnet_vlan_in_excel) + rt_name, nsg_names, add_def_seclist, subnet_vlan_in_excel,state_vlan) commonTools.write_to_cd3(values_for_column_subnets_vlans, cd3file, "SubnetsVLANs") print("SubnetsVLANs exported to CD3\n") for reg in export_regions: - importCommands[reg].write('\n\nterraform plan\n') - importCommands[reg].close() - importCommands_vlan[reg].write('\n\nterraform plan\n') + importCommands_subnet[reg].write(f'\n\n{tf_or_tofu} plan\n') + importCommands_subnet[reg].close() + if skip_vlans['reg'] == 1: + continue + importCommands_vlan[reg].write(f'\n\n{tf_or_tofu} plan\n') importCommands_vlan[reg].close() # Execution of the code begins here diff --git a/cd3_automation_toolkit/Network/DNS/create_dns_rrsets.py b/cd3_automation_toolkit/Network/DNS/create_dns_rrsets.py index 22e5aa554..1bd56ce02 100644 --- a/cd3_automation_toolkit/Network/DNS/create_dns_rrsets.py +++ b/cd3_automation_toolkit/Network/DNS/create_dns_rrsets.py @@ -79,6 +79,9 @@ def create_terraform_dns_rrsets(inputfile, outdir, service_dir, prefix, ct): zone_name = str(df["Zone"][i]).strip() domain = str(df["Domain"][i]).strip() rtype = str(df["RType"][i]).strip() + if 'nan' in [view_name,zone_name,domain,rtype]: + print(f'Required parameters for record creation are missing. Skipping record creation for row : {i+3}') + continue rrset_tf_name = str(view_name + "_" + zone_name+ "_" + domain+ "_" + rtype).replace(".", "_") # Assign value to item key variable in template tempStr['rrset_tf_name'] = rrset_tf_name diff --git a/cd3_automation_toolkit/Network/DNS/export_dns_resolvers.py b/cd3_automation_toolkit/Network/DNS/export_dns_resolvers.py index b2a3d7172..c3add289f 100644 --- a/cd3_automation_toolkit/Network/DNS/export_dns_resolvers.py +++ b/cd3_automation_toolkit/Network/DNS/export_dns_resolvers.py @@ -6,6 +6,7 @@ # import oci import os +import subprocess as sp from commonTools import * importCommands = {} oci_obj_names = {} @@ -102,12 +103,14 @@ def get_e_map(region, dns_client, vnc_client, ct, resolver, ntk_compartment_name # Write values to columns map - values_for_column -def print_resolvers(resolver_tf_name, resolver, values_for_column, **value): +def print_resolvers(resolver_tf_name, resolver, values_for_column,state, **value): endpoint_value = value region = endpoint_value['region'] res_id = endpoint_value['res_id'] e_name = endpoint_value['e_name'] - importCommands[region.lower()].write("\nterraform import \"module.dns-resolvers[\\\"" + resolver_tf_name + "\\\"].oci_dns_resolver_endpoint.resolver_endpoint[\\\"" + e_name + "\\\"]\" resolverId/"+ str(res_id)+"/name/" + str(e_name)) + tf_resource = f'module.dns-resolvers[\\"{resolver_tf_name}\\"].oci_dns_resolver_endpoint.resolver_endpoint[\\"{e_name}\\"]' + if e_name and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" resolverId/{str(res_id)}/name/{str(e_name)}' for col_header in values_for_column: if col_header == 'Region': @@ -142,7 +145,9 @@ def export_dns_resolvers(inputfile, outdir, service_dir, config, signer, ct, exp global cd3file global reg global values_for_column - global serv_dir + global serv_dir,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] serv_dir = service_dir cd3file = inputfile @@ -160,41 +165,48 @@ def export_dns_resolvers(inputfile, outdir, service_dir, config, signer, ct, exp print("\nCD3 excel file should not be opened during export process!!!") print("Tabs- DNS-Resolvers will be overwritten during export process!!!\n") - # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + # Fetch Resolver Details + print("\nFetching details of DNS Resolvers ...") + + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' + for reg in export_regions: script_file = f'{outdir}/{reg}/{serv_dir}/' + file_name + resource = 'import_' + sheetName.lower() + # Create backups if os.path.exists(script_file): commonTools.backup_file(outdir + "/" + reg + "/" + serv_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - # Fetch Resolver Details - print("\nFetching details of DNS Resolvers ...") + importCommands[reg] = '' - for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for DNS Resolvers #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() dns_client = oci.dns.DnsClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) vnc_client = oci.core.VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) for ntk_compartment_name in export_compartments: vcns = oci.pagination.list_call_get_all_results(vnc_client.list_vcns, compartment_id=ct.ntk_compartment_ids[ntk_compartment_name], lifecycle_state="AVAILABLE") + for vcn in vcns.data: resolver_id = vnc_client.get_vcn_dns_resolver_association(vcn.id).data.dns_resolver_id resolver = dns_client.get_resolver(resolver_id).data endpoint_map = get_e_map(region, dns_client, vnc_client, ct, resolver, ntk_compartment_name) vcn_name = vnc_client.get_vcn(resolver.attached_vcn_id).data.display_name resolver_tf_name = vcn_name - importCommands[region.lower()].write( - "\nterraform import \"module.dns-resolvers[\\\"" + resolver_tf_name + "\\\"].oci_dns_resolver.resolver\" " + str( - resolver.id)) + tf_resource = f'module.dns-resolvers[\\"{resolver_tf_name}\\"].oci_dns_resolver.resolver' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(resolver.id)}' for key, value in endpoint_map.items(): - print_resolvers(resolver_tf_name, resolver, values_for_column, **value) + print_resolvers(resolver_tf_name, resolver, values_for_column,state,**value) commonTools.write_to_cd3(values_for_column, cd3file, sheetName) print("{0} DNS Resolvers and Endpoints exported into CD3.\n".format(len(values_for_column["Region"]))) @@ -202,7 +214,10 @@ def export_dns_resolvers(inputfile, outdir, service_dir, config, signer, ct, exp # writing data for reg in export_regions: - script_file = f'{outdir}/{reg}/{serv_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for DNS Resolvers #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Network/DNS/export_dns_views_zones_records.py b/cd3_automation_toolkit/Network/DNS/export_dns_views_zones_records.py index 6037b6cb0..11ba5a798 100644 --- a/cd3_automation_toolkit/Network/DNS/export_dns_views_zones_records.py +++ b/cd3_automation_toolkit/Network/DNS/export_dns_views_zones_records.py @@ -6,6 +6,7 @@ # import oci import os +import subprocess as sp from commonTools import * importCommands = {} @@ -15,7 +16,7 @@ def get_rrset(zone_data,dns_client,record_default): r_map = {} r_tmp = {} - zone_records = dns_client.get_zone_records(zone_data.id).data + zone_records = oci.pagination.list_call_get_all_results(dns_client.get_zone_records,zone_data.id).data for zone_record in zone_records.items: if record_default == 'n' and zone_record.is_protected == True: @@ -40,7 +41,7 @@ def get_rrset(zone_data,dns_client,record_default): return r_map -def print_data(region, ntk_compartment_name, rrset, zone_data, view_data, values_for_column): +def print_data(region, ntk_compartment_name, rrset, zone_data, view_data, values_for_column,state): view_tf_name = str(view_data.display_name) #zone_tf_name = view_tf_name + "_" + str(zone_data.name).replace(".", "_") zone_name = str(zone_data.name).replace(".", "_") @@ -49,9 +50,9 @@ def print_data(region, ntk_compartment_name, rrset, zone_data, view_data, values rrset_tf_name = str(view_tf_name + "_" + zone_name + "_" + domain.replace(".", "_") + "_" + rtype).replace(".", "_") rrset_id = "zoneNameOrId/"+str(zone_data.id)+"/domain/"+domain+"/rtype/"+rtype+"/scope/PRIVATE/viewId/"+str( view_data.id) - importCommands[region.lower()].write( - "\nterraform import \"module.dns-rrsets[\\\"" + rrset_tf_name + "\\\"].oci_dns_rrset.rrset\" " + rrset_id) - + tf_resource = f'module.dns-rrsets[\\"{rrset_tf_name}\\"].oci_dns_rrset.rrset' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {rrset_id}' for col_header in values_for_column: if col_header == 'Region': @@ -104,7 +105,9 @@ def export_dns_views_zones_rrsets(inputfile, outdir, service_dir, config, signer global values_for_vcninfo global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -127,23 +130,28 @@ def export_dns_views_zones_rrsets(inputfile, outdir, service_dir, config, signer print("Tabs- DNS-ViewsZonesRecords will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' - for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - if (os.path.exists(script_file)): - commonTools.backup_file(outdir + "/" + reg +"/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' # Fetch Views/Zones/rrsets Details print("\nFetching details of DNS Views/Zones/Records...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for DNS Views/Zones/RRsets #########\n\n") + resource = 'import_' + sheetName.lower() + importCommands[reg] = "" + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if (os.path.exists(script_file)): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() dns_client = oci.dns.DnsClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) # Same compartment will be used to export view/zones @@ -152,6 +160,7 @@ def export_dns_views_zones_rrsets(inputfile, outdir, service_dir, config, signer for view_data in views.data: if view_default == 'n' and view_data.is_protected == True: continue + #view_data = dns_client.get_view(view.id).data view_tf_name = str(view_data.display_name) zones = oci.pagination.list_call_get_all_results(dns_client.list_zones, @@ -167,18 +176,18 @@ def export_dns_views_zones_rrsets(inputfile, outdir, service_dir, config, signer rrsets = get_rrset(zone_data, dns_client, record_default) if rrsets: for rrset in rrsets.values(): - print_data(region, ntk_compartment_name, rrset, zone_data, view_data, values_for_column) - importCommands[region.lower()].write( - "\nterraform import \"module.dns-zones[\\\"" + zone_tf_name + "\\\"].oci_dns_zone.zone\" " + str( - zone_data.id)) + print_data(region, ntk_compartment_name, rrset, zone_data, view_data, values_for_column,state) + tf_resource = f'module.dns-zones[\\"{zone_tf_name}\\"].oci_dns_zone.zone' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(zone_data.id)}' + else: print_empty_view(region, ntk_compartment_name, view_data, values_for_column) else: print_empty_view(region, ntk_compartment_name, view_data, values_for_column) - - importCommands[region.lower()].write( - "\nterraform import \"module.dns-views[\\\"" + view_tf_name + "\\\"].oci_dns_view.view\" " + str( - view_data.id)) + tf_resource = f'module.dns-views[\\"{view_tf_name}\\"].oci_dns_view.view' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(view_data.id)}' #print_data(region, view_data) @@ -190,5 +199,8 @@ def export_dns_views_zones_rrsets(inputfile, outdir, service_dir, config, signer # writing data for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for DNS Views/Zones/RRsets #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Network/Global/create_rpc_resources.py b/cd3_automation_toolkit/Network/Global/create_rpc_resources.py index 91bc86c6a..5dbd83592 100755 --- a/cd3_automation_toolkit/Network/Global/create_rpc_resources.py +++ b/cd3_automation_toolkit/Network/Global/create_rpc_resources.py @@ -138,6 +138,7 @@ def create_rpc_resource(inputfile, outdir, service_dir, prefix, auth_mechanism, for eachregion in ct.all_regions: tfStr["global"] = '' + match_list = [] for i in df.index: if str(df.loc[i, 'Attached To']).lower().startswith("rpc"): @@ -270,19 +271,20 @@ def create_rpc_resource(inputfile, outdir, service_dir, prefix, auth_mechanism, # Write all info to TF string tfStr["global"] = tfStr["global"] + template.render(tempStr) - # Write TF string to the file in respective region directory - # for reg in ct.all_regions: + # Write TF string to the file in global directory + reg_out_dir = f'{outdir}/global/rpc/' if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) + if tfStr["global"] != '': # Generate RPC String src = "##Add New RPC for global here##" tfStr["global"] = template.render(count=0).replace(src, tfStr["global"] + "\n" + src) tfStr["global"] = "".join([s for s in tfStr["global"].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource = sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) # Write to TF file outfile = reg_out_dir + "/" + auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/__init__.py b/cd3_automation_toolkit/Network/LoadBalancers/__init__.py index f6371ef04..6b42427d1 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/__init__.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/__init__.py @@ -4,6 +4,7 @@ from .create_backendset_backendservers import create_backendset_backendservers from .create_listener import create_listener from .create_path_route_set import create_path_route_set +from .create_routing_policy import create_lb_routing_policy from .create_ruleset import create_ruleset from .export_lbr_nonGreenField import export_lbr from .export_nlb_nonGreenField import export_nlb diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_backendset_backendservers.py b/cd3_automation_toolkit/Network/LoadBalancers/create_backendset_backendservers.py index 49b2c3803..61c8836d0 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_backendset_backendservers.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_backendset_backendservers.py @@ -55,6 +55,10 @@ def create_backendset_backendservers(inputfile, outdir, service_dir, prefix, ct) beset_str[reg] = '' beserver_str[reg] = '' + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + resource = sheetName.lower() + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) + # List of the column headers dfcolumns = df.columns.values.tolist() @@ -173,7 +177,7 @@ def create_backendset_backendservers(inputfile, outdir, service_dir, prefix, ct) else: pass - if columnname == "Backend ServerComp&ServerName:Port": + if columnname == "Backend ServerComp@ServerName:Port": columnname = "backend_server" columnname = commonTools.check_column_headers(columnname) @@ -186,13 +190,28 @@ def create_backendset_backendservers(inputfile, outdir, service_dir, prefix, ct) cnt = 0 #beserver_str = '' - columnvalue = str(df.loc[i,'Backend ServerComp&ServerName:Port']).strip().split(',') + columnvalue = str(df.loc[i,'Backend ServerComp@ServerName:Port']).strip().split(',') for lbr_be_server in columnvalue: + lbr_be_server=lbr_be_server.strip() + if (lbr_be_server != "" and lbr_be_server != "nan"): bserver_list = str(df.loc[i, 'Backup ']).strip().split(',') cnt = cnt + 1 - serverinfo = lbr_be_server.strip().split("&") - servername = serverinfo[1].split(":")[0].strip() + + inst_compartment_tf_name = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + if len(lbr_be_server.split("@")) == 2: + if(len(lbr_be_server.split("@")[0].strip())!=0): + inst_compartment_tf_name = commonTools.check_tf_variable(lbr_be_server.split("@")[0].strip()) + serverinfo = lbr_be_server.split("@")[1] + else: + serverinfo=lbr_be_server + if (":" not in serverinfo): + print("Invalid Backend ServerComp@ServerName:Port format specified for row " + str(i + 3) + ". Exiting!!!") + exit(1) + else: + servername = serverinfo.split(":")[0].strip() + serverport = serverinfo.split(":")[1].strip() + if servername in bserver_list: backup = "true" else: @@ -202,16 +221,12 @@ def create_backendset_backendservers(inputfile, outdir, service_dir, prefix, ct) tempStr.update(tempback) backend_server_tf_name = commonTools.check_tf_variable(servername+"-"+str(cnt)) - serverport = serverinfo[1].split(":")[1].strip() - inst_compartment_tf_name = '' e = servername.count(".") if (e == 3): backend_server_ip_address = "IP:"+servername else: backend_server_ip_address = "NAME:" + servername - if serverinfo[0].strip() != "": - inst_compartment_tf_name = commonTools.check_tf_variable(serverinfo[0].strip()) tempback = {'backend_server_tf_name': backend_set_tf_name+"_"+backend_server_tf_name,'serverport':serverport,'backend_server_ip_address':backend_server_ip_address, 'instance_tf_compartment': inst_compartment_tf_name } tempStr.update(tempback) @@ -235,9 +250,7 @@ def create_backendset_backendservers(inputfile, outdir, service_dir, prefix, ct) if finalstring != "": - resource = sheetName.lower() srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # Write to TF file outfile = srcdir + lb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_listener.py b/cd3_automation_toolkit/Network/LoadBalancers/create_listener.py index e1ad0ff91..0f6ece5a7 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_listener.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_listener.py @@ -51,6 +51,9 @@ def create_listener(inputfile, outdir, service_dir, prefix, ct): # Take backup of files for reg in ct.all_regions: listener_str[reg] = "" + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + resource = sheetName.lower() + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -217,9 +220,7 @@ def create_listener(inputfile, outdir, service_dir, prefix, ct): listener_str[reg] = listener.render(skeleton=True, count=0, region=reg).replace(src,listener_str[reg]+"\n"+src) finalstring = "".join([s for s in listener_str[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource=sheetName.lower() srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # Write to TF file outfile = srcdir + lb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_nlb_backendset_backendservers.py b/cd3_automation_toolkit/Network/LoadBalancers/create_nlb_backendset_backendservers.py index 366bf396b..86bad49e8 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_nlb_backendset_backendservers.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_nlb_backendset_backendservers.py @@ -43,10 +43,14 @@ def create_nlb_backendset_backendservers(inputfile, outdir, service_dir, prefix, beset_str[reg] = '' beserver_str[reg] = '' nlb_names[reg] = [] + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + resource = sheetName.lower() + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() prevreg = '' + prevcomp='' for i in df.index: region = str(df.loc[i, 'Region']) @@ -60,9 +64,16 @@ def create_nlb_backendset_backendservers(inputfile, outdir, service_dir, prefix, if region in commonTools.endNames: break + if region != 'nan' and region not in ct.all_regions: print("\nInvalid Region; It should be one of the values mentioned in VCN Info tab...Exiting!!") exit(1) + compname = str(df.loc[i, 'Compartment Name']) + + if compname.lower() != 'nan': + compname = compname.strip() + prevcomp = compname + # temporary dictionaries tempStr= {} @@ -120,7 +131,7 @@ def create_nlb_backendset_backendservers(inputfile, outdir, service_dir, prefix, if columnname == "Backend HealthCheck Interval In Millis": columnname = 'interval_in_millis' - if columnname == "Backend ServerComp&ServerName:Port": + if columnname == "Backend ServerComp@ServerName:Port": columnname = "backend_server" columnname = commonTools.check_column_headers(columnname) @@ -135,25 +146,38 @@ def create_nlb_backendset_backendservers(inputfile, outdir, service_dir, prefix, cnt = 0 #beserver_str = '' - columnvalue = str(df.loc[i,'Backend ServerComp&ServerName:Port']).strip().split(',') + columnvalue = str(df.loc[i,'Backend ServerComp@ServerName:Port']).strip().split(',') for nlb_be_server in columnvalue: + + nlb_be_server = nlb_be_server.strip() + if (nlb_be_server != "" and nlb_be_server != "nan"): cnt = cnt + 1 - serverinfo = nlb_be_server.strip().split("&") - servername = serverinfo[1].split(":")[0].strip() - backend_server_tf_name = commonTools.check_tf_variable(servername+"-"+str(cnt)) - serverport = serverinfo[1].split(":")[1].strip() - inst_compartment_tf_name = '' + inst_compartment_tf_name = commonTools.check_tf_variable(prevcomp).strip() + #inst_compartment_tf_name = tempStr['compartment_tf_name'] + if len(nlb_be_server.split("@")) == 2: + if (len(nlb_be_server.split("@")[0].strip()) != 0): + inst_compartment_tf_name = commonTools.check_tf_variable(nlb_be_server.split("@")[0].strip()) + serverinfo = nlb_be_server.split("@")[1] + else: + serverinfo = nlb_be_server + if (":" not in serverinfo): + print("Invalid Backend ServerComp@ServerName:Port format specified for row " + str( + i + 3) + ". Exiting!!!") + exit(1) + else: + servername = serverinfo.split(":")[0].strip() + serverport = serverinfo.split(":")[1].strip() + + backend_server_tf_name = commonTools.check_tf_variable(servername + "-" + str(cnt)) e = servername.count(".") if (e == 3): - backend_server_ip_address = "IP:"+servername + backend_server_ip_address = "IP:" + servername servername = "" else: backend_server_ip_address = "NAME:" + servername - if serverinfo[0].strip() != "": - inst_compartment_tf_name = commonTools.check_tf_variable(serverinfo[0].strip()) tempback = {'backend_server_tf_name': backend_set_tf_name+"_"+backend_server_tf_name,'serverport':serverport,'backend_server_ip_address':backend_server_ip_address, 'instance_tf_compartment': inst_compartment_tf_name, 'servername': servername } tempStr.update(tempback) @@ -175,9 +199,8 @@ def create_nlb_backendset_backendservers(inputfile, outdir, service_dir, prefix, finalstring = "".join([s for s in finalstring.strip().splitlines(True) if s.strip("\r\n").strip()]) if finalstring != "": - resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # Write to TF file outfile = srcdir + lb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_path_route_set.py b/cd3_automation_toolkit/Network/LoadBalancers/create_path_route_set.py index c4c07733b..f84290270 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_path_route_set.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_path_route_set.py @@ -56,6 +56,9 @@ def create_path_route_set(inputfile, outdir, service_dir, prefix, ct): prs_str[reg] = '' rule_str[reg] = '' path_route_set_list[reg] = [] + resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -156,9 +159,7 @@ def create_path_route_set(inputfile, outdir, service_dir, prefix, ct): prs_str[reg] = prs.render(skeleton=True, count=0, region=reg).replace(src,prs_str[reg]+"\n"+src) finalstring = "".join([s for s in prs_str[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource=sheetName.lower() srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # Write to TF file outfile = srcdir + lb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_routing_policy.py b/cd3_automation_toolkit/Network/LoadBalancers/create_routing_policy.py new file mode 100755 index 000000000..09851538f --- /dev/null +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_routing_policy.py @@ -0,0 +1,153 @@ +#!/usr/bin/python3 +# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. +# +# This script will produce a Terraform file that will be used to set up OCI core components +# Create LB Routing Policy +# +# Author: Ulaganathan N +# Oracle Consulting + + +import pandas as pd +from jinja2 import Environment, FileSystemLoader +from pathlib import Path +from commonTools import * + + + +def create_lb_routing_policy(inputfile, outdir, service_dir, prefix, ct): + # Load the template file + file_loader = FileSystemLoader(f'{Path(__file__).parent}/templates') + env = Environment(loader=file_loader, keep_trailing_newline=True) + lb_routing_policy_template = env.get_template('lb-routing-policy-template') + filename = inputfile + sheetName = "LB-RoutingPolicy" + lb_auto_tfvars_filename = prefix + "_"+sheetName.lower()+".auto.tfvars" + + # Read cd3 using pandas dataframe + df, col_headers = commonTools.read_cd3(filename, sheetName) + + df = df.dropna(how='all') + df = df.reset_index(drop=True) + + # DF with just the load balancer names and the Region details + dffill = df[['Region', 'LBR Name', 'Routing Policy Name']] + dffill = dffill.fillna(method='ffill') + + # Drop unnecessary columns + dfdrop = df[['Region', 'LBR Name', 'Routing Policy Name']] + dfdrop = df.drop(dfdrop, axis=1) + + # dfcert with required details + df = pd.concat([dffill, dfdrop], axis=1) + routing_policies = {} + defined_tags = {} + freeform_tags = {} + + # Take backup of files + for reg in ct.all_regions: + routing_policies[reg] = '' + defined_tags[reg] = '' + freeform_tags[reg] = '' + resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) + + # List of the column headers + dfcolumns = df.columns.values.tolist() + for i in df.index: + region = str(df.loc[i, 'Region']) + + if region.lower() == 'nan': + continue + + region = region.strip().lower() + + if region in commonTools.endNames: + break + + if region not in ct.all_regions: + print("\nInvalid Region; It should be one of the values mentioned in VCN Info tab...Exiting!!") + exit() + + # temporary dictionaries + tempStr = {} + tempdict = {} + lbr_tf_name = '' + routing_policy_tf_name = '' + + # Check if mandatory field is empty + if pd.isna(df.loc[i, 'Rules']): + print("\nColumn Rules cannot be left empty.....Exiting!") + exit(1) + + # Fetch data; loop through columns + for columnname in dfcolumns: + # Column value + columnvalue = str(df[columnname][i]).strip() + + # Check for boolean/null in column values + columnvalue = commonTools.check_columnvalue(columnvalue) + + # Check for multivalued columns + tempdict = commonTools.check_multivalues_columnvalue(columnvalue, columnname, tempdict) + + # Process Defined and Freeform Tags + if columnname.lower() in commonTools.tagColumns: + tempdict = commonTools.split_tag_values(columnname, columnvalue, tempdict) + + if columnname == "LBR Name": + lbr_tf_name = commonTools.check_tf_variable(columnvalue) + tempdict = {'load_balancer_id': columnvalue, 'lbr_tf_name': lbr_tf_name} + + if columnname == "Routing Policy Name": + routing_policy_tf_name = commonTools.check_tf_variable(columnvalue) + tempdict = {'name': routing_policy_tf_name, 'routing_policy_tf_name': routing_policy_tf_name} + + if columnname == "Rules": + # Split the string into lines and remove any trailing commas + rules = [line.strip() for line in columnvalue.split('\n')] + processed_rules = [] + + for rule in rules: + parts = [part.strip() for part in rule.split('::')] + + if len(parts) >= 2: + name = parts[0] + condition = parts[1] + backend_set_name = parts[2] if len(parts) > 2 else "" + + processed_rules.append({ + 'name': name, + 'condition': condition, + 'backend_set_name': backend_set_name + }) + tempdict = {'rules': processed_rules} + + columnname = commonTools.check_column_headers(columnname) + tempStr[columnname] = str(columnvalue).strip() + tempStr.update(tempdict) + + routing_policy_name = lbr_tf_name + "_" + routing_policy_tf_name + + if routing_policy_name != '': + if routing_policy_name not in routing_policies[region]: + routing_policies[region] = routing_policies[region] + lb_routing_policy_template.render(tempStr) + + + # Take backup of files + for reg in ct.all_regions: + if routing_policies[reg] != '': + # Generate Final String + src = "##Add New Routing Policy for " + reg.lower() + " here##" + routing_policies[reg] = lb_routing_policy_template.render(skeleton=True, count=0, region=reg).replace(src, routing_policies[reg] + "\n" + src) + finalstring = "".join([s for s in routing_policies[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) + + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + + # Write to TF file + outfile = srcdir + lb_auto_tfvars_filename + oname = open(outfile, "w+") + print("Writing to " + outfile) + oname.write(finalstring) + oname.close() diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_ruleset.py b/cd3_automation_toolkit/Network/LoadBalancers/create_ruleset.py index 98069a765..55133f6f3 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_ruleset.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_ruleset.py @@ -65,6 +65,9 @@ def create_ruleset(inputfile, outdir, service_dir, prefix, ct): # Take backup of files for reg in ct.all_regions: rs_str[reg] = '' + resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -307,9 +310,7 @@ def add_rules(df,rs_str,tempStr,control_access): rs_str[reg] = rs.render(skeleton=True, count=0, region=reg).replace(src,rs_str[reg]+"\n"+src) finalstring = "".join([s for s in rs_str[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource=sheetName.lower() srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) outfile = srcdir + lb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_lbr_hostname_certs.py b/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_lbr_hostname_certs.py index c783eb3d3..e320c3765 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_lbr_hostname_certs.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_lbr_hostname_certs.py @@ -74,6 +74,9 @@ def create_terraform_lbr_hostname_certs(inputfile, outdir, service_dir, prefix, certificate_str[reg] = '' cipher_suites[reg] = '' hostname_str_02[reg] = '' + resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) def certificate_templates(dfcert): @@ -181,7 +184,7 @@ def certificate_templates(dfcert): # List of the column headers dfcolumns = df.columns.values.tolist() - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) for i in df.index: region = str(df.loc[i, 'Region']) @@ -254,35 +257,52 @@ def certificate_templates(dfcert): lbr_subnets_list = [] network_compartment_id = '' vcn_name = '' - if columnname == 'LBR Subnets': + if columnname == 'Network Details': lbr_subnets = str(columnvalue).strip().split(",") if len(lbr_subnets) == 1: - if ("ocid1.subnet.oc1" in str(lbr_subnets[0]).strip()): - lbr_subnets_list.append(str(lbr_subnets[0]).strip()) - else: - try: - key = region, str(lbr_subnets[0]).strip() - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - lbr_subnets_list.append(subnets.vcn_subnet_map[key][2]) - except Exception as e: - print("Invalid Subnet Name specified for row " + str(i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + columnvalue=str(lbr_subnets[0]).strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" + vcn_name = "" + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - tempdict = {'network_compartment_tf_name': commonTools.check_tf_variable(network_compartment_id), 'vcn_name': vcn_name,'lbr_subnets': json.dumps(lbr_subnets_list)} + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + + lbr_subnets_list.append(subnet_id) + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'lbr_subnets': json.dumps(lbr_subnets_list)} elif len(lbr_subnets) == 2: for subnet in lbr_subnets: - if "ocid1.subnet.oc1" in subnet: - lbr_subnets_list.append(str(subnet).strip()) - else: - try: - key = region, str(subnet).strip() - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - lbr_subnets_list.append(subnets.vcn_subnet_map[key][2]) - except Exception as e: - print("Invalid Subnet Name specified for row " + str(i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + columnvalue=subnet + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" + vcn_name = "" + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - tempdict = {'network_compartment_tf_name': commonTools.check_tf_variable(network_compartment_id), 'vcn_name': vcn_name,'lbr_subnets': json.dumps(lbr_subnets_list) } + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + lbr_subnets_list.append(subnet_id) + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name,'lbr_subnets': json.dumps(lbr_subnets_list)} if columnname == "NSGs": if columnvalue != '': @@ -386,9 +406,7 @@ def certificate_templates(dfcert): finalstring = "".join([s for s in finalstring.strip().splitlines(True) if s.strip("\r\n").strip()]) if finalstring != "": - resource = sheetName.lower() srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, lb_auto_tfvars_filename) # Write to TF file outfile = srcdir + lb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_nlb_listener.py b/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_nlb_listener.py index d03faf8c6..d6d5406ff 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_nlb_listener.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/create_terraform_nlb_listener.py @@ -48,10 +48,13 @@ def create_terraform_nlb_listener(inputfile, outdir, service_dir, prefix, ct): reserved_ips_str[reg] = '' nlb_listener_str[reg] = '' nlb_names[reg] = [] + resource = sheetName.lower() + srcdir = outdir + "/" + reg + "/" + service_dir + "/" + commonTools.backup_file(srcdir, resource, nlb_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) prevreg = '' for i in df.index: @@ -76,18 +79,18 @@ def create_terraform_nlb_listener(inputfile, outdir, service_dir, prefix, ct): empty_nlb = 1 #NLB having multiple Listeners can't have null values for listener properties - elif (str(df.loc[i, 'Region']).lower() == 'nan') and (str(df.loc[i, 'Compartment Name']).lower() == 'nan') and (str(df.loc[i, 'NLB Name']).lower() == 'nan') and (str(df.loc[i, 'Subnet Name']).lower() == 'nan'): + elif (str(df.loc[i, 'Region']).lower() == 'nan') and (str(df.loc[i, 'Compartment Name']).lower() == 'nan') and (str(df.loc[i, 'NLB Name']).lower() == 'nan') and (str(df.loc[i, 'Network Details']).lower() == 'nan'): if (str(df.loc[i, 'Listener Name']).lower() == 'nan') or (str(df.loc[i, 'Listener Protocol(UDP|TCP|UDP/TCP|Any)']).lower() == 'nan') or (str(df.loc[i, 'Listener Port']).lower() == 'nan') or (str(df.loc[i, 'Backend Set Name']).lower() == 'nan'): print("\nColumns Backend Set Name, Listener Name, Listener Protocol and Listener Port cannot be left empty.....Exiting! Check Row No "+(str(i+3))) exit(1) - elif (str(df.loc[i, 'Region']).lower() != 'nan') and (str(df.loc[i, 'Compartment Name']).lower() != 'nan') and (str(df.loc[i, 'NLB Name']).lower() != 'nan') and (str(df.loc[i, 'Subnet Name']).lower() != 'nan'): + elif (str(df.loc[i, 'Region']).lower() != 'nan') and (str(df.loc[i, 'Compartment Name']).lower() != 'nan') and (str(df.loc[i, 'NLB Name']).lower() != 'nan') and (str(df.loc[i, 'Network Details']).lower() != 'nan'): if (str(df.loc[i, 'Listener Name']).lower() == 'nan') or (str(df.loc[i, 'Listener Protocol(UDP|TCP|UDP/TCP|Any)']).lower() == 'nan') or (str(df.loc[i, 'Listener Port']).lower() == 'nan') or (str(df.loc[i, 'Backend Set Name']).lower() == 'nan'): print("\nColumns Backend Set Name, Listener Name, Listener Protocol and Listener Port cannot be left empty.....Exiting! Check Row No " + (str(i + 3))) exit(1) elif (str(df.loc[i, 'Listener Name']).lower() != 'nan') and (str(df.loc[i, 'Listener Protocol(UDP|TCP|UDP/TCP|Any)']).lower() != 'nan') and (str(df.loc[i, 'Listener Port']).lower() != 'nan') and (str(df.loc[i, 'Backend Set Name']).lower() != 'nan'): - if (str(df.loc[i, 'Region']).lower() == 'nan') or (str(df.loc[i, 'Compartment Name']).lower() == 'nan') or (str(df.loc[i, 'NLB Name']).lower() == 'nan') or (str(df.loc[i, 'Subnet Name']).lower() == 'nan'): - print("\nColumns Region, Compartment Name, NLB Name and Subnet Name cannot be left empty.....Exiting! Check Row No "+(str(i+3))) + if (str(df.loc[i, 'Region']).lower() == 'nan') or (str(df.loc[i, 'Compartment Name']).lower() == 'nan') or (str(df.loc[i, 'NLB Name']).lower() == 'nan') or (str(df.loc[i, 'Network Details']).lower() == 'nan'): + print("\nColumns Region, Compartment Name, NLB Name and Network Details cannot be left empty.....Exiting! Check Row No "+(str(i+3))) exit(1) # temporary dictionaries @@ -130,26 +133,31 @@ def create_terraform_nlb_listener(inputfile, outdir, service_dir, prefix, ct): nlb_tf_name = commonTools.check_tf_variable(columnvalue) tempdict = {'nlb_tf_name': nlb_tf_name, 'nlb_name': nlb_name} + subnet_id = '' network_compartment_id = '' vcn_name = '' - if columnname == 'Subnet Name': - subnet_tf_name = str(columnvalue).strip() - if subnet_tf_name == 'nan' or subnet_tf_name == '': - continue - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + if columnname == 'Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str(i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable( + str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - tempdict = {'network_compartment_tf_name': commonTools.check_tf_variable(network_compartment_id), 'vcn_name': vcn_name,'subnet_id': subnet_id} + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_tf_name': network_compartment_id, 'vcn_name': vcn_name, + 'subnet_id': subnet_id} if columnname == "NSGs": if columnvalue != '' and columnvalue != 'nan': @@ -221,9 +229,7 @@ def create_terraform_nlb_listener(inputfile, outdir, service_dir, prefix, ct): finalstring = "".join([s for s in finalstring.strip().splitlines(True) if s.strip("\r\n").strip()]) if finalstring != "": - resource = sheetName.lower() srcdir = outdir + "/" + reg + "/" + service_dir + "/" - commonTools.backup_file(srcdir, resource, nlb_auto_tfvars_filename) # Write to TF file outfile = srcdir + nlb_auto_tfvars_filename diff --git a/cd3_automation_toolkit/Network/LoadBalancers/export_lbr_nonGreenField.py b/cd3_automation_toolkit/Network/LoadBalancers/export_lbr_nonGreenField.py index dfd120722..4466568a7 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/export_lbr_nonGreenField.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/export_lbr_nonGreenField.py @@ -10,21 +10,25 @@ import sys import oci import os +import subprocess as sp from oci.certificates import CertificatesClient from oci.core.virtual_network_client import VirtualNetworkClient from oci.load_balancer.load_balancer_client import LoadBalancerClient -sys.path.append(os.getcwd()+"/..") + +sys.path.append(os.getcwd() + "/..") from commonTools import * importCommands = {} oci_obj_names = {} + def cookie_headers(values_for_column, session_persistence, excel_header_map): for headers in values_for_column: if headers == 'Cookie Name': if (session_persistence.__getattribute__(commonTools.check_column_headers(headers))): - values_for_column[headers].append(str(session_persistence.__getattribute__(commonTools.check_column_headers(headers)))) + values_for_column[headers].append( + str(session_persistence.__getattribute__(commonTools.check_column_headers(headers)))) else: values_for_column[headers].append("") @@ -47,6 +51,7 @@ def cookie_headers(values_for_column, session_persistence, excel_header_map): values_for_column[headers].append("") return values_for_column + def common_headers(region, headers, values_for_column, eachlbr, excel_header_map, lbr_compartment_name): if headers == 'Region': values_for_column[headers].append(str(region)) @@ -63,82 +68,84 @@ def common_headers(region, headers, values_for_column, eachlbr, excel_header_map pass return values_for_column -def print_certs(obj, reg, outdir,service_dir): +def print_certs(obj, reg, outdir, service_dir): cname = "" pname = "" ca_certificate = obj.ca_certificate public_certificate = obj.public_certificate - #print(obj.certificate_name, outdir, reg) + # print(obj.certificate_name, outdir, reg) if str(ca_certificate).lower() != "none": - cname = outdir + "/" + str(reg).lower() + "/"+ service_dir +"/" + str(obj.certificate_name) + "-ca-certificate.cert" + cname = outdir + "/" + str(reg).lower() + "/" + service_dir + "/" + str( + obj.certificate_name) + "-ca-certificate.cert" ca_cert = open(cname, "w") ca_cert.write(ca_certificate) ca_cert.close() if str(public_certificate).lower() != "none": - pname = outdir + "/" + str(reg).lower() + "/"+ service_dir +"/" + str(obj.certificate_name) + "-public_certificate.cert" + pname = outdir + "/" + str(reg).lower() + "/" + service_dir + "/" + str( + obj.certificate_name) + "-public_certificate.cert" public_cert = open(pname, "w") public_cert.write(public_certificate) public_cert.close() cert_name = obj.certificate_name - ca_cert = str(cname)#.replace("\\", "\\\\") - public_cert = str(pname)#.replace("\\", "\\\\") + ca_cert = str(cname) # .replace("\\", "\\\\") + public_cert = str(pname) # .replace("\\", "\\\\") return cert_name, ca_cert, public_cert -def insert_values(values_for_column, oci_objs, sheet_dict, region,comp_name, display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnets, nsgs, reserved_ip, hostnames, cert_name, ca_cert, +def insert_values(values_for_column, oci_objs, sheet_dict, region, comp_name, display_name, minimum_bandwidth_in_mbps, + maximum_bandwidth_in_mbps, subnets, nsgs, reserved_ip, hostnames, cert_name, ca_cert, passphrase, privatekey, public_cert, cipher_name, cipher_suites): - for col_header in values_for_column.keys(): - if col_header == 'Region': - values_for_column[col_header].append(str(region)) - elif col_header == 'Compartment Name': - values_for_column[col_header].append(comp_name) - elif col_header == 'LBR Name': - values_for_column[col_header].append(display_name) - elif col_header == "LBR Subnets": - values_for_column[col_header].append(subnets) - elif (col_header == "NSGs"): - values_for_column[col_header].append(nsgs) - elif (col_header == "Reserved IP (Y|N|OCID)"): - values_for_column[col_header].append(reserved_ip) - elif (col_header == 'LBR Hostname(Name:Hostname)'): - values_for_column[col_header].append(hostnames) - elif col_header == 'Certificate Name': - values_for_column[col_header].append(cert_name) - elif col_header == 'CA Cert': - values_for_column[col_header].append(ca_cert) - elif col_header == 'Passphrase': - values_for_column[col_header].append(passphrase) - elif col_header == 'Private Key': - values_for_column[col_header].append(privatekey) - elif col_header == 'Public Cert': - values_for_column[col_header].append(public_cert) - elif col_header == 'Cipher Suite Name': - values_for_column[col_header].append(cipher_name) - elif col_header == 'Ciphers': - values_for_column[col_header].append(cipher_suites) - elif col_header == 'Minimum Bandwidth In Mbps (Flexible shapes only)': - values_for_column[col_header].append(minimum_bandwidth_in_mbps) - elif col_header == 'Maximum Bandwidth In Mbps (Flexible shapes only)': - values_for_column[col_header].append(maximum_bandwidth_in_mbps) - elif col_header.lower() in commonTools.tagColumns: - values_for_column = commonTools.export_tags(oci_objs[0], col_header, values_for_column) - else: - values_for_column = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict, values_for_column) - + if col_header == 'Region': + values_for_column[col_header].append(str(region)) + elif col_header == 'Compartment Name': + values_for_column[col_header].append(comp_name) + elif col_header == 'LBR Name': + values_for_column[col_header].append(display_name) + elif col_header == "Network Details": + values_for_column[col_header].append(subnets) + elif (col_header == "NSGs"): + values_for_column[col_header].append(nsgs) + elif (col_header == "Reserved IP (Y|N|OCID)"): + values_for_column[col_header].append(reserved_ip) + elif (col_header == 'LBR Hostname(Name:Hostname)'): + values_for_column[col_header].append(hostnames) + elif col_header == 'Certificate Name': + values_for_column[col_header].append(cert_name) + elif col_header == 'CA Cert': + values_for_column[col_header].append(ca_cert) + elif col_header == 'Passphrase': + values_for_column[col_header].append(passphrase) + elif col_header == 'Private Key': + values_for_column[col_header].append(privatekey) + elif col_header == 'Public Cert': + values_for_column[col_header].append(public_cert) + elif col_header == 'Cipher Suite Name': + values_for_column[col_header].append(cipher_name) + elif col_header == 'Ciphers': + values_for_column[col_header].append(cipher_suites) + elif col_header == 'Minimum Bandwidth In Mbps (Flexible shapes only)': + values_for_column[col_header].append(minimum_bandwidth_in_mbps) + elif col_header == 'Maximum Bandwidth In Mbps (Flexible shapes only)': + values_for_column[col_header].append(maximum_bandwidth_in_mbps) + elif col_header.lower() in commonTools.tagColumns: + values_for_column = commonTools.export_tags(oci_objs[0], col_header, values_for_column) + else: + values_for_column = commonTools.export_extra_columns(oci_objs, col_header, sheet_dict, values_for_column) -def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBRs, lbr_compartment_name, network,service_dir): +def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBRs, lbr_compartment_name, network, + service_dir): for eachlbr in LBRs.data: - #Fetch LBR Name + # Fetch LBR Name display_name = eachlbr.display_name # Filter out the LBs provisioned by oke @@ -158,30 +165,30 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR else: reserved_ip = ips.reserved_ip.id - #Fetch Network Compartment Name - #Fetch Compartment Name + # Fetch Network Compartment Name + # Fetch Compartment Name lbr_comp_id = eachlbr.compartment_id comp_done_ids = [] - for comp_name,comp_id in ct.ntk_compartment_ids.items(): + for comp_name, comp_id in ct.ntk_compartment_ids.items(): if lbr_comp_id == comp_id and lbr_comp_id not in comp_done_ids: lbr_compartment_name = comp_name comp_done_ids.append(lbr_comp_id) - #Fetch hostname + # Fetch hostname hostname_name_list = '' - if(eachlbr.hostnames): + if (eachlbr.hostnames): for hostname in eachlbr.hostnames: hostname_info = lbr.get_hostname(eachlbr.id, hostname).data value = hostname_info.name + ":" + hostname_info.hostname - hostname_name_list = hostname_name_list +','+value + hostname_name_list = hostname_name_list + ',' + value if (hostname_name_list != "" and hostname_name_list[0] == ','): hostname_name_list = hostname_name_list.lstrip(',') - #Fetch NSGs + # Fetch NSGs nsg_detail = "" - #if eachlbr.network_security_group_ids: + # if eachlbr.network_security_group_ids: for nsg_id in eachlbr.network_security_group_ids: - #for nsgs in NSGs.data: + # for nsgs in NSGs.data: # id = nsgs.id # if nsg_ids == id: # nsg_name = nsgs.display_name + "," + nsg_name @@ -193,7 +200,7 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR nsg_name = nsg_detail - #Fetch Subnets + # Fetch Subnets subnet_name_list = "" if eachlbr.subnet_ids: for subnet_id in eachlbr.subnet_ids: @@ -202,7 +209,14 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR vcn_id = subnet_info.data.vcn_id vcn_info = network.get_vcn(vcn_id=vcn_id) vcn_name = vcn_info.data.display_name - vs = vcn_name + "_" + subnet_name + + ntk_compartment_id = network.get_vcn(subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = lbr_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + vs = network_compartment_name + "@" + vcn_name + "::" + subnet_name subnet_name_list = subnet_name_list + ',' + vs if (subnet_name_list != "" and subnet_name_list[0] == ','): subnet_name_list = subnet_name_list.lstrip(',') @@ -215,19 +229,21 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR maximum_bandwidth_in_mbps = eachlbr.shape_details.maximum_bandwidth_in_mbps minimum_bandwidth_in_mbps = eachlbr.shape_details.minimum_bandwidth_in_mbps - #Loops for fetching Certificates and Cipher Suites + # Loops for fetching Certificates and Cipher Suites ciphers = eachlbr.ssl_cipher_suites certs = eachlbr.certificates cert_ct = 0 cipher_ct = 0 no_of_certs = '' no_of_ciphers = '' - cipher_list =[] + cipher_list = [] certificate_list = [] if (not certs and not ciphers): oci_objs = [eachlbr] - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name,display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, hostname_name_list, '', '', '', '', '','','') + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, display_name, + minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, + hostname_name_list, '', '', '', '', '', '', '') elif (not certs and ciphers): oci_objs = [eachlbr, ciphers] @@ -245,28 +261,36 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR cipher_ct = cipher_ct + 1 if (cipher_ct == 1): - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, hostname_name_list, '','','','','',cipher_name,cipher_suites) + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, + display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, + nsg_name, reserved_ip, hostname_name_list, '', '', '', '', '', cipher_name, + cipher_suites) else: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc,'','','','','','','','','','','','','','', cipher_name,cipher_suites) + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', '', '', '', '', '', '', + '', '', '', '', '', cipher_name, cipher_suites) elif (certs and not ciphers): oci_objs = [eachlbr, certs] for certificates, details in certs.items(): # Get cert info - cert_name,ca_cert,public_cert = print_certs(details,region,outdir,service_dir) + cert_name, ca_cert, public_cert = print_certs(details, region, outdir, service_dir) cert_ct = cert_ct + 1 if (cert_ct == 1): - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name,display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, hostname_name_list, cert_name,ca_cert,'','',public_cert, '','') + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, + display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, + nsg_name, reserved_ip, hostname_name_list, cert_name, ca_cert, '', '', public_cert, + '', '') else: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc,'','','','','','','','','', cert_name,ca_cert,'','',public_cert, '','') + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', '', '', '', '', '', '', + cert_name, ca_cert, '', '', public_cert, '', '') elif (certs and ciphers): oci_objs = [eachlbr, certs, ciphers] - #Check the number of certs and ciphers; consider largest count for loop - for certificates,cert_details in certs.items(): + # Check the number of certs and ciphers; consider largest count for loop + for certificates, cert_details in certs.items(): certificate_list.append(certificates) no_of_certs = len(certificate_list) @@ -291,19 +315,24 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR j = 0 for cert, cert_details in certs.items(): if i == j: - #Insert values of certs and cipher till they are equal - cert_name, ca_cert, public_cert = print_certs(cert_details, region, outdir,service_dir) + # Insert values of certs and cipher till they are equal + cert_name, ca_cert, public_cert = print_certs(cert_details, region, outdir, service_dir) if i != 0: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '','','', - '', '', '', '','', + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', + '', '', '', '', '', '', cert_name, ca_cert, '', '', public_cert, cipher_name, cipher_suites) else: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, hostname_name_list, cert_name, ca_cert, '', '', public_cert, cipher_name, cipher_suites) + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, + lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, + maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, + hostname_name_list, cert_name, ca_cert, '', '', public_cert, + cipher_name, cipher_suites) elif i >= no_of_certs and j == no_of_certs - 1: - #Insert additional values of cipher; as count of cipher is more - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '','','','','','','','','','', '','', '', '', cipher_name, cipher_suites) + # Insert additional values of cipher; as count of cipher is more + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', '', '', '', + '', '', '', '', '', '', '', '', cipher_name, cipher_suites) else: pass j = j + 1 @@ -317,7 +346,7 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR else: for cert, cert_details in certs.items(): # Fetch Cert values - cert_name, ca_cert, public_cert = print_certs(cert_details, region, outdir,service_dir) + cert_name, ca_cert, public_cert = print_certs(cert_details, region, outdir, service_dir) j = 0 for cipher, cipher_details in ciphers.items(): cipher_suites = '' @@ -329,15 +358,20 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR cipher_suites = cipher_suites.lstrip(',') cipher_name = cipher_details.name if i != 0: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc,'','','','', + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', '', '', '', '', '', '', cert_name, ca_cert, '', '', public_cert, cipher_name, cipher_suites) else: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, hostname_name_list, cert_name, ca_cert, '', '', public_cert, cipher_name, cipher_suites) + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, + lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, + maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, + hostname_name_list, cert_name, ca_cert, '', '', public_cert, + cipher_name, cipher_suites) elif i >= no_of_ciphers and j == no_of_ciphers - 1: - #Insert additional values of certs; as count of certs is more - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '','','','','','','','','',cert_name, ca_cert, '', '', public_cert, '', '') + # Insert additional values of certs; as count of certs is more + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', '', '', '', + '', '', '', cert_name, ca_cert, '', '', public_cert, '', '') else: pass j = j + 1 @@ -345,7 +379,7 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR # if both are equal, loop through one of them as main; other as secondary elif no_of_certs == no_of_ciphers: - i=0 + i = 0 if i == no_of_ciphers: break else: @@ -360,20 +394,25 @@ def print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBR j = 0 for cert, cert_details in certs.items(): if i == j: - cert_name, ca_cert, public_cert = print_certs(cert_details, region, outdir,service_dir) + cert_name, ca_cert, public_cert = print_certs(cert_details, region, outdir, service_dir) if i != 0: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '','','','', + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, '', '', '', '', '', '', '', '', '', cert_name, ca_cert, '', '', public_cert, cipher_name, cipher_suites) else: - insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, hostname_name_list, cert_name, ca_cert, '','', public_cert, cipher_name, cipher_suites) + insert_values(values_for_column_lhc, oci_objs, sheet_dict_lhc, region, + lbr_compartment_name, display_name, minimum_bandwidth_in_mbps, + maximum_bandwidth_in_mbps, subnet_name_list, nsg_name, reserved_ip, + hostname_name_list, cert_name, ca_cert, '', '', public_cert, + cipher_name, cipher_suites) j = j + 1 i = i + 1 return values_for_column_lhc + def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, lbr_compartment_name): - certs = CertificatesClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) + certs = CertificatesClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) for eachlbr in LBRs.data: @@ -387,10 +426,10 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, # Loop through Backend Sets - #Fetch Compartment Name + # Fetch Compartment Name lbr_comp_id = eachlbr.compartment_id comp_done_ids = [] - for comp_name,comp_id in ct.ntk_compartment_ids.items(): + for comp_name, comp_id in ct.ntk_compartment_ids.items(): if lbr_comp_id == comp_id and lbr_comp_id not in comp_done_ids: lbr_compartment_name = comp_name comp_done_ids.append(lbr_comp_id) @@ -401,34 +440,35 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, backendset_details = lbr.get_backend_set(eachlbr.__getattribute__('id'), backendsets).data certificate_list = '' hc = '' - # Process the Backend Server and Backup server details for backends in backendset_details.__getattribute__('backends'): if str(backends.__getattribute__('name')).lower() != "none": backend_value = str(backends.__getattribute__('name')) - backend_list= backend_list+","+"&"+backend_value + backend_list = backend_list + "," + backend_value if (backend_list != "" and backend_list[0] == ','): backend_list = backend_list.lstrip(',') if str(backends.__getattribute__('backup')).lower() == 'true': backup_value = backends.ip_address - backup_list = backup_list +',' +backup_value + backup_list = backup_list + ',' + backup_value if (backup_list != "" and backup_list[0] == ','): backup_list = backup_list.lstrip(',') - # Process columns related to Session Cookies - lb_cookie_session_persistence_configuration = backendset_details.__getattribute__('lb_cookie_session_persistence_configuration') + lb_cookie_session_persistence_configuration = backendset_details.__getattribute__( + 'lb_cookie_session_persistence_configuration') session_persistence_configuration = backendset_details.__getattribute__('session_persistence_configuration') if str(lb_cookie_session_persistence_configuration).lower() != 'none': lb_session = 'LB' values_for_column_bss['Cookie Session(n|LB|Backend Server)'].append(lb_session) - values_for_column_bss = cookie_headers(values_for_column_bss, lb_cookie_session_persistence_configuration, sheet_dict_bss) + values_for_column_bss = cookie_headers(values_for_column_bss, + lb_cookie_session_persistence_configuration, sheet_dict_bss) elif str(session_persistence_configuration).lower() != 'none': lb_session = 'Backend Server' values_for_column_bss['Cookie Session(n|LB|Backend Server)'].append(lb_session) - values_for_column_bss = cookie_headers(values_for_column_bss, session_persistence_configuration, sheet_dict_bss) + values_for_column_bss = cookie_headers(values_for_column_bss, session_persistence_configuration, + sheet_dict_bss) else: lb_session = 'n' @@ -442,7 +482,8 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, # Process Columns that are common across LBR sheets - Region, Compartment Name and LBR Name if col_headers in sheet_dict_common.keys(): - values_for_column_bss = common_headers(region, col_headers, values_for_column_bss, eachlbr, sheet_dict_common,lbr_compartment_name) + values_for_column_bss = common_headers(region, col_headers, values_for_column_bss, eachlbr, + sheet_dict_common, lbr_compartment_name) # Process the Tag Columns elif headers_lower in commonTools.tagColumns: @@ -455,7 +496,7 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, values_for_column_bss[col_headers].append("") else: for protocols in certificate_list.protocols: - protocols_list = protocols_list+","+protocols + protocols_list = protocols_list + "," + protocols if (protocols_list != "" and protocols_list[0] == ','): protocols_list = protocols_list.lstrip(',') values_for_column_bss[col_headers].append(protocols_list) @@ -466,12 +507,13 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, if col_headers == "Backend Policy(LEAST_CONNECTIONS|ROUND_ROBIN|IP_HASH)": policy = backendset_details.__getattribute__(sheet_dict_bss[col_headers]) - values_for_column_bss['Backend Policy(LEAST_CONNECTIONS|ROUND_ROBIN|IP_HASH)'].append(str(policy)) + values_for_column_bss['Backend Policy(LEAST_CONNECTIONS|ROUND_ROBIN|IP_HASH)'].append( + str(policy)) elif 'Backend HealthCheck' in col_headers: values_for_column_bss[col_headers].append(hc.__getattribute__(sheet_dict_bss[col_headers])) - elif col_headers == "Backend ServerComp&ServerName:Port": + elif col_headers == "Backend ServerComp@ServerName:Port": values_for_column_bss[col_headers].append(backend_list) elif col_headers == "Backend Set Name": @@ -484,8 +526,10 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, certificates = "" for certificate_ids in certificate_list.certificate_ids: certificates = certificates + "," + certificate_ids - values_for_column_bss[col_headers].append(str(certificate_list.certificate_ids).lstrip(",")) - elif certificate_list.certificate_name != "" and str(certificate_list.certificate_name).lower() != "none": + values_for_column_bss[col_headers].append( + str(certificate_list.certificate_ids).lstrip(",")) + elif certificate_list.certificate_name != "" and str( + certificate_list.certificate_name).lower() != "none": values_for_column_bss[col_headers].append(certificate_list.certificate_name) else: values_for_column_bss[col_headers].append("") @@ -515,14 +559,16 @@ def print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, continue else: - oci_objs = [backendset_details,eachlbr,hc,certificate_list] - values_for_column_bss = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_bss,values_for_column_bss) + oci_objs = [backendset_details, eachlbr, hc, certificate_list] + values_for_column_bss = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_bss, + values_for_column_bss) else: if "Cookie" not in col_headers: # Process the remaining Columns - oci_objs = [backendset_details,eachlbr,hc,certificate_list] - values_for_column_bss = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_bss,values_for_column_bss) + oci_objs = [backendset_details, eachlbr, hc, certificate_list] + values_for_column_bss = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_bss, + values_for_column_bss) return values_for_column_bss @@ -539,10 +585,10 @@ def print_listener(region, ct, values_for_column_lis, LBRs, lbr_compartment_name if 'ocid1.cluster' in created_by: continue - #Fetch Compartment Name + # Fetch Compartment Name lbr_comp_id = eachlbr.compartment_id comp_done_ids = [] - for comp_name,comp_id in ct.ntk_compartment_ids.items(): + for comp_name, comp_id in ct.ntk_compartment_ids.items(): if lbr_comp_id == comp_id and lbr_comp_id not in comp_done_ids: lbr_compartment_name = comp_name comp_done_ids.append(lbr_comp_id) @@ -556,9 +602,10 @@ def print_listener(region, ct, values_for_column_lis, LBRs, lbr_compartment_name if col_headers == 'Certificate Name or OCID': sslcerts = values.__getattribute__(sheet_dict_lis['UseSSL (y|n)']) if str(sslcerts).lower() != "none": - if sslcerts.__getattribute__('certificate_name') != "" and str(sslcerts.__getattribute__('certificate_name')).lower() != "none": + if sslcerts.__getattribute__('certificate_name') != "" and str( + sslcerts.__getattribute__('certificate_name')).lower() != "none": values_for_column_lis[col_headers].append(sslcerts.__getattribute__('certificate_name')) - elif sslcerts.certificate_ids != [] : + elif sslcerts.certificate_ids != []: certificates = "" for certificate_ids in sslcerts.certificate_ids: certificates = certificates + "," + certificate_ids @@ -586,14 +633,15 @@ def print_listener(region, ct, values_for_column_lis, LBRs, lbr_compartment_name values_for_column_lis[col_headers].append("") else: for protocols in sslcerts.protocols: - protocols_list = protocols_list+","+protocols + protocols_list = protocols_list + "," + protocols if (protocols_list != "" and protocols_list[0] == ','): protocols_list = protocols_list.lstrip(',') values_for_column_lis[col_headers].append(protocols_list) # Process Columns that are common across LBR sheets - Region, Compartment Name and LBR Name elif col_headers in sheet_dict_common.keys(): - values_for_column_lis = common_headers(region, col_headers, values_for_column_lis, eachlbr, sheet_dict_common, lbr_compartment_name) + values_for_column_lis = common_headers(region, col_headers, values_for_column_lis, eachlbr, + sheet_dict_common, lbr_compartment_name) # Process the Tag Columns elif headers_lower in commonTools.tagColumns: @@ -605,7 +653,7 @@ def print_listener(region, ct, values_for_column_lis, LBRs, lbr_compartment_name rule_str = "" if values.__getattribute__(sheet_dict_lis[col_headers]) != []: for rule in values.__getattribute__(sheet_dict_lis[col_headers]): - rule_str = rule_str +","+rule + rule_str = rule_str + "," + rule if (rule_str != "" and rule_str[0] == ','): rule_str = rule_str.lstrip(',') values_for_column_lis[col_headers].append(rule_str) @@ -617,28 +665,32 @@ def print_listener(region, ct, values_for_column_lis, LBRs, lbr_compartment_name values_for_column_lis[col_headers].append("n") elif col_headers == "LBR Hostnames (Name)": - hostnames="" + hostnames = "" if values.__getattribute__(sheet_dict_lis[col_headers]): for eachhostname in values.__getattribute__(sheet_dict_lis[col_headers]): - hostnames = hostnames+","+eachhostname + hostnames = hostnames + "," + eachhostname if (hostnames != "" and hostnames[0] == ','): hostnames = hostnames.lstrip(',') values_for_column_lis[col_headers].append(hostnames) elif col_headers == 'Idle Time Out (in Seconds)': connection_config = values.__getattribute__('connection_configuration') - values_for_column_lis[col_headers].append(connection_config.__getattribute__(sheet_dict_lis[col_headers])) + values_for_column_lis[col_headers].append( + connection_config.__getattribute__(sheet_dict_lis[col_headers])) else: - oci_objs = [values,eachlbr,sslcerts] - values_for_column_lis = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_lis, values_for_column_lis) + oci_objs = [values, eachlbr, sslcerts] + values_for_column_lis = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_lis, + values_for_column_lis) else: - oci_objs = [eachlbr,values,sslcerts] - values_for_column_lis = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_lis, values_for_column_lis) + oci_objs = [eachlbr, values, sslcerts] + values_for_column_lis = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_lis, + values_for_column_lis) return values_for_column_lis + def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): for eachlbr in LBRs.data: @@ -650,11 +702,10 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): if 'ocid1.cluster' in created_by: continue - - #Fetch Compartment Name + # Fetch Compartment Name lbr_comp_id = eachlbr.compartment_id comp_done_ids = [] - for comp_name,comp_id in ct.ntk_compartment_ids.items(): + for comp_name, comp_id in ct.ntk_compartment_ids.items(): if lbr_comp_id == comp_id and lbr_comp_id not in comp_done_ids: lbr_compartment_name = comp_name comp_done_ids.append(lbr_comp_id) @@ -665,7 +716,8 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): headers_lower = commonTools.check_column_headers(col_headers) if col_headers in sheet_dict_common.keys(): - values_for_column_rule = common_headers(region, col_headers, values_for_column_rule, eachlbr,sheet_dict_common, lbr_compartment_name) + values_for_column_rule = common_headers(region, col_headers, values_for_column_rule, eachlbr, + sheet_dict_common, lbr_compartment_name) elif col_headers == 'Rule Set Name': values_for_column_rule[col_headers].append(rulesets) @@ -686,11 +738,11 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): uri_details.query = '' if 'Host:Port' in col_headers: - value = uri_details.host+":"+str(uri_details.port) + value = uri_details.host + ":" + str(uri_details.port) values_for_column_rule[col_headers].append(value) if 'Protocol:Path' in col_headers: - value = uri_details.protocol+":"+uri_details.path + value = uri_details.protocol + ":" + uri_details.path values_for_column_rule[col_headers].append(value) if 'Query' in col_headers: @@ -699,7 +751,7 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): else: value = str(eachitem.__getattribute__(sheet_dict_rule[col_headers])) if value.lower() == 'none': - value="" + value = "" values_for_column_rule[col_headers].append(value) except AttributeError as e: @@ -710,7 +762,7 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): allowed_method = '' if eachitem.action == "CONTROL_ACCESS_USING_HTTP_METHODS": for method in eachitem.__getattribute__(headers_lower): - allowed_method = allowed_method +",\"" + method + "\"" + allowed_method = allowed_method + ",\"" + method + "\"" if (allowed_method != "" and allowed_method[0] == ','): allowed_method = allowed_method.lstrip(',') @@ -722,7 +774,7 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): for attributes in eachitem.conditions: values_for_column_rule[col_headers].append(attributes.__getattribute__(headers_lower)) except AttributeError as e: - values_for_column_rule[col_headers].append("") + values_for_column_rule[col_headers].append("") elif 'Operator' in col_headers: try: @@ -732,8 +784,8 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): values_for_column_rule[col_headers].append("") elif col_headers == "Suffix or Prefix (suffix:|prefix:)": - combined_suffix='' - combined_prefix='' + combined_suffix = '' + combined_prefix = '' try: suffix_val = eachitem.suffix if suffix_val != "" and suffix_val != 'nan' and suffix_val != None: @@ -748,11 +800,13 @@ def print_rule(region, ct, values_for_column_rule, LBRs, lbr_compartment_name): pass else: oci_objs = [eachlbr, eachitem] - values_for_column_rule = commonTools.export_extra_columns(oci_objs, col_headers, sheet_dict_rule, - values_for_column_rule) + values_for_column_rule = commonTools.export_extra_columns(oci_objs, col_headers, + sheet_dict_rule, + values_for_column_rule) return values_for_column_rule + def print_prs(region, ct, values_for_column_prs, LBRs, lbr_compartment_name): for eachlbr in LBRs.data: @@ -764,23 +818,24 @@ def print_prs(region, ct, values_for_column_prs, LBRs, lbr_compartment_name): if 'ocid1.cluster' in created_by: continue - #Fetch Compartment Name + # Fetch Compartment Name lbr_comp_id = eachlbr.compartment_id comp_done_ids = [] - for comp_name,comp_id in ct.ntk_compartment_ids.items(): + for comp_name, comp_id in ct.ntk_compartment_ids.items(): if lbr_comp_id == comp_id and lbr_comp_id not in comp_done_ids: lbr_compartment_name = comp_name comp_done_ids.append(lbr_comp_id) - for prs,values in eachlbr.__getattribute__('path_route_sets').items(): + for prs, values in eachlbr.__getattribute__('path_route_sets').items(): for path_routes in values.__getattribute__('path_routes'): for col_headers in values_for_column_prs.keys(): headers_lower = commonTools.check_column_headers(col_headers) if col_headers in sheet_dict_common.keys(): - values_for_column_prs = common_headers(region, col_headers, values_for_column_prs, eachlbr,sheet_dict_common, lbr_compartment_name) + values_for_column_prs = common_headers(region, col_headers, values_for_column_prs, eachlbr, + sheet_dict_common, lbr_compartment_name) elif col_headers == 'Match Type': try: - key = path_routes.__getattribute__('path_match_type') + key = path_routes.__getattribute__('path_match_type') match_type = key.match_type values_for_column_prs[col_headers].append(match_type) except AttributeError as e: @@ -796,8 +851,68 @@ def print_prs(region, ct, values_for_column_prs, LBRs, lbr_compartment_name): values_for_column_prs) return values_for_column_prs + + +def print_routing_policies(region, ct, values_for_column_rp, LBRs, lbr_compartment_name): + for eachlbr in LBRs.data: + # Retrieve the routing policies for the load balancer + routing_policies = eachlbr.routing_policies + + # Filter out the LBs provisioned by OKE + eachlbr_defined_tags = eachlbr.defined_tags + if 'Oracle-Tags' in eachlbr_defined_tags.keys(): + if 'CreatedBy' in eachlbr_defined_tags['Oracle-Tags'].keys(): + created_by = eachlbr_defined_tags['Oracle-Tags']['CreatedBy'] + if 'ocid1.cluster' in created_by: + continue + + # Fetch the compartment name + lbr_comp_id = eachlbr.compartment_id + comp_done_ids = [] + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if lbr_comp_id == comp_id and lbr_comp_id not in comp_done_ids: + # Retrieve the values for the routing policies + for rp, values in eachlbr.__getattribute__('routing_policies').items(): + for col_headers in values_for_column_rp.keys(): + headers_lower = commonTools.check_column_headers(col_headers) + + if col_headers in sheet_dict_common.keys(): + values_for_column_rp = common_headers(region, col_headers, values_for_column_rp, eachlbr, + sheet_dict_common, lbr_compartment_name) + elif col_headers == 'LBR Name': + values_for_column_rp[col_headers].append(eachlbr.display_name) + + elif col_headers == 'Routing Policy Name': + values_for_column_rp[col_headers].append(values.__getattribute__('name')) + + elif col_headers == "Rules": + rules = [] + for rule in values.rules: + if hasattr(rule, 'actions') and rule.actions and hasattr(rule.actions[0], 'backend_set_name'): + backend_set_name = rule.actions[0].backend_set_name + else: + backend_set_name = None + rule_str = f"{rule.name}::{rule.condition}::{backend_set_name}" + rules.append(rule_str) + rules_string = "\n".join(rules) + values_for_column_rp[col_headers].append(rules_string) + + elif col_headers in sheet_dict_rp.keys(): + values_for_column_rp[col_headers].append( + values.__getattribute__(sheet_dict_rp[col_headers])) + + else: + # Process the remaining Columns + oci_objs = [eachlbr, values] + values_for_column_rp = commonTools.export_extra_columns(oci_objs, col_headers, + sheet_dict_rp, + values_for_column_rp) + + return values_for_column_rp + + # Execution of the code begins here -def export_lbr(inputfile, outdir, service_dir, config1,signer1, ct, export_compartments, export_regions): +def export_lbr(inputfile, outdir, service_dir, config1, signer1, ct, export_compartments, export_regions): global tf_import_cmd global sheet_dict global importCommands @@ -809,134 +924,188 @@ def export_lbr(inputfile, outdir, service_dir, config1,signer1, ct, export_compa global values_for_column_lis global values_for_column_rule global values_for_column_prs + global values_for_column_rp global sheet_dict_common global sheet_dict_lhc global sheet_dict_bss global sheet_dict_lis global sheet_dict_rule global sheet_dict_prs + global sheet_dict_rp global listener_to_cd3 - global config,signer - signer=signer1 - config=config1 + global config, signer,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] + signer = signer1 + config = config1 cd3file = inputfile if ('.xls' not in cd3file): print("\nAcceptable cd3 format: .xlsx") exit() - # Read CD3 - df, values_for_column_lhc= commonTools.read_cd3(cd3file,"LB-Hostname-Certs") + df, values_for_column_lhc = commonTools.read_cd3(cd3file, "LB-Hostname-Certs") df, values_for_column_bss = commonTools.read_cd3(cd3file, "LB-BackendSet-BackendServer") df, values_for_column_lis = commonTools.read_cd3(cd3file, "LB-Listener") df, values_for_column_rule = commonTools.read_cd3(cd3file, "LB-RuleSet") df, values_for_column_prs = commonTools.read_cd3(cd3file, "LB-PathRouteSet") + df, values_for_column_rp = commonTools.read_cd3(cd3file, "LB-RoutingPolicy") # Get dict for columns from Excel_Columns - sheet_dict_common=ct.sheet_dict["Common-LBR-Headers"] + sheet_dict_common = ct.sheet_dict["Common-LBR-Headers"] sheet_dict_lhc = ct.sheet_dict["LB-Hostname-Certs"] sheet_dict_bss = ct.sheet_dict["LB-BackendSet-BackendServer"] sheet_dict_lis = ct.sheet_dict["LB-Listener"] sheet_dict_rule = ct.sheet_dict["LB-RuleSet"] sheet_dict_prs = ct.sheet_dict["LB-PathRouteSet"] + sheet_dict_rp = ct.sheet_dict["LB-RoutingPolicy"] print("\nCD3 excel file should not be opened during export process!!!") - print("Tabs- LB-Hostname-Certs, LB-BackendSet-BackendServer, LB-Listener, LB-RuleSet, LB-PathRouteSet will be overwritten during export process!!!\n") - - # Create backups - for reg in export_regions: - resource='tf_import_lbr' - if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_lbr_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, "tf_import_commands_lbr_nonGF.sh") - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_lbr_nonGF.sh", "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + print("Tabs- LB-Hostname-Certs, LB-BackendSet-BackendServer, LB-Listener, LB-RuleSet, LB-PathRouteSet, LB-RoutingPolicy will be overwritten during export process!!!\n") # Fetch LBR Details print("\nFetching details of Load Balancer...") + # Create backups + file_name = 'import_commands_lbr_nonGF.sh' + resource = 'import_lbr' + total_resources=0 + for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Load Balancer Objects #########\n\n") - config.__setitem__("region", ct.region_dict[reg]) - lbr = LoadBalancerClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) - network = oci.core.VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + + if os.path.exists(script_file): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + importCommands[reg] = '' + + config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass + lbr = LoadBalancerClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) + network = oci.core.VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, + signer=signer) region = reg.capitalize() for compartment_name in export_compartments: - LBRs = oci.pagination.list_call_get_all_results(lbr.list_load_balancers,compartment_id=ct.ntk_compartment_ids[compartment_name], - lifecycle_state="ACTIVE") - values_for_column_lhc = print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBRs, compartment_name, network,service_dir) - values_for_column_lis = print_listener(region, ct, values_for_column_lis,LBRs,compartment_name) - values_for_column_bss = print_backendset_backendserver(region, ct, values_for_column_bss, lbr,LBRs,compartment_name) - values_for_column_rule = print_rule(region, ct, values_for_column_rule, LBRs, compartment_name) - values_for_column_prs = print_prs(region, ct, values_for_column_prs, LBRs, compartment_name) - - for eachlbr in LBRs.data: - - # Filter out the LBs provisioned by oke - eachlbr_defined_tags = eachlbr.defined_tags - if 'Oracle-Tags' in eachlbr_defined_tags.keys(): - if 'CreatedBy' in eachlbr_defined_tags['Oracle-Tags'].keys(): - created_by = eachlbr_defined_tags['Oracle-Tags']['CreatedBy'] - if 'ocid1.cluster' in created_by: - continue - - - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_lbr_nonGF.sh", "a") - lbr_info = eachlbr - lbr_display_name = lbr_info.display_name - tf_name = commonTools.check_tf_variable(lbr_display_name) - importCommands[reg].write("\nterraform import \"module.load-balancers[\\\""+str(tf_name)+"\\\"].oci_load_balancer_load_balancer.load_balancer\" " + lbr_info.id) - - for certificates in eachlbr.certificates: - cert_tf_name = commonTools.check_tf_variable(certificates) - importCommands[reg].write("\nterraform import \"module.certificates[\\\""+str(tf_name)+"_" + str(cert_tf_name) + "_cert""\\\"].oci_load_balancer_certificate.certificate\" loadBalancers/" + lbr_info.id + "/certificates/" + certificates) - - for hostnames in eachlbr.hostnames: - hostname_tf_name = commonTools.check_tf_variable(hostnames) - importCommands[reg].write("\nterraform import \"module.hostnames[\\\""+str(tf_name)+ "_" + str(hostname_tf_name) + "_hostname""\\\"].oci_load_balancer_hostname.hostname\" loadBalancers/" + lbr_info.id + "/hostnames/" + hostnames) - - for listeners in eachlbr.listeners: - listener_tf_name = commonTools.check_tf_variable(listeners) - importCommands[reg].write("\nterraform import \"module.listeners[\\\""+str(tf_name)+"_" + str(listener_tf_name) +"\\\"].oci_load_balancer_listener.listener\" loadBalancers/" + lbr_info.id + "/listeners/" + listeners) - - for backendsets, values in eachlbr.backend_sets.items(): - backendsets_tf_name = commonTools.check_tf_variable(backendsets) - importCommands[reg].write("\nterraform import \"module.backend-sets[\\\""+str(tf_name)+"_" + str(backendsets_tf_name) +"\\\"].oci_load_balancer_backend_set.backend_set\" loadBalancers/" + lbr_info.id + "/backendSets/" + backendsets) - - cnt = 0 - for keys in values.backends: - cnt = cnt + 1 - backendservers_name = keys.name - backendservers_tf_name = commonTools.check_tf_variable(keys.ip_address+"-"+str(cnt)) - importCommands[reg].write("\nterraform import \"module.backends[\\\""+str(tf_name)+"_" + backendsets_tf_name + "_" + backendservers_tf_name +"\\\"].oci_load_balancer_backend.backend\" loadBalancers/" + lbr_info.id + "/backendSets/" + backendsets + "/backends/" + backendservers_name) - - for pathroutes in eachlbr.path_route_sets: - pathroutes_tf_name = commonTools.check_tf_variable(pathroutes) - importCommands[reg].write("\nterraform import \"module.path-route-sets[\\\""+str(tf_name)+"_" + pathroutes_tf_name +"\\\"].oci_load_balancer_path_route_set.path_route_set\" loadBalancers/" + lbr_info.id + "/pathRouteSets/" + pathroutes) - - for routerules in eachlbr.rule_sets: - routerules_tf_name = commonTools.check_tf_variable(routerules) - importCommands[reg].write("\nterraform import \"module.rule-sets[\\\""+str(tf_name)+"_" + routerules_tf_name + "\\\"].oci_load_balancer_rule_set.rule_set\" loadBalancers/" + lbr_info.id + "/ruleSets/" + routerules) - - for ciphers in eachlbr.ssl_cipher_suites: - ciphers_tf_name = commonTools.check_tf_variable(ciphers) - importCommands[reg].write("\nterraform import \"module.cipher-suites[\\\""+str(tf_name)+"_" + ciphers_tf_name +"\\\"].oci_load_balancer_ssl_cipher_suite.ssl_cipher_suite\" loadBalancers/" + lbr_info.id + "/sslCipherSuites/" + ciphers) + LBRs = oci.pagination.list_call_get_all_results(lbr.list_load_balancers, + compartment_id=ct.ntk_compartment_ids[compartment_name], + lifecycle_state="ACTIVE") + values_for_column_lhc = print_lbr_hostname_certs(region, ct, outdir, values_for_column_lhc, lbr, LBRs, + compartment_name, network, service_dir) + values_for_column_lis = print_listener(region, ct, values_for_column_lis, LBRs, compartment_name) + values_for_column_bss = print_backendset_backendserver(region, ct, values_for_column_bss, lbr, LBRs, + compartment_name) + values_for_column_rule = print_rule(region, ct, values_for_column_rule, LBRs, compartment_name) + values_for_column_prs = print_prs(region, ct, values_for_column_prs, LBRs, compartment_name) + values_for_column_rp = print_routing_policies(region, ct, values_for_column_rp, LBRs, compartment_name) + + + for eachlbr in LBRs.data: + total_resources+=1 + + # Filter out the LBs provisioned by oke + eachlbr_defined_tags = eachlbr.defined_tags + if 'Oracle-Tags' in eachlbr_defined_tags.keys(): + if 'CreatedBy' in eachlbr_defined_tags['Oracle-Tags'].keys(): + created_by = eachlbr_defined_tags['Oracle-Tags']['CreatedBy'] + if 'ocid1.cluster' in created_by: + continue + + + lbr_info = eachlbr + lbr_display_name = lbr_info.display_name + tf_name = commonTools.check_tf_variable(lbr_display_name) + tf_resource = f'module.load-balancers[\\"{tf_name}\\"].oci_load_balancer_load_balancer.load_balancer' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {lbr_info.id}' + + for certificates in eachlbr.certificates: + cert_tf_name = commonTools.check_tf_variable(certificates) + tf_resource = f'module.certificates[\\"{tf_name}_{cert_tf_name}_cert\\"].oci_load_balancer_certificate.certificate' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/certificates/{certificates}' + + for hostnames in eachlbr.hostnames: + hostname_tf_name = commonTools.check_tf_variable(hostnames) + tf_resource = f'module.hostnames[\\"{tf_name}_{hostname_tf_name}_hostname\\"].oci_load_balancer_hostname.hostname' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/hostnames/{hostnames}' + + for listeners in eachlbr.listeners: + listener_tf_name = commonTools.check_tf_variable(listeners) + tf_resource = f'module.listeners[\\"{tf_name}_{listener_tf_name}\\"].oci_load_balancer_listener.listener' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/listeners/{listeners}' + + for backendsets, values in eachlbr.backend_sets.items(): + backendsets_tf_name = commonTools.check_tf_variable(backendsets) + tf_resource = f'module.backend-sets[\\"{tf_name}_{backendsets_tf_name}\\"].oci_load_balancer_backend_set.backend_set' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/backendSets/{backendsets}' + + cnt = 0 + for keys in values.backends: + cnt = cnt + 1 + backendservers_name = keys.name + backendservers_tf_name = commonTools.check_tf_variable(keys.ip_address + "-" + str(cnt)) + tf_resource = f'module.backends[\\"{tf_name}_{backendsets_tf_name}_{backendservers_tf_name}\\"].oci_load_balancer_backend.backend' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/backendSets/{backendsets}/backends/{backendservers_name}' + + for pathroutes in eachlbr.path_route_sets: + pathroutes_tf_name = commonTools.check_tf_variable(pathroutes) + tf_resource = f'module.path-route-sets[\\"{tf_name}_{pathroutes_tf_name}\\"].oci_load_balancer_path_route_set.path_route_set' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/pathRouteSets/{pathroutes}' + + for routing_policy in eachlbr.routing_policies: + routing_policy_tf_name = commonTools.check_tf_variable(routing_policy) + tf_resource = f'module.routing-policies[\\"{tf_name}_{routing_policy_tf_name}\\"].oci_load_balancer_load_balancer_routing_policy.load_balancer_routing_policy' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/routingPolicies/{routing_policy}' + + for routerules in eachlbr.rule_sets: + routerules_tf_name = commonTools.check_tf_variable(routerules) + tf_resource = f'module.rule-sets[\\"{tf_name}_{routerules_tf_name}\\"].oci_load_balancer_rule_set.rule_set' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/ruleSets/{routerules}' + + for ciphers in eachlbr.ssl_cipher_suites: + ciphers_tf_name = commonTools.check_tf_variable(ciphers) + tf_resource = f'module.cipher-suites[\\"{tf_name}_{ciphers_tf_name}\\"].oci_load_balancer_ssl_cipher_suite.ssl_cipher_suite' + if tf_resource not in state["resources"]: + importCommands[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" loadBalancers/{lbr_info.id}/sslCipherSuites/{ciphers}' commonTools.write_to_cd3(values_for_column_lhc, cd3file, "LB-Hostname-Certs") commonTools.write_to_cd3(values_for_column_bss, cd3file, "LB-BackendSet-BackendServer") commonTools.write_to_cd3(values_for_column_lis, cd3file, "LB-Listener") - commonTools.write_to_cd3(values_for_column_rule,cd3file, "LB-RuleSet") + commonTools.write_to_cd3(values_for_column_rule, cd3file, "LB-RuleSet") commonTools.write_to_cd3(values_for_column_prs, cd3file, "LB-PathRouteSet") + commonTools.write_to_cd3(values_for_column_rp, cd3file, "LB-RoutingPolicy") - print("{0} LBRs exported into CD3.\n".format(len(values_for_column_lhc["Region"]))) - + print("{0} LBRs exported into CD3.\n".format(total_resources)) # writing data for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/tf_import_commands_lbr_nonGF.sh' - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for Load Balancer Objects #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Network/LoadBalancers/export_nlb_nonGreenField.py b/cd3_automation_toolkit/Network/LoadBalancers/export_nlb_nonGreenField.py index 1de4afadc..f71fdab27 100644 --- a/cd3_automation_toolkit/Network/LoadBalancers/export_nlb_nonGreenField.py +++ b/cd3_automation_toolkit/Network/LoadBalancers/export_nlb_nonGreenField.py @@ -10,6 +10,7 @@ import sys import oci import os +import subprocess as sp from oci.core.virtual_network_client import VirtualNetworkClient from oci.network_load_balancer import NetworkLoadBalancerClient @@ -20,7 +21,7 @@ importCommands = {} oci_obj_names = {} -def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, nlb_compartment_name,cmpt,vcn,nlb): +def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, nlb_compartment_name,cmpt,vcn,nlb,state): for eachnlb in NLBs.data: cnt_bss = 0 @@ -40,7 +41,9 @@ def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, n cnt_bss = cnt_bss + 1 backendsets_tf_name = commonTools.check_tf_variable(backendsets) - importCommands[reg].write("\nterraform import \"module.nlb-backend-sets[\\\"" + str(tf_name) + "_" + str(backendsets_tf_name) + "\\\"].oci_network_load_balancer_backend_set.backend_set\" networkLoadBalancers/" + eachnlb.id + "/backendSets/" + backendsets) + tf_resource = f'module.nlb-backend-sets[\\"{tf_name}_{backendsets_tf_name}\\"].oci_network_load_balancer_backend_set.backend_set' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkLoadBalancers/{eachnlb.id}/backendSets/{backendsets}' backend_list = "" backendset_details = nlb.get_backend_set(eachnlb.__getattribute__('id'), backendsets).data @@ -59,7 +62,12 @@ def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, n if "ocid1.privateip" in backend_value: private_ip_ocid = backend_value.split(":")[0] #port = backend_value.split(":")[1] - private_ip = vcn.get_private_ip(private_ip_ocid).data + try: + private_ip = vcn.get_private_ip(private_ip_ocid).data + except Exception as e: + print("Some issue with Backend "+backend_value+ " for NLB "+nlb_display_name+". Skipping it...") + continue + vnic_ocid = private_ip.vnic_id vnic = vcn.get_vnic(vnic_ocid).data vnic_found = 0 @@ -75,19 +83,20 @@ def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, n if vnic_found==1: break - backend = instance_comp_name+"&"+instance_display_name+":"+port + backend = instance_comp_name+"@"+instance_display_name+":"+port backend_list = backend_list + "," + backend backendservers_name = instance_display_name +"-"+str(cnt_bes) backendservers_tf_name = commonTools.check_tf_variable(backendservers_name) else: backend = backend_value - backend_list= backend_list+","+"&"+backend + backend_list= backend_list+","+backend backendservers_name = backend.split(":")[0] +"-"+str(cnt_bes) backendservers_tf_name = commonTools.check_tf_variable(backendservers_name) - - importCommands[reg].write("\nterraform import \"module.nlb-backends[\\\"" + str(tf_name) + "_" + backendsets_tf_name + "_" + backendservers_tf_name + "\\\"].oci_network_load_balancer_backend.backend\" networkLoadBalancers/" + eachnlb.id + "/backendSets/" + backendsets + "/backends/" + backend_value) + tf_resource = f'module.nlb-backends[\\"{tf_name}_{backendsets_tf_name}_{backendservers_tf_name}\\"].oci_network_load_balancer_backend.backend' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkLoadBalancers/{eachnlb.id}/backendSets/{backendsets}/backends/{backend_value}' if (backend_list != "" and backend_list[0] == ','): backend_list = backend_list.lstrip(',') @@ -123,7 +132,7 @@ def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, n elif 'Backend HealthCheck' in col_header: values_for_column_bss[col_header].append(hc.__getattribute__(sheet_dict_bss[col_header])) - elif col_header == "Backend ServerComp&ServerName:Port": + elif col_header == "Backend ServerComp@ServerName:Port": values_for_column_bss[col_header].append(backend_list) elif col_header == "Backend Set Name": @@ -135,7 +144,7 @@ def print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs, n return values_for_column_bss -def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartment_name,vcn): +def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartment_name,vcn,ct,state): for eachnlb in NLBs.data: # Filter out the NLBs provisioned by oke @@ -148,7 +157,9 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm nlb_display_name = eachnlb.display_name tf_name = commonTools.check_tf_variable(nlb_display_name) - importCommands[reg].write("\nterraform import \"module.network-load-balancers[\\\"" + str(tf_name) + "\\\"].oci_network_load_balancer_network_load_balancer.network_load_balancer\" " + eachnlb.id) + tf_resource = f'module.network-load-balancers[\\"{tf_name}\\"].oci_network_load_balancer_network_load_balancer.network_load_balancer' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {eachnlb.id}' cnt_lsnr = 0 @@ -159,8 +170,13 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm vcn_id = subnet_info.vcn_id vcn_info = vcn.get_vcn(vcn_id).data vcn_name = vcn_info.display_name + ntk_compartment_id = vcn.get_vcn(vcn_id).data.compartment_id # compartment-id + network_compartment_name = nlb_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name - subnet_detail = vcn_name + "_" + subnet_name + subnet_detail = network_compartment_name + "@" + vcn_name + "::" + subnet_name #Fetch NSGs nsg_detail = "" @@ -173,9 +189,11 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm # Fetch reserved IP address reserved_ip = "" + is_public=False if eachnlb.ip_addresses != []: for ips in eachnlb.ip_addresses: if(ips.is_public == True): + is_public=ips.is_public if str(ips.reserved_ip) == "null" or str(ips.reserved_ip) == "None": reserved_ip = "N" else: @@ -186,7 +204,9 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm cnt_lsnr = cnt_lsnr + 1 listener_tf_name = commonTools.check_tf_variable(listeners) - importCommands[reg].write("\nterraform import \"module.nlb-listeners[\\\"" + str(tf_name) + "_" + str(listener_tf_name) + "\\\"].oci_network_load_balancer_listener.listener\" networkLoadBalancers/" + eachnlb.id + "/listeners/" + listeners) + tf_resource = f'module.nlb-listeners[\\"{tf_name}_{listener_tf_name}\\"].oci_network_load_balancer_listener.listener' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkLoadBalancers/{eachnlb.id}/listeners/{listeners}' for col_header in values_for_column_lis.keys(): if col_header == 'Region': @@ -204,7 +224,7 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm values_for_column_lis[col_header].append(eachnlb.display_name) else: values_for_column_lis[col_header].append("") - elif col_header == "Subnet Name": + elif col_header == "Network Details": if cnt_lsnr == 1: values_for_column_lis[col_header].append(subnet_detail) else: @@ -217,7 +237,7 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm elif (col_header == "Is Private(True|False)"): if cnt_lsnr == 1: - values_for_column_lis[col_header].append(not(ips.is_public)) + values_for_column_lis[col_header].append(not(is_public)) else: values_for_column_lis[col_header].append("") @@ -245,14 +265,14 @@ def print_nlb_listener(region, outdir, values_for_column_lis, NLBs, nlb_compartm values_for_column_lis[col_header].append(nlb_compartment_name) elif col_header == 'NLB Name': values_for_column_lis[col_header].append(eachnlb.display_name) - elif col_header == "Subnet Name": + elif col_header == "Network Details": values_for_column_lis[col_header].append(subnet_detail) elif (col_header == "NSGs"): values_for_column_lis[col_header].append(nsg_detail) elif (col_header == "Reserved IP(Y|N|OCID)"): values_for_column_lis[col_header].append(reserved_ip) elif (col_header == "Is Private(True|False)"): - values_for_column_lis[col_header].append(not(ips.is_public)) + values_for_column_lis[col_header].append(not(is_public)) # Process the Tag Columns elif col_header.lower() in commonTools.tagColumns: values_for_column_lis = commonTools.export_tags(eachnlb, col_header, values_for_column_lis) @@ -274,7 +294,9 @@ def export_nlb(inputfile, outdir, service_dir, config,signer, ct, export_compart global values_for_column_lis global sheet_dict_bss global sheet_dict_lis - global listener_to_cd3 + global listener_to_cd3,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -293,45 +315,57 @@ def export_nlb(inputfile, outdir, service_dir, config,signer, ct, export_compart print("\nCD3 excel file should not be opened during export process!!!") print("Tabs- NLB-Listeners, NLB-BackendSets-BackendServers will be overwritten during export process!!!\n") - # Create backups - for reg in export_regions: - resource='tf_import_nlb' - if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_nlb_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, "tf_import_commands_nlb_nonGF.sh") - importCommands[reg] = open(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_nlb_nonGF.sh", "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - # Fetch NLB Details print("\nFetching details of Network Load Balancer...") + file_name = 'import_commands_nlb.sh' + resource = 'import_nlb' + total_resources = 0 + for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Network Load Balancer Objects #########\n\n") + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + + # Create backups + if os.path.exists(script_file): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + + importCommands[reg] = '' + config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass nlb = NetworkLoadBalancerClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) vcn = VirtualNetworkClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) cmpt = ComputeClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) region = reg.capitalize() - for compartment_name in export_compartments: NLBs = oci.pagination.list_call_get_all_results(nlb.list_network_load_balancers,compartment_id=ct.ntk_compartment_ids[compartment_name], lifecycle_state="ACTIVE") + if NLBs.data != [] and importCommands[reg] == '': + total_resources += len(NLBs.data) - values_for_column_lis = print_nlb_listener(region, outdir, values_for_column_lis,NLBs,compartment_name,vcn) - values_for_column_bss = print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs,compartment_name,cmpt,vcn,nlb) + values_for_column_lis = print_nlb_listener(region, outdir, values_for_column_lis,NLBs,compartment_name,vcn,ct,state) + values_for_column_bss = print_nlb_backendset_backendserver(region, ct, values_for_column_bss,NLBs,compartment_name,cmpt,vcn,nlb,state) commonTools.write_to_cd3(values_for_column_lis, cd3file, "NLB-Listeners") commonTools.write_to_cd3(values_for_column_bss, cd3file, "NLB-BackendSets-BackendServers") - print("{0} NLBs exported into CD3.\n".format(len(values_for_column_lis["Region"]))) - + print("{0} NLBs exported into CD3.\n".format(total_resources)) # writing data for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/tf_import_commands_nlb_nonGF.sh' - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + script_file = f'{outdir}/{reg}/{service_dir}/' + file_name + if importCommands[reg] != "": + init_commands = f'\n######### Writing import for Network Load Balancer Objects #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Network/LoadBalancers/templates/lb-routing-policy-template b/cd3_automation_toolkit/Network/LoadBalancers/templates/lb-routing-policy-template new file mode 100755 index 000000000..1785895ee --- /dev/null +++ b/cd3_automation_toolkit/Network/LoadBalancers/templates/lb-routing-policy-template @@ -0,0 +1,62 @@ +{% if (skeleton and count == 0) %} +// Copyright (c) 2024, 2025, Oracle and/or its affiliates. + +############################# +# Network +# Routing Policy - tfvars +# Allowed Values: +# load_balancer_id can be the ocid or the key of load_balancers (map) +# Sample import command for Routing Policy: +# terraform import "module.routing-policy\"<>\"].oci_load_balancer_load_balancer_routing_policy.load_balancer_routing_policy" <> +############################# + +lb_routing_policies = { +##Add New Routing Policy for {{ region|lower }} here## +}{% else %} + {{ lbr_tf_name }}_{{ routing_policy_tf_name }} = { + condition_language_version = "V1" + load_balancer_id = "{{ load_balancer_id }}" + name = "{{ routing_policy_name }}" + rules = [ + {% for rule in rules %} + { + condition = "{{ rule.condition }}" + name = "{{ rule.name }}" + backend_set_name = "{{ rule.backend_set_name }}" + }{% if not loop.last %},{% endif %} + {% endfor %} + ] + + {# ##Do not modify below this line## #} + {# #} + {# ###Section for adding Defined and Freeform Tags### #} + {% if defined_tags and defined_tags != 'nan' and defined_tags != '' and defined_tags != [['nan']] %} + {% if defined_tags[0] %} + defined_tags = { + {% for tags in defined_tags %} + {% if not loop.last %} + "{{ tags[0] }}"= "{{ tags[1] }}" , + {% else %} + "{{ tags[0] }}"= "{{ tags[1] }}" + {% endif %} + {% endfor %} + } + {% endif %} + {% endif %} + {% if freeform_tags and freeform_tags != 'nan' and freeform_tags != '' and freeform_tags != [['nan']] %} + {% if freeform_tags[0] %} + freeform_tags = { + {% for tags in freeform_tags %} + {% if not loop.last %} + "{{ tags[0] }}"="{{ tags[1] }}", + {% else %} + "{{ tags[0] }}"="{{ tags[1] }}" + {% endif %} + {% endfor %} + } + {% endif %} + {% endif %} + {# ###Section for adding Defined and Freeform Tags ends here### #} + }, + +{% endif %} \ No newline at end of file diff --git a/cd3_automation_toolkit/OCI_Regions b/cd3_automation_toolkit/OCI_Regions index 5d3767430..da2a8419e 100644 --- a/cd3_automation_toolkit/OCI_Regions +++ b/cd3_automation_toolkit/OCI_Regions @@ -3,6 +3,7 @@ saltlake:us-saltlake-2 amsterdam:eu-amsterdam-1 stockholm:eu-stockholm-1 abudhabi:me-abudhabi-1 +saltlake:us-saltlake-1 bogota:sa-bogota-1 mumbai:ap-mumbai-1 paris:eu-paris-1 @@ -16,6 +17,7 @@ seoul:ap-seoul-1 jeddah:me-jeddah-1 johannesburg:af-johannesburg-1 osaka:ap-osaka-1 +kragujevac:eu-kragujevac-1 london:uk-london-1 milan:eu-milan-1 madrid:eu-madrid-1 @@ -24,6 +26,7 @@ marseille:eu-marseille-1 monterrey:mx-monterrey-1 jerusalem:il-jerusalem-1 tokyo:ap-tokyo-1 +neom:me-neom-1 chicago:us-chicago-1 phoenix:us-phoenix-1 queretaro:mx-queretaro-1 diff --git a/cd3_automation_toolkit/Release-Notes b/cd3_automation_toolkit/Release-Notes index 21f771400..03f492dde 100644 --- a/cd3_automation_toolkit/Release-Notes +++ b/cd3_automation_toolkit/Release-Notes @@ -1,3 +1,17 @@ +------------------------------------- +CD3 Automation Toolkit Tag v2024.4.0 +Aug 16th, 2024 +------------------------------------- +1. Differential state import - Import commands during CD3 export process will only be written for the OCI objects which are not already in state file. + This will considerably reduce the time taken to run import commands. +2. Users/Groups for Custom Identity Domains +3. Routing Policies for Load Balancers. +4. Terraform version upgrade to 1.5.7 on the container. OCI RM stack version also upgraded to 1.5.x +5. Support for OpenTofu 1.6.2. Update tenancyconfig.properties to specify the IaC tool to be configured for a particular prefix. +6. Independence from Network Tabs while exporting all other OCI resources. ie network tabs do not need to have data to export instances/databases etc. +7. Inclusion of OCI FSDR export and update functionality (using python) under 'OCI Other Tools'. Output files generated are made available at + /cd3user/tenancies//othertools_files and also under artifacts in Jenkins console. + ------------------------------------- CD3 Automation Toolkit Tag v2024.3.2 Jun 26th, 2024 diff --git a/cd3_automation_toolkit/SDDC/create_terraform_sddc.py b/cd3_automation_toolkit/SDDC/create_terraform_sddc.py index 0f184dedd..456f5dbe6 100755 --- a/cd3_automation_toolkit/SDDC/create_terraform_sddc.py +++ b/cd3_automation_toolkit/SDDC/create_terraform_sddc.py @@ -126,24 +126,31 @@ def create_terraform_sddc_cluster(inputfile, outdir, service_dir, prefix, ct, sd columnvalue = commonTools.check_columnvalue(str(df1[columnname][i]).strip()) # Check for multivalued columns tempdict = commonTools.check_multivalues_columnvalue(columnvalue, columnname, tempdict) - if columnname == 'Provisioning Subnet': - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + + subnet_id = '' + network_compartment_id = '' + vcn_name = '' + if columnname == 'Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - else: - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str(i + 3) + ". It Doesnt exist in SubnetsVLANs sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower() != 'nan' and columnvalue.lower() != '': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if ("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - - tempdict = {'network_compartment_id': commonTools.check_tf_variable(network_compartment_id), - 'vcn_name': vcn_name,'provisioning_subnet': subnet_id} + else: + vcn_name = vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, + 'provisioning_subnet': subnet_id} columnname = commonTools.check_column_headers(columnname) tempStr[columnname] = str(columnvalue).strip() diff --git a/cd3_automation_toolkit/SDDC/export_sddc_nonGreenField.py b/cd3_automation_toolkit/SDDC/export_sddc_nonGreenField.py index d9611ad50..3af083e0c 100644 --- a/cd3_automation_toolkit/SDDC/export_sddc_nonGreenField.py +++ b/cd3_automation_toolkit/SDDC/export_sddc_nonGreenField.py @@ -10,6 +10,7 @@ from oci.core.virtual_network_client import VirtualNetworkClient from oci.core.blockstorage_client import BlockstorageClient import os +import subprocess as sp sys.path.append(os.getcwd() + "/..") from commonTools import * @@ -21,14 +22,16 @@ def get_volume_data(bvol, volume_id, ct): vol_comp = list(ct.ntk_compartment_ids.keys())[comp_list.index(volume_data.compartment_id)] return vol_comp+'@'+vol_name -###SDDC Data +### Execution start here - SDDC Data def export_sddc(inputfile, outdir, service_dir,config,signer, ct, export_compartments=[], export_regions=[]): cd3file = inputfile if ('.xls' not in cd3file): print("\nAcceptable cd3 format: .xlsx") exit() - - global importCommands,importCommands_cluster, values_for_column_sddc, df, sheet_dict_sddc # declaring global variables + # declaring global variables + global importCommands,importCommands_cluster, values_for_column_sddc, df, sheet_dict_sddc,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] sheetName= "SDDCs" sheetNameNetwork = "SDDCs-Network" @@ -51,23 +54,29 @@ def export_sddc(inputfile, outdir, service_dir,config,signer, ct, export_compart print("Tabs- SDDCs and SDDCs-Network will be overwritten during this export process!!!\n") # Create of .sh file - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' + total_resources=0 + + # Create backups for reg in export_regions: - ## Create of .sh file for sddc script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): - commonTools.backup_file(outdir + "/" + reg+"/"+service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + importCommands[reg] = '' for reg in export_regions: var_data[reg] = "" script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - importCommands[reg].write("\n######### Writing import for SDDC #########\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass sddc_client = oci.ocvp.SddcClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) sddc_cluster_client = oci.ocvp.ClusterClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) vnc = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -104,18 +113,18 @@ def export_sddc(inputfile, outdir, service_dir,config,signer, ct, export_compart key_name = commonTools.check_tf_variable(sddc.display_name) ssh_key = json.dumps(sddc.ssh_authorized_keys) sddc_keys[key_name] = ssh_key - - importCommands[reg].write( - "\nterraform import \"module.sddcs[\\\"" + tf_name + "\\\"].oci_ocvp_sddc.sddc\" " + sddc.id) + tf_resource = f'module.sddcs[\\"{tf_name}\\"].oci_ocvp_sddc.sddc' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {sddc.id}' elif sddc_cluster.vsphere_type == "WORKLOAD": sddc_network = sddc_cluster_data.network_configuration sddc_datastores = sddc_cluster_data.datastores tf_name = commonTools.check_tf_variable( sddc.display_name + "--" + sddc_cluster_data.display_name) - - importCommands[reg].write( - "\nterraform import \"module.sddc-clusters[\\\"" + tf_name + "\\\"].oci_ocvp_cluster.sddc_cluster\" " + sddc_cluster.id) + tf_resource = f'module.sddc-clusters[\\"{tf_name}\\"].oci_ocvp_cluster.sddc_cluster' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {sddc_cluster.id}' if 'Standard' in ( sddc_init_config.initial_host_shape_name if sddc_cluster.vsphere_type == "MANAGEMENT" else sddc_cluster.initial_host_shape_name): @@ -170,12 +179,20 @@ def export_sddc(inputfile, outdir, service_dir,config,signer, ct, export_compart elif col_header == 'SSH Key Var Name': values_for_column_sddc[col_header].append( key_name if sddc_cluster.vsphere_type == "MANAGEMENT" else "") - elif col_header == "Provisioning Subnet": + elif col_header == "Network Details": subnet_id = sddc_network.provisioning_subnet_id subnet_info = vnc.get_subnet(subnet_id) sub_name = subnet_info.data.display_name vcn_name = vnc.get_vcn(subnet_info.data.vcn_id).data.display_name - values_for_column_sddc[col_header].append(vcn_name + "_" + sub_name) + + ntk_compartment_id = vnc.get_vcn(subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name = ntk_compartment_name + for comp_name, comp_id in ct.ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + vplussubnet = network_compartment_name + "@" + vcn_name + "::" + sub_name + values_for_column_sddc[col_header].append(vplussubnet) elif col_header == "NSX Edge Uplink1 VLAN": vlan_id = sddc_network.nsx_edge_uplink1_vlan_id values_for_column_sddc[col_header].append(vnc.get_vlan(vlan_id).data.display_name) @@ -241,9 +258,12 @@ def export_sddc(inputfile, outdir, service_dir,config,signer, ct, export_compart with open(file, "w") as f: f.write(var_data[reg]) - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + init_commands = f'\n#!/bin/bash\n{tf_or_tofu} init\n######### Writing import for SDDC #########\n' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) commonTools.write_to_cd3(values_for_column_sddc, cd3file, sheetName) commonTools.write_to_cd3(values_for_column_sddc, cd3file, sheetNameNetwork) - print("{0} SDDC Cluster Details exported into CD3.\n".format(len(values_for_column_sddc["Region"]))) + print("{0} SDDC Clusters exported into CD3.\n".format(len(values_for_column_sddc["Region"]))) diff --git a/cd3_automation_toolkit/Security/Firewall/export_firewall_nonGreenField.py b/cd3_automation_toolkit/Security/Firewall/export_firewall_nonGreenField.py index f7b5b9a6e..e830e4641 100644 --- a/cd3_automation_toolkit/Security/Firewall/export_firewall_nonGreenField.py +++ b/cd3_automation_toolkit/Security/Firewall/export_firewall_nonGreenField.py @@ -10,6 +10,7 @@ import sys import oci import os +import subprocess as sp from oci.network_firewall import NetworkFirewallClient from oci.core.virtual_network_client import VirtualNetworkClient @@ -21,11 +22,13 @@ oci_obj_names = {} AD = lambda ad: "AD1" if ("AD-1" in ad or "ad-1" in ad) else ("AD2" if ("AD-2" in ad or "ad-2" in ad) else ("AD3" if ("AD-3" in ad or "ad-3" in ad) else " NULL")) -def print_firewall(region, ct, values_for_column_fw, fws, fw_compartment_name, vcn, fw): +def print_firewall(region, ct, values_for_column_fw, fws, fw_compartment_name, vcn, fw,state): for eachfw in fws.data: fw_display_name = eachfw.display_name tf_name = commonTools.check_tf_variable(fw_display_name) - importCommands[reg].write("\nterraform import \"module.firewalls[\\\"" + str(tf_name) + "\\\"].oci_network_firewall_network_firewall.network_firewall\" "+eachfw.id) + tf_resource = f'module.firewalls[\\"{str(tf_name)}\\"].oci_network_firewall_network_firewall.network_firewall' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {eachfw.id}' # Fetch subnet and Compartment name comp_done_ids = [] subnet_ocid = eachfw.subnet_id @@ -110,8 +113,9 @@ def export_firewall(inputfile, _outdir, service_dir, config, signer, ct, export_ global values_for_column_fwpolicy global sheet_dict_fwpolicy global sheet_dict_fwaddress - global listener_to_cd3 - + global listener_to_cd3,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -127,25 +131,29 @@ def export_firewall(inputfile, _outdir, service_dir, config, signer, ct, export_ print("Tabs- Firewall will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' + + # Create backups for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - if (os.path.exists(script_file)): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, - file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + importCommands[reg] = '' # Fetch Network firewall Policy Details print("\nFetching details of Network Firewall...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Network Firewall Objects #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass fw = NetworkFirewallClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) vcn = VirtualNetworkClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -157,14 +165,17 @@ def export_firewall(inputfile, _outdir, service_dir, config, signer, ct, export_ fws = oci.pagination.list_call_get_all_results(fw.list_network_firewalls, compartment_id=ct.ntk_compartment_ids[compartment_name], lifecycle_state="ACTIVE") # fwpolicies = oci.pagination.list_call_get_all_results(fwpolicy.list_network_firewall_policies,compartment_id=ct.ntk_compartment_ids[compartment_name],lifecycle_state = "ACTIVE") - values_for_column_fw = print_firewall(region, ct, values_for_column_fw, fws, compartment_name, vcn, fw) + values_for_column_fw = print_firewall(region, ct, values_for_column_fw, fws, compartment_name, vcn, fw,state) - commonTools.write_to_cd3(values_for_column_fw, cd3file, sheetName) - # commonTools.write_to_cd3(values_for_column_bss, cd3file, "NLB-BackendSets-BackendServers") - - print("Firewalls exported to CD3\n") - # writing data + # writing data + init_commands = f'\n######### Writing import for Network Firewall Objects #########\n\n#!/bin/bash\n{tf_or_tofu} init' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') \ No newline at end of file + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + + commonTools.write_to_cd3(values_for_column_fw, cd3file, sheetName) + print("{0} Firewalls exported into CD3.\n".format(len(values_for_column_fw["Region"]))) + diff --git a/cd3_automation_toolkit/Security/Firewall/export_firewallpolicy_nonGreenField.py b/cd3_automation_toolkit/Security/Firewall/export_firewallpolicy_nonGreenField.py index a84b4c4e3..3fbcbfc1c 100644 --- a/cd3_automation_toolkit/Security/Firewall/export_firewallpolicy_nonGreenField.py +++ b/cd3_automation_toolkit/Security/Firewall/export_firewallpolicy_nonGreenField.py @@ -16,18 +16,18 @@ from oci.key_management import KmsVaultClient from oci.identity import IdentityClient import time +import subprocess as sp from oci.network_load_balancer import NetworkLoadBalancerClient sys.path.append(os.getcwd() + "/..") from commonTools import * -importCommands = {} +importCommands,importCommands_nfp,importCommands_nfao,importCommands_ulo,importCommands_slo,importCommands_alo,importCommands_sro,importCommands_mso,importCommands_dpo,importCommands_dro,importCommands_fpo = {},{},{},{},{},{},{},{},{},{},{} oci_obj_names = {} -def print_firewall_policy(region, ct, values_for_column_fwpolicy, fwpolicies, fwpolicy_compartment_name): +def print_firewall_policy(region, ct, values_for_column_fwpolicy, fwpolicies, fwpolicy_compartment_name,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall Policy #########\n\n") print("Exporting Policy details for " + region) for eachfwpolicy in fwpolicies: fwpolicy_display_name = eachfwpolicy.display_name @@ -35,7 +35,9 @@ def print_firewall_policy(region, ct, values_for_column_fwpolicy, fwpolicies, fw fwpolicy_display_name = target_pol[src_pol.index(fwpolicy_display_name)] else: tf_name = commonTools.check_tf_variable(fwpolicy_display_name) - importCommands[reg].write("\nterraform import \"module.policies[\\\"" + str(tf_name) + "\\\"].oci_network_firewall_network_firewall_policy.network_firewall_policy\" "+eachfwpolicy.id) + tf_resource = f'module.policies[\\"{str(tf_name)}\\"].oci_network_firewall_network_firewall_policy.network_firewall_policy' + if tf_resource not in state["resources"]: + importCommands_nfp[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {eachfwpolicy.id}' for col_header in values_for_column_fwpolicy: if col_header == 'Region': @@ -51,9 +53,8 @@ def print_firewall_policy(region, ct, values_for_column_fwpolicy, fwpolicies, fw return values_for_column_fwpolicy -def print_firewall_address(region, ct, values_for_column_fwaddress, fwpolicies, fwpolicy): +def print_firewall_address(region, ct, values_for_column_fwaddress, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall Address Objects #########\n\n") print("Exporting Address-list details " + region) for policy in fwpolicies: policy_id = policy.id @@ -62,18 +63,16 @@ def print_firewall_address(region, ct, values_for_column_fwaddress, fwpolicies, addpolicy_display_name = target_pol[src_pol.index(addpolicy_display_name)] addpolicy_tf_name = commonTools.check_tf_variable(addpolicy_display_name) - fwaddresslist = oci.pagination.list_call_get_all_results(fwpolicy.list_address_lists, policy_id) + fwaddresslist = oci.pagination.list_call_get_all_results(fwclient.list_address_lists, policy_id) addresslist_info = fwaddresslist.data - #importCommands[reg].write("\nterraform import \"module.address_list[\\\"" + str(addpolicy_tf_name) + "_" + str(address_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_address_list.network_firewall_policy_address_list\" networkFirewallPolicies/" + policy_id + "/addressLists/" + address_display_name) - for add in addresslist_info: - address_info = fwpolicy.get_address_list(add.parent_resource_id, add.name).data.addresses + address_info = fwclient.get_address_list(add.parent_resource_id, add.name).data.addresses address_display_name = add.name address_tf_name = commonTools.check_tf_variable(address_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.address_lists[\\\"" + str(addpolicy_tf_name) + "_" + str(address_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_address_list.network_firewall_policy_address_list\" networkFirewallPolicies/" + policy_id + "/addressLists/" + address_display_name) - + tf_resource = f'module.address_lists[\\"{str(addpolicy_tf_name)}_{str(address_tf_name)}\\"].oci_network_firewall_network_firewall_policy_address_list.network_firewall_policy_address_list' + if not clone and tf_resource not in state["resources"]: + importCommands_nfao[reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{policy_id}/addressLists/{address_display_name}' address_detail = "" for address in address_info: @@ -98,9 +97,8 @@ def print_firewall_address(region, ct, values_for_column_fwaddress, fwpolicies, return values_for_column_fwaddress -def print_firewall_urllist(region, ct, values_for_column_fwurllist, fwpolicies, fwpolicy): +def print_firewall_urllist(region, ct, values_for_column_fwurllist, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall url list Objects #########\n\n") print("Exporting Url-list details " + region) for urlpolicy in fwpolicies: urlpolicy_id = urlpolicy.id @@ -108,14 +106,16 @@ def print_firewall_urllist(region, ct, values_for_column_fwurllist, fwpolicies, if clone: urlpolicy_display_name = target_pol[src_pol.index(urlpolicy_display_name)] urlpolicy_tf_name = commonTools.check_tf_variable(urlpolicy_display_name) - fwurllists = oci.pagination.list_call_get_all_results(fwpolicy.list_url_lists, urlpolicy_id) + fwurllists = oci.pagination.list_call_get_all_results(fwclient.list_url_lists, urlpolicy_id) urllist_info = fwurllists.data for url in urllist_info: - url_info = fwpolicy.get_url_list(url.parent_resource_id, url.name).data.urls + url_info = fwclient.get_url_list(url.parent_resource_id, url.name).data.urls url_display_name = url.name url_tf_name = commonTools.check_tf_variable(url_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.url_lists[\\\"" + str(urlpolicy_tf_name) + "_" + str(url_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_url_list.network_firewall_policy_url_list\" networkFirewallPolicies/" + urlpolicy_id + "/urlLists/" + url_display_name) + tf_resource = f'module.url_lists[\\"{str(urlpolicy_tf_name)}_{str(url_tf_name)}\\"].oci_network_firewall_network_firewall_policy_url_list.network_firewall_policy_url_list' + if not clone and tf_resource not in state["resources"]: + importCommands_ulo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{urlpolicy_id}/urlLists/{url_display_name}' a = url_info url_detail = "" for b in a: @@ -137,9 +137,8 @@ def print_firewall_urllist(region, ct, values_for_column_fwurllist, fwpolicies, return values_for_column_fwurllist -def print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpolicies, fwpolicy): +def print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall service list Objects #########\n\n") print("Exporting Service and Service-list details " + region) for servicelistpolicy in fwpolicies: @@ -148,28 +147,32 @@ def print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpo if clone: servicelistpolicy_display_name = target_pol[src_pol.index(servicelistpolicy_display_name)] servicelistpolicy_tf_name = commonTools.check_tf_variable(servicelistpolicy_display_name) - fwservicelists = oci.pagination.list_call_get_all_results(fwpolicy.list_service_lists, servicelistpolicy_id) + fwservicelists = oci.pagination.list_call_get_all_results(fwclient.list_service_lists, servicelistpolicy_id) servicelist_info = fwservicelists.data service_seen_so_far = set() for service in servicelist_info: - service_info = fwpolicy.get_service_list(service.parent_resource_id, service.name).data.services + service_info = fwclient.get_service_list(service.parent_resource_id, service.name).data.services service_display_name = service.name service_tf_name = commonTools.check_tf_variable(service_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.service_lists[\\\"" + str(servicelistpolicy_tf_name) + "_" + str(service_display_name) + "\\\"].oci_network_firewall_network_firewall_policy_service_list.network_firewall_policy_service_list\" networkFirewallPolicies/" + servicelistpolicy_id + "/serviceLists/" + service_display_name) + tf_resource = f'module.service_lists[\\"{str(servicelistpolicy_tf_name)}_{str(service_display_name)}\\"].oci_network_firewall_network_firewall_policy_service_list.network_firewall_policy_service_list' + if not clone and tf_resource not in state["resources"]: + importCommands_slo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{servicelistpolicy_id}/serviceLists/{service_display_name}' service_detail = "" for eachservice in service_info: service_seen_so_far.add(eachservice) - servicelist = fwpolicy.get_service(service.parent_resource_id, eachservice).data + servicelist = fwclient.get_service(service.parent_resource_id, eachservice).data servicetype = servicelist.type port_detail = "" servicename = servicelist.name servicename_tf =commonTools.check_tf_variable(servicename) - if not clone: - importCommands[reg].write("\nterraform import \"module.services[\\\"" + str(servicelistpolicy_tf_name) + "_" + str(servicename_tf) + "\\\"].oci_network_firewall_network_firewall_policy_service.network_firewall_policy_service\" networkFirewallPolicies/" + servicelistpolicy_id + "/services/" + servicename) + tf_resource = f'module.services[\\"{str(servicelistpolicy_tf_name)}_{str(servicename_tf)}\\"].oci_network_firewall_network_firewall_policy_service.network_firewall_policy_service' + if not clone and tf_resource not in state["resources"]: + importCommands_slo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{servicelistpolicy_id}/services/{servicename}' for svc in servicelist.port_ranges: port_detail = port_detail + "," + str(svc.minimum_port) + "-" + str(svc.maximum_port) if (port_detail != ""): @@ -193,7 +196,7 @@ def print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpo values_for_column_fwservicelist = commonTools.export_tags(servicelistpolicy, col_header,values_for_column_fwservicelist) ## Fetch services without Lists - fwservices = oci.pagination.list_call_get_all_results(fwpolicy.list_services,servicelistpolicy_id) + fwservices = oci.pagination.list_call_get_all_results(fwclient.list_services,servicelistpolicy_id) services = fwservices.data service_detail = "" for service in services: @@ -202,10 +205,12 @@ def print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpo if service.name in service_seen_so_far: continue - service_data = fwpolicy.get_service(service.parent_resource_id, service.name).data + service_data = fwclient.get_service(service.parent_resource_id, service.name).data service_tf_name = commonTools.check_tf_variable(service_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.services[\\\"" + str(servicelistpolicy_tf_name) + "_" + str(service_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_service.network_firewall_policy_service\" networkFirewallPolicies/" + servicelistpolicy_id + "/services/" + service_display_name) + tf_resource = f'module.services[\\"{str(servicelistpolicy_tf_name)}_{str(service_tf_name)}\\"].oci_network_firewall_network_firewall_policy_service.network_firewall_policy_service' + if not clone and tf_resource not in state["resources"]: + importCommands_slo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{servicelistpolicy_id}/services/{service_display_name}' port_detail = "" for svc_port_range in service_data.port_ranges: @@ -232,9 +237,8 @@ def print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpo return values_for_column_fwservicelist -def print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, fwpolicy): +def print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall application list Objects #########\n\n") print("Exporting Application and Application-list details " + region) for applistpolicy in fwpolicies: applistpolicy_id = applistpolicy.id @@ -242,26 +246,31 @@ def print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, if clone: applistpolicy_display_name = target_pol[src_pol.index(applistpolicy_display_name)] applistpolicy_tf_name = commonTools.check_tf_variable(applistpolicy_display_name) - fwapplists = oci.pagination.list_call_get_all_results(fwpolicy.list_application_groups, applistpolicy_id) + fwapplists = oci.pagination.list_call_get_all_results(fwclient.list_application_groups, applistpolicy_id) applist_info = fwapplists.data app_seen_so_far = set() for application in applist_info: - application_info = fwpolicy.get_application_group(application.parent_resource_id, application.name).data.apps + application_info = fwclient.get_application_group(application.parent_resource_id, application.name).data.apps application_display_name = application.name application_tf_name = commonTools.check_tf_variable(application_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.application_groups[\\\"" + str(applistpolicy_tf_name) + "_" + str(application_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_application_group.network_firewall_policy_application_group\" networkFirewallPolicies/" + applistpolicy_id + "/applicationGroups/" + application_display_name) + tf_resource = f'module.application_groups[\\"{str(applistpolicy_tf_name)}_{str(application_tf_name)}\\"].oci_network_firewall_network_firewall_policy_application_group.network_firewall_policy_application_group' + if not clone and tf_resource not in state["resources"]: + importCommands_alo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{applistpolicy_id}/applicationGroups/{application_display_name}' application_detail = "" for eachapplication in application_info: - applist = fwpolicy.get_application(application.parent_resource_id, eachapplication).data + applist = fwclient.get_application(application.parent_resource_id, eachapplication).data applicationname = applist.name app_seen_so_far.add(eachapplication) applicationname_tf = commonTools.check_tf_variable(applicationname) - if not clone: - importCommands[reg].write("\nterraform import \"module.applications[\\\"" + str(applistpolicy_tf_name) + "_" + str(applicationname_tf) + "\\\"].oci_network_firewall_network_firewall_policy_application.network_firewall_policy_application\" networkFirewallPolicies/" + applistpolicy_id + "/applications/" + applicationname) + tf_resource = f'module.applications[\\"{str(applistpolicy_tf_name)}_{str(applicationname_tf)}\\"].oci_network_firewall_network_firewall_policy_application.network_firewall_policy_application' + if not clone and tf_resource not in state["resources"]: + importCommands_alo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{applistpolicy_id}/applications/{applicationname}' + if applist.icmp_code != None: application_detail = application_detail + "\n" + applist.name + "::" + applist.type + "::" + str(applist.icmp_type) + "::" + str(applist.icmp_code) else: @@ -284,19 +293,19 @@ def print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, values_for_column_fwapplist = commonTools.export_tags(applistpolicy, col_header,values_for_column_fwapplist) ## Fetch apps without Lists - fwapps = oci.pagination.list_call_get_all_results(fwpolicy.list_applications, applistpolicy_id) + fwapps = oci.pagination.list_call_get_all_results(fwclient.list_applications, applistpolicy_id) apps = fwapps.data application_detail = "" for app in apps: app_display_name = app.name if app.name in app_seen_so_far: continue - app_data = fwpolicy.get_application(app.parent_resource_id, app.name).data + app_data = fwclient.get_application(app.parent_resource_id, app.name).data app_tf_name = commonTools.check_tf_variable(app_display_name) - if not clone: - importCommands[reg].write( - "\nterraform import \"module.applications[\\\"" + str(applistpolicy_tf_name) + "_" + str( - app_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_application.network_firewall_policy_application\" networkFirewallPolicies/" + applistpolicy_id + "/applications/" + app_display_name) + tf_resource = f'module.applications[\\"{str(applistpolicy_tf_name)}_{str(app_tf_name)}\\"].oci_network_firewall_network_firewall_policy_application.network_firewall_policy_application' + if not clone and tf_resource not in state["resources"]: + importCommands_alo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{applistpolicy_id}/applications/{app_display_name}' if app_data.icmp_code != None: application_detail = application_detail + "\n" + app.name + "::" + app.type + "::" + str( @@ -323,9 +332,8 @@ def print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, return values_for_column_fwapplist -def print_firewall_secrules(region, ct, values_for_column_fwsecrules, fwpolicies, fwpolicy): +def print_firewall_secrules(region, ct, values_for_column_fwsecrules, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall Security Rules Objects #########\n\n") print("Exporting Security rules details " + region) for secrulespolicy in fwpolicies: secrulespolicy_id = secrulespolicy.id @@ -333,15 +341,18 @@ def print_firewall_secrules(region, ct, values_for_column_fwsecrules, fwpolicies if clone: secrulespolicy_display_name = target_pol[src_pol.index(secrulespolicy_display_name)] secrulespolicy_tf_name = commonTools.check_tf_variable(secrulespolicy_display_name) - fwsecrules = oci.pagination.list_call_get_all_results(fwpolicy.list_security_rules,secrulespolicy_id) + fwsecrules = oci.pagination.list_call_get_all_results(fwclient.list_security_rules,secrulespolicy_id) secrules_info = fwsecrules.data #print(secrules_info) for rules in secrules_info: - rule_info = fwpolicy.get_security_rule(rules.parent_resource_id, rules.name).data + rule_info = fwclient.get_security_rule(rules.parent_resource_id, rules.name).data rules_display_name = rules.name rules_tf_name = commonTools.check_tf_variable(rules_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.security_rules[\\\"" + str(secrulespolicy_tf_name) + "_" + str(rules_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_security_rule.network_firewall_policy_security_rule\" networkFirewallPolicies/" + secrulespolicy_id + "/securityRules/" + rules_display_name) + tf_resource = f'module.security_rules[\\"{str(secrulespolicy_tf_name)}_{str(rules_tf_name)}\\"].oci_network_firewall_network_firewall_policy_security_rule.network_firewall_policy_security_rule' + if not clone and tf_resource not in state["resources"]: + importCommands_sro[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{secrulespolicy_id}/securityRules/{rules_display_name}' + rsrc_detail = "" rdst_detail = "" rapp_detail = "" @@ -413,9 +424,8 @@ def print_firewall_secrules(region, ct, values_for_column_fwsecrules, fwpolicies values_for_column_fwsecrules = commonTools.export_tags(secrulespolicy, col_header,values_for_column_fwsecrules) return values_for_column_fwsecrules -def print_firewall_secret(region, ct, values_for_column_fwsecret, fwpolicies, fwpolicy, vault, compartment, kmsvault): +def print_firewall_secret(region, ct, values_for_column_fwsecret, fwpolicies, fwclient, vault, compartment, kmsvault,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall Mapped Secret Objects #########\n\n") print("Exporting Mapped secret details " + region) for secretpolicy in fwpolicies: secretpolicy_id = secretpolicy.id @@ -423,18 +433,20 @@ def print_firewall_secret(region, ct, values_for_column_fwsecret, fwpolicies, fw if clone: secretpolicy_display_name = target_pol[src_pol.index(secretpolicy_display_name)] secretpolicy_tf_name = commonTools.check_tf_variable(secretpolicy_display_name) - fwsecrets = oci.pagination.list_call_get_all_results(fwpolicy.list_mapped_secrets, secretpolicy_id) + fwsecrets = oci.pagination.list_call_get_all_results(fwclient.list_mapped_secrets, secretpolicy_id) secret_info = fwsecrets.data for key in secret_info: - key_info = fwpolicy.get_mapped_secret(key.parent_resource_id, key.name).data + key_info = fwclient.get_mapped_secret(key.parent_resource_id, key.name).data secretdisplay_name = key.name secretdisplay_tf_name = commonTools.check_tf_variable(secretdisplay_name) vault_secret = vault.get_secret(key_info.vault_secret_id).data kmsvault_name = kmsvault.get_vault(vault_secret.vault_id).data vault_secret_name = kmsvault_name.display_name + '::' + vault_secret.secret_name vault_secret_compartment_detail = compartment.get_compartment(vault_secret.compartment_id).data.name - if not clone: - importCommands[reg].write("\nterraform import \"module.secrets[\\\"" + str(secretpolicy_tf_name) + "_" + str(secretdisplay_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_mapped_secret.network_firewall_policy_mapped_secret\" networkFirewallPolicies/" + secretpolicy_id + "/mappedSecrets/" + secretdisplay_name) + tf_resource = f'module.secrets[\\"{str(secretpolicy_tf_name)}_{str(secretdisplay_tf_name)}\\"].oci_network_firewall_network_firewall_policy_mapped_secret.network_firewall_policy_mapped_secret' + if not clone and tf_resource not in state["resources"]: + importCommands_mso[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{secretpolicy_id}/mappedSecrets/{secretdisplay_name}' for col_header in values_for_column_fwsecret: if col_header == 'Region': @@ -458,9 +470,8 @@ def print_firewall_secret(region, ct, values_for_column_fwsecret, fwpolicies, fw return values_for_column_fwsecret -def print_firewall_decryptprofile(region, ct, values_for_column_fwdecryptprofile, fwpolicies, fwpolicy): +def print_firewall_decryptprofile(region, ct, values_for_column_fwdecryptprofile, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall Decrypt profile Objects #########\n\n") print("Exporting Decryption Profile details " + region) for decryptionprofile in fwpolicies: decryptionprofile_id = decryptionprofile.id @@ -468,14 +479,17 @@ def print_firewall_decryptprofile(region, ct, values_for_column_fwdecryptprofile if clone: decryptionprofile_display_name = target_pol[src_pol.index(decryptionprofile_display_name)] decryptionprofile_tf_name = commonTools.check_tf_variable(decryptionprofile_display_name) - fwdcyrptionprofiles = oci.pagination.list_call_get_all_results(fwpolicy.list_decryption_profiles, decryptionprofile_id) + fwdcyrptionprofiles = oci.pagination.list_call_get_all_results(fwclient.list_decryption_profiles, decryptionprofile_id) decryptionprofile_info = fwdcyrptionprofiles.data for decryption in decryptionprofile_info: - key_info = fwpolicy.get_decryption_profile(decryption.parent_resource_id, decryption.name).data + key_info = fwclient.get_decryption_profile(decryption.parent_resource_id, decryption.name).data key_info_name = key_info.name key_info_tf_name = commonTools.check_tf_variable(key_info.name) - if not clone: - importCommands[reg].write("\nterraform import \"module.decryption_profiles[\\\"" + str(decryptionprofile_tf_name) + "_" + str(key_info_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_decryption_profile.network_firewall_policy_decryption_profile\" networkFirewallPolicies/" + decryptionprofile_id + "/decryptionProfiles/" + key_info_name) + tf_resource = f'module.decryption_profiles[\\"{str(decryptionprofile_tf_name)}_{str(key_info_tf_name)}\\"].oci_network_firewall_network_firewall_policy_decryption_profile.network_firewall_policy_decryption_profile' + if not clone and tf_resource not in state["resources"]: + importCommands_dpo[ + reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{decryptionprofile_id}/decryptionProfiles/{key_info_name}' + if key_info.type == "SSL_INBOUND_INSPECTION": key_info1_are_certificate_extensions_restricted = "" key_info1_is_auto_include_alt_name = "" @@ -522,9 +536,8 @@ def print_firewall_decryptprofile(region, ct, values_for_column_fwdecryptprofile values_for_column_fwdecryptprofile = commonTools.export_tags(decryptionprofile, col_header,values_for_column_fwdecryptprofile) return values_for_column_fwdecryptprofile -def print_firewall_decryptrule(region, ct, values_for_column_fwdecryptrule, fwpolicies, fwpolicy): +def print_firewall_decryptrule(region, ct, values_for_column_fwdecryptrule, fwpolicies, fwclient,state): if not clone: - importCommands[reg].write("\n\n######### Writing import for Network firewall decryption Rules Objects #########\n\n") print("Exporting Decryption rules details " + region) for decryptrulepolicy in fwpolicies: decryptrulepolicy_id = decryptrulepolicy.id @@ -532,14 +545,16 @@ def print_firewall_decryptrule(region, ct, values_for_column_fwdecryptrule, fwpo if clone: decryptrulepolicy_display_name = target_pol[src_pol.index(decryptrulepolicy_display_name)] decryptrulepolicy_tf_name = commonTools.check_tf_variable(decryptrulepolicy_display_name) - fwdecrypteules = oci.pagination.list_call_get_all_results(fwpolicy.list_decryption_rules, decryptrulepolicy_id) + fwdecrypteules = oci.pagination.list_call_get_all_results(fwclient.list_decryption_rules, decryptrulepolicy_id) decrypteules_info = fwdecrypteules.data for drules in decrypteules_info: - drule_info = fwpolicy.get_decryption_rule(drules.parent_resource_id, drules.name).data + drule_info = fwclient.get_decryption_rule(drules.parent_resource_id, drules.name).data drules_display_name = drules.name drules_tf_name = commonTools.check_tf_variable(drules_display_name) - if not clone: - importCommands[reg].write("\nterraform import \"module.decryption_rules[\\\"" + str(decryptrulepolicy_tf_name) + "_" + str(drules_tf_name) + "\\\"].oci_network_firewall_network_firewall_policy_decryption_rule.network_firewall_policy_decryption_rule\" networkFirewallPolicies/" + decryptrulepolicy_id + "/decryptionRules/" + drules_display_name) + tf_resource = f'module.decryption_rules[\\"{str(decryptrulepolicy_tf_name)}_{str(drules_tf_name)}\\"].oci_network_firewall_network_firewall_policy_decryption_rule.network_firewall_policy_decryption_rule' + if not clone and tf_resource not in state["resources"]: + importCommands_dro[reg] += f'\n{tf_or_tofu} import "{tf_resource}" networkFirewallPolicies/{decryptrulepolicy_id}/decryptionRules/{drules_display_name}' + rsrc_detail = "" rdst_detail = "" if drule_info.condition.source_address != None: @@ -583,12 +598,12 @@ def print_firewall_decryptrule(region, ct, values_for_column_fwdecryptrule, fwpo elif col_header.lower() in commonTools.tagColumns: values_for_column_fwdecryptrule = commonTools.export_tags(decryptrulepolicy, col_header,values_for_column_fwdecryptrule) return values_for_column_fwdecryptrule -# Execution of the code begins here +# Execution of the code begins here def export_firewallpolicy(inputfile, _outdir, service_dir, config, signer, ct, export_compartments, export_regions, export_policies,target_policies=[],attached_policy_only="",clone_policy=False): global tf_import_cmd global sheet_dict - global importCommands + global importCommands,importCommands_nfp,importCommands_nfao,importCommands_ulo,importCommands_slo,importCommands_alo,importCommands_sro,importCommands_mso,importCommands_dpo,importCommands_dro,importCommands_fpo global values_for_vcninfo global cd3file global reg @@ -609,7 +624,9 @@ def export_firewallpolicy(inputfile, _outdir, service_dir, config, signer, ct, e global listener_to_cd3 global clone global src_pol - global target_pol + global target_pol,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] src_pol = export_policies.copy() if export_policies else [] target_pol = [] if not target_policies : @@ -650,24 +667,29 @@ def export_firewallpolicy(inputfile, _outdir, service_dir, config, signer, ct, e print("Tabs related to firewall and firewall policies will be overwritten during export process!!!\n") for reg in export_regions: - resource = 'tf_import_fwpolicy' + resource = 'import_fwpolicy' + if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/import_commands_firewallpolicy.sh")): + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, "import_commands_firewallpolicy.sh") + importCommands[reg], importCommands_nfp[reg], importCommands_nfao[reg], importCommands_ulo[reg], \ + importCommands_slo[reg], importCommands_alo[reg], importCommands_sro[reg], importCommands_mso[reg], \ + importCommands_dpo[reg], importCommands_dro[reg], importCommands_fpo[ + reg] = "", "", "", "", "", "", "", "", "", "", "" - if (os.path.exists(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_firewallpolicy_nonGF.sh")): - commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, "tf_import_commands_firewallpolicy_nonGF.sh") - importCommands[reg] = open( - outdir + "/" + reg + "/" + service_dir + "/temppolicyfile", "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - importCommands[reg].write("\n\n######### Writing import for Network firewall policy Objects #########\n\n") - # Fetch Network firewall Policy Details print("\nFetching details of Network firewall policy...") for reg in export_regions: config.__setitem__("region", ct.region_dict[reg]) - fwpolicy = NetworkFirewallClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass + fwclient = NetworkFirewallClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) vault = VaultsClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) kmsvault = KmsVaultClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) compartment = IdentityClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) @@ -676,41 +698,36 @@ def export_firewallpolicy(inputfile, _outdir, service_dir, config, signer, ct, e for compartment_name in export_compartments: fwpolicies = [] - fw_data = oci.pagination.list_call_get_all_results(fwpolicy.list_network_firewall_policies,compartment_id=ct.ntk_compartment_ids[compartment_name], lifecycle_state="ACTIVE") - fw_data = fw_data.data - if (export_policies is not None): - for eachfwpolicy in fw_data: - policy_ocid = eachfwpolicy.id - policydata = fwpolicy.get_network_firewall_policy(network_firewall_policy_id=policy_ocid) - eachfwpolicy1 = policydata.data + fw_data = oci.pagination.list_call_get_all_results(fwclient.list_network_firewall_policies,compartment_id=ct.ntk_compartment_ids[compartment_name], lifecycle_state="ACTIVE").data + for eachfwpolicy in fw_data: + if export_policies is not None: + eachfwpolicy1 = fwclient.get_network_firewall_policy(network_firewall_policy_id=eachfwpolicy.id).data fwpolicy_display_name1 = eachfwpolicy1.display_name - if (any(e in fwpolicy_display_name1 for e in export_policies)): + if (fwpolicy_display_name1 in export_policies): if clone: - if fwpolicy_display_name1 in export_policies: - if attached_policy_only == "y": - if eachfwpolicy1.attached_network_firewall_count == 0: - print("Skipping "+str(fwpolicy_display_name1) + " as it is not attached.") - continue - print("Cloning " + str(fwpolicy_display_name1) +" to "+str(target_pol[src_pol.index(fwpolicy_display_name1)]) ) - fwpolicies.append(eachfwpolicy) + if attached_policy_only == "y": + if eachfwpolicy1.attached_network_firewall_count == 0: + print("Skipping "+str(fwpolicy_display_name1) + " as it is not attached.") + continue + print("Cloning " + str(fwpolicy_display_name1) +" to "+str(target_pol[src_pol.index(fwpolicy_display_name1)]) ) + fwpolicies.append(eachfwpolicy) continue print("Processing "+str(fwpolicy_display_name1)) fwpolicies.append(eachfwpolicy) - else: - for eachfwpolicy in fw_data: + else: fwpolicies.append(eachfwpolicy) #fwpolicies.append(data) - values_for_column_fwpolicy = print_firewall_policy(region, ct, values_for_column_fwpolicy, fwpolicies,compartment_name) - values_for_column_fwaddress = print_firewall_address(region, ct, values_for_column_fwaddress, fwpolicies, fwpolicy) - values_for_column_fwurllist = print_firewall_urllist(region, ct, values_for_column_fwurllist, fwpolicies, fwpolicy) - values_for_column_fwservicelist = print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpolicies, fwpolicy) - values_for_column_fwapplist = print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, fwpolicy) - values_for_column_fwsecrules = print_firewall_secrules(region, ct, values_for_column_fwsecrules,fwpolicies, fwpolicy) - values_for_column_fwsecret = print_firewall_secret(region, ct, values_for_column_fwsecret, fwpolicies,fwpolicy, vault, compartment, kmsvault) - values_for_column_fwdecryptprofile = print_firewall_decryptprofile(region, ct,values_for_column_fwdecryptprofile,fwpolicies, fwpolicy) - values_for_column_fwdecryptrule = print_firewall_decryptrule(region, ct, values_for_column_fwdecryptrule,fwpolicies, fwpolicy) - + values_for_column_fwpolicy = print_firewall_policy(region, ct, values_for_column_fwpolicy, fwpolicies,compartment_name,state) + values_for_column_fwaddress = print_firewall_address(region, ct, values_for_column_fwaddress, fwpolicies, fwclient,state) + values_for_column_fwurllist = print_firewall_urllist(region, ct, values_for_column_fwurllist, fwpolicies, fwclient,state) + values_for_column_fwservicelist = print_firewall_servicelist(region, ct, values_for_column_fwservicelist, fwpolicies, fwclient,state) + values_for_column_fwapplist = print_firewall_applist(region, ct, values_for_column_fwapplist, fwpolicies, fwclient,state) + values_for_column_fwsecrules = print_firewall_secrules(region, ct, values_for_column_fwsecrules,fwpolicies, fwclient,state) + values_for_column_fwsecret = print_firewall_secret(region, ct, values_for_column_fwsecret, fwpolicies,fwclient, vault, compartment, kmsvault,state) + values_for_column_fwdecryptprofile = print_firewall_decryptprofile(region, ct,values_for_column_fwdecryptprofile,fwpolicies, fwclient,state) + values_for_column_fwdecryptrule = print_firewall_decryptrule(region, ct, values_for_column_fwdecryptrule,fwpolicies, fwclient,state) + print(importCommands_nfp[reg]) if clone: commonTools.write_to_cd3(values_for_column_fwpolicy, cd3file, "Firewall-Policy",append=True) commonTools.write_to_cd3(values_for_column_fwaddress, cd3file, "Firewall-Policy-AddressList",append=True) @@ -735,23 +752,24 @@ def export_firewallpolicy(inputfile, _outdir, service_dir, config, signer, ct, e print("Firewall Policies exported to CD3\n") # writing data + init_commands = f'\n######### Writing import for Network firewall policy Objects #########\n\n#!/bin/bash\n{tf_or_tofu} init' + importCommands_message = ["Policy","Address Objects","url list Objects","service list Objects","application list Objects","Security Rules Objects","Mapped Secret Objects","Decrypt profile Objects","decryption Rules Objects","policy Objects"] for reg in export_regions: - script_file = f'{outdir}/{reg}/{service_dir}/temppolicyfile' - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') - readfilepath = outdir + "/" + reg + "/" + service_dir + "/temppolicyfile" - writefilepath = outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_firewallpolicy_nonGF.sh" - input_file = open(readfilepath, "r") - output_file = open(writefilepath, "w") - lines_seen_so_far = set() - for line in input_file: - if not line.isspace() and line not in lines_seen_so_far: - output_file.write(line) - lines_seen_so_far.add(line) - if line in ['\n', '\r\n']: - output_file.write(line) - input_file.close() - output_file.close() - os.remove(readfilepath) - #os.chmod(outdir + "/" + reg + "/" + service_dir + "/tf_import_commands_firewallpolicy_nonGF.sh", 777) + count = 0 + all_importCommands = [importCommands_nfp[reg], importCommands_nfao[reg], importCommands_ulo[reg], importCommands_slo[reg], + importCommands_alo[reg], importCommands_sro[reg], importCommands_mso[reg], importCommands_dpo[reg], + importCommands_dro[reg], importCommands_fpo[reg]] + print(importCommands_nfp[reg]) + for item in all_importCommands: + if item != "": + importCommands[reg] += f'\n\n######### Writing import for Network firewall {importCommands_message[count]} #########\n\n' + importCommands[reg] += item + count += 1 + script_file = f'{outdir}/{reg}/{service_dir}/import_commands_firewallpolicy.sh' + + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) + diff --git a/cd3_automation_toolkit/Security/Firewall/fw_create.py b/cd3_automation_toolkit/Security/Firewall/fw_create.py index 09c2ad265..37535024a 100644 --- a/cd3_automation_toolkit/Security/Firewall/fw_create.py +++ b/cd3_automation_toolkit/Security/Firewall/fw_create.py @@ -48,6 +48,9 @@ def fw_create(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: firewall_str[reg] = '' firewall_names[reg] = [] + resource = sheetName.lower() + reg_out_dir = outdir + "/" + reg + "/" + service_dir + commonTools.backup_file(reg_out_dir, resource, firewall_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -167,12 +170,10 @@ def fw_create(inputfile, outdir, service_dir, prefix, ct): firewall_str[region] = firewall_str[region] + firewall.render(tempStr) for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + firewall_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, firewall_auto_tfvars_filename) if firewall_str[reg] != '': # Generate Final String src = "##Add New firewall for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create.py index 46d2020b6..18f97d618 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create.py @@ -49,6 +49,9 @@ def firewallpolicy_create(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: policy_str[reg] = '' policy_names[reg] = [] + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, policy_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -107,12 +110,12 @@ def firewallpolicy_create(inputfile, outdir, service_dir, prefix, ct): policy_str[region] = policy_str[region] + policy.render(tempStr) for reg in region_list: - resource = sheetName.lower() + reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + policy_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, policy_auto_tfvars_filename) + if policy_str[reg] != '': # Generate Final String src = "##Add New firewall policy for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_address.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_address.py index 2d493ec60..a7e90e0dc 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_address.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_address.py @@ -53,6 +53,9 @@ def fwpolicy_create_address(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: address_str[reg] = '' address_names[reg] = [] + resource = sheetName.lower() + reg_out_dir = outdir + "/" + reg + "/" + service_dir + commonTools.backup_file(reg_out_dir, resource, address_auto_tfvars_filename) # List of the column headers @@ -136,12 +139,11 @@ def fwpolicy_create_address(inputfile, outdir, service_dir, prefix, ct): for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + address_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, address_auto_tfvars_filename) + if address_str[reg] != '': # Generate Final String src = "##Add New addresses for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_applicationlist.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_applicationlist.py index 56d556f26..441b8a4df 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_applicationlist.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_applicationlist.py @@ -47,6 +47,9 @@ def fwpolicy_create_applicationlist(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: applicationlist_str[reg] = '' applicationlist_names[reg] = [] + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, applicationlist_auto_tfvars_filename) # List of the column headers @@ -137,12 +140,11 @@ def fwpolicy_create_applicationlist(inputfile, outdir, service_dir, prefix, ct): applicationlist_str[region] = applicationlist_str[region] + applicationlist.render(tempStr) for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + applicationlist_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, applicationlist_auto_tfvars_filename) + if applicationlist_str[reg] != '': # Generate Final String src = "##Add New application list for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_apps.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_apps.py index 95433123b..b8811c288 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_apps.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_apps.py @@ -54,6 +54,9 @@ def fwpolicy_create_apps(inputfile, outdir, service_dir, prefix, ct): apps_str[reg] = '' apps_names[reg] = [] apps_str_02[reg] = '' + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, apps_auto_tfvars_filename) # List of the column headers @@ -165,12 +168,11 @@ def fwpolicy_create_apps(inputfile, outdir, service_dir, prefix, ct): apps_str_02[region] = apps_str_02[region] + apps_str[region] for reg in region_list: - resource = "firewall-policy-apps" reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + apps_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, apps_auto_tfvars_filename) + if apps_str_02[reg] != '': # Generate Final String src = "##Add New apps for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptionprofile.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptionprofile.py index a6c7d18bf..5e6f61c06 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptionprofile.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptionprofile.py @@ -45,6 +45,9 @@ def fwpolicy_create_decryptionprofile(inputfile, outdir, service_dir, prefix, ct for reg in ct.all_regions: decryptionprofile_str[reg] = '' + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, decryptionprofile_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -109,12 +112,11 @@ def fwpolicy_create_decryptionprofile(inputfile, outdir, service_dir, prefix, ct for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + decryptionprofile_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, decryptionprofile_auto_tfvars_filename) + if decryptionprofile_str[reg] != '': # Generate Final String src = "##Add New Decryption Profile for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptrules.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptrules.py index 08783bbba..20991bd9f 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptrules.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_decryptrules.py @@ -47,6 +47,9 @@ def fwpolicy_create_decryptrules(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: decryptrules_str[reg] = '' decryptrules_names[reg] = [] + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, decryptrules_auto_tfvars_filename) # List of the column headers @@ -161,12 +164,11 @@ def fwpolicy_create_decryptrules(inputfile, outdir, service_dir, prefix, ct): for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + decryptrules_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, decryptrules_auto_tfvars_filename) + if decryptrules_str[reg] != '': # Generate Final String src = "##Add New Decryption rules for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secret.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secret.py index b7dc7cc73..cf2247a8d 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secret.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secret.py @@ -46,6 +46,9 @@ def fwpolicy_create_secret(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: secret_str[reg] = '' + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, secret_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -125,12 +128,11 @@ def fwpolicy_create_secret(inputfile, outdir, service_dir, prefix, ct): for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + secret_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, secret_auto_tfvars_filename) + if secret_str[reg] != '': # Generate Final String src = "##Add New Secrets for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secrules.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secrules.py index 64f608364..33fe4a81a 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secrules.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_secrules.py @@ -47,6 +47,9 @@ def fwpolicy_create_secrules(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: secrules_str[reg] = '' secrules_names[reg] = [] + resource = sheetName.lower() + reg_out_dir = outdir + "/" + reg + "/" + service_dir + commonTools.backup_file(reg_out_dir, resource, secrules_auto_tfvars_filename) # List of the column headers @@ -248,12 +251,11 @@ def fwpolicy_create_secrules(inputfile, outdir, service_dir, prefix, ct): for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + secrules_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, secrules_auto_tfvars_filename) + if secrules_str[reg] != '': # Generate Final String src = "##Add New Security rules for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_service.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_service.py index f4c604087..aa1d20735 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_service.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_service.py @@ -55,8 +55,9 @@ def fwpolicy_create_service(inputfile, outdir, service_dir, prefix, ct): service_str[reg] = '' service_names[reg] = [] service_str_02[reg] = '' - - + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = "firewall-policy-services" + commonTools.backup_file(reg_out_dir, resource, service_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() region_seen_so_far = [] @@ -190,12 +191,11 @@ def fwpolicy_create_service(inputfile, outdir, service_dir, prefix, ct): #print(service_str_02[region]) for reg in region_list: - resource = "firewall-policy-services" reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + service_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, service_auto_tfvars_filename) + if service_str_02[reg] != '': # Generate Final String src = "##Add New service policy for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_servicelist.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_servicelist.py index bf203e233..5e39aefa9 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_servicelist.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_servicelist.py @@ -56,8 +56,9 @@ def fwpolicy_create_servicelist(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: servicelist_str[reg] = '' servicelist_names[reg] = [] - - + reg_out_dir = outdir + "/" + reg + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir, resource, servicelist_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -156,12 +157,11 @@ def fwpolicy_create_servicelist(inputfile, outdir, service_dir, prefix, ct): servicelist_str[region] = servicelist_str[region] + servicelist.render(tempStr) for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + servicelist_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, servicelist_auto_tfvars_filename) + if servicelist_str[reg] != '': # Generate Final String src = "##Add New service list for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_urllist.py b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_urllist.py index b193e2a3c..2d860db4a 100644 --- a/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_urllist.py +++ b/cd3_automation_toolkit/Security/Firewall/fwpolicy_create_urllist.py @@ -51,7 +51,9 @@ def fwpolicy_create_urllist(inputfile, outdir, service_dir, prefix, ct): for reg in ct.all_regions: urllist_str[reg] = '' urllist_names[reg] = [] - + resource = sheetName.lower() + reg_out_dir = outdir + "/" + reg + "/" + service_dir + commonTools.backup_file(reg_out_dir, resource, urllist_auto_tfvars_filename) # List of the column headers dfcolumns = df.columns.values.tolist() @@ -138,12 +140,11 @@ def fwpolicy_create_urllist(inputfile, outdir, service_dir, prefix, ct): for reg in region_list: - resource = sheetName.lower() reg_out_dir = outdir + "/" + reg + "/" + service_dir if not os.path.exists(reg_out_dir): os.makedirs(reg_out_dir) outfile[reg] = reg_out_dir + "/" + urllist_auto_tfvars_filename - commonTools.backup_file(reg_out_dir, resource, urllist_auto_tfvars_filename) + if urllist_str[reg] != '': # Generate Final String src = "##Add New urllist for " + reg.lower() + " here##" diff --git a/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvault.py b/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvault.py deleted file mode 100644 index e3eb3dea4..000000000 --- a/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvault.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python3 -# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. -# -# This script will produce a Terraform file that will be used to set up OCI Security components -# Key/Vault -# -# Author: Suruchi Singla -# Oracle Consulting -# Modified (TF Upgrade): Shruthi Subramanian -# - -from jinja2 import Environment, FileSystemLoader -from pathlib import Path -from oci.config import DEFAULT_LOCATION -from commonTools import * - -###### -# Required Inputs- Config file, prefix AND outdir -###### -# Execution of the code begins here -def create_cis_keyvault(outdir, service_dir, service_dir_iam, prefix, ct, region_name, comp_name): - - # Declare variables - region_name = region_name.strip().lower() - comp_name = comp_name.strip() - - if region_name not in ct.all_regions: - print("Invalid Region!! Tenancy is not subscribed to this region. Please try again") - exit(1) - - - # Load the template file - file_loader = FileSystemLoader(f'{Path(__file__).parent}/templates') - env = Environment(loader=file_loader, keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) - vault_template = env.get_template('vaults-template') - key_template = env.get_template('keys-template') - - tempStr = {} - vaultStr = '' - keyStr = '' - auto_tfvars_filename = "cis-keyvault.auto.tfvars" - - compartmentVarName = commonTools.check_tf_variable(comp_name) - columnvalue = str(compartmentVarName) - tempStr['compartment_tf_name'] = columnvalue - - key_name = prefix+"-"+region_name+"-kms-key" - vault_name = prefix+"-"+region_name+"-kms-vault" - - tempStr['key_name'] = key_name - tempStr['key_tf_name'] = key_name - tempStr['vault_name'] = vault_name - tempStr['vault_tf_name'] = vault_name - tempStr['management_endpoint'] = vault_name - tempStr['algorithm'] = "AES" - - vaultStr = vaultStr + vault_template.render(tempStr) - keyStr= keyStr + key_template.render(tempStr) - - if vaultStr != '': - # Generate Final String - src = "##Add New Vaults for " + region_name + " here##" - vaultStr = vault_template.render(skeleton=True, count=0, region=region_name).replace(src, vaultStr+"\n"+src) - - if keyStr != '': - # Generate Final String - src = "##Add New Keys for " + region_name + " here##" - keyStr = key_template.render(skeleton=True, count=0, region=region_name).replace(src, keyStr+"\n"+src) - - finalstring = vaultStr + keyStr - finalstring = "".join([s for s in finalstring.strip().splitlines(True) if s.strip("\r\n").strip()]) - - if finalstring != "": - resource = "keyvault" - srcdir = outdir + "/" + region_name + "/" + service_dir +"/" - commonTools.backup_file(srcdir, resource, auto_tfvars_filename) - - # Write to TF file - outfile = outdir + "/" + region_name + "/" + service_dir + "/" + auto_tfvars_filename - oname = open(outfile, "w+") - print(outfile + " containing TF for Key/Vault has been created for region "+region_name) - oname.write(finalstring) - oname.close() diff --git a/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvaults.py b/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvaults.py index 9e751b680..64d08fec3 100644 --- a/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvaults.py +++ b/cd3_automation_toolkit/Security/KeyVault/create_terraform_keyvaults.py @@ -314,9 +314,6 @@ def create_terraform_keyvaults(inputfile, outdir, service_dir, prefix, ct): vaultStr[reg] += key_template.render(count=0, region=reg).replace(key_str, keyStr[reg] + "\n" + key_str) vaultStr[reg] = "".join([s for s in vaultStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource = sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) - oname = open(outfile, "w+") oname.write(vaultStr[reg]) oname.close() diff --git a/cd3_automation_toolkit/Security/KeyVault/export_keyvaults_nonGreenField.py b/cd3_automation_toolkit/Security/KeyVault/export_keyvaults_nonGreenField.py index 85b0074d0..e9dda66eb 100644 --- a/cd3_automation_toolkit/Security/KeyVault/export_keyvaults_nonGreenField.py +++ b/cd3_automation_toolkit/Security/KeyVault/export_keyvaults_nonGreenField.py @@ -12,13 +12,16 @@ import oci from oci.key_management import KmsVaultClient import os +import subprocess as sp sys.path.append(os.getcwd() + "/..") from commonTools import * # Execution of the code begins here def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_regions=[], export_compartments=[]): global values_for_column_kms - global cd3file + global cd3file,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] comp_id_list = list(ct.ntk_compartment_ids.values()) comp_name_list = list(ct.ntk_compartment_ids.keys()) @@ -47,12 +50,20 @@ def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_ for reg in export_regions: importCommands = "" region = reg.lower() - script_file = f'{outdir}/{region}/{service_dir}/tf_import_commands_kms_nonGF.sh' + script_file = f'{outdir}/{region}/{service_dir}/import_commands_kms.sh' # create backups if os.path.exists(script_file): commonTools.backup_file(os.path.dirname(script_file), "tf_import_kms", os.path.basename(script_file)) config["region"] = ct.region_dict[reg] + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass kms_vault_client = KmsVaultClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) for ntk_compartment_name in export_compartments: vaults = oci.pagination.list_call_get_all_results(kms_vault_client.list_vaults, @@ -63,12 +74,11 @@ def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_ get_vault_data = kms_vault_client.get_vault(vault_id=vault.id).data key_count = 0 if vault.lifecycle_state == "ACTIVE": - if importCommands == '': - importCommands += "\n######### Writing import for Vaults and Keys #########\n\n#!/bin/bash\nterraform init" total_vaults += 1 vault_tf_name = commonTools.check_tf_variable(vault.display_name) - - importCommands += f'\nterraform import "module.vaults[\\\"{vault_tf_name}\\\"].oci_kms_vault.vault" {vault.id}' + tf_resource = f'module.vaults[\\"{vault_tf_name}\\"].oci_kms_vault.vault' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" {vault.id}' kms_key_client = oci.key_management.KmsManagementClient(config, service_endpoint=vault.management_endpoint) keys = oci.pagination.list_call_get_all_results(kms_key_client.list_keys, @@ -81,7 +91,9 @@ def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_ key_count += 1 total_keys += 1 key_tf_name = commonTools.check_tf_variable(key.display_name) - importCommands += f'\nterraform import "module.keys[\\\"{key_tf_name}\\\"].oci_kms_key.key" managementEndpoint/{vault.management_endpoint}/keys/{key.id}' + tf_resource = f'module.keys[\\"{key_tf_name}\\"].oci_kms_key.key' + if tf_resource not in state["resources"]: + importCommands += f'\n{tf_or_tofu} import "{tf_resource}" managementEndpoint/{vault.management_endpoint}/keys/{key.id}' get_key_data = kms_key_client.get_key(key_id=key.id).data if get_key_data.vault_id == vault.id and get_key_data.lifecycle_state != "PENDING_DELETION": if key_count == 1: @@ -129,9 +141,9 @@ def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_ elif col_header == 'Curve Id': values_for_column_kms[col_header].append(get_key_data.key_shape.curve_id if get_key_data.key_shape.algorithm == 'ECDSA' else '') elif col_header == 'Auto rotation': - values_for_column_kms[col_header].append("TRUE" if get_key_data.is_auto_rotation_enabled else "FALSE") + values_for_column_kms[col_header].append("TRUE" if get_key_data.is_auto_rotation_enabled==True else "FALSE") elif col_header == 'Rotation interval in days': - values_for_column_kms[col_header].append(get_key_data.auto_key_rotation_details.rotation_interval_in_days if get_key_data.is_auto_rotation_enabled else '') + values_for_column_kms[col_header].append(get_key_data.auto_key_rotation_details.rotation_interval_in_days if hasattr(get_key_data.auto_key_rotation_details, 'rotation_interval_in_days') else '') elif str(col_header).lower() in ["key defined tags" , "key freeform tags"]: if len(key.defined_tags) != 0: values_for_column_kms = commonTools.export_tags(key, col_header, values_for_column_kms) @@ -159,11 +171,9 @@ def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_ values_for_column_kms[col_header].append( get_key_data.key_shape.curve_id if get_key_data.key_shape.algorithm == 'ECDSA' else '') elif col_header == 'Auto rotation': - values_for_column_kms[col_header].append( - "TRUE" if get_key_data.is_auto_rotation_enabled else "FALSE") + values_for_column_kms[col_header].append("TRUE" if get_key_data.is_auto_rotation_enabled==True else "FALSE") elif col_header == 'Rotation interval in days': - values_for_column_kms[col_header].append( - get_key_data.auto_key_rotation_details.rotation_interval_in_days if get_key_data.is_auto_rotation_enabled else '') + values_for_column_kms[col_header].append(get_key_data.auto_key_rotation_details.rotation_interval_in_days if hasattr(get_key_data.auto_key_rotation_details,'rotation_interval_in_days') else '') elif str(col_header).lower() in ["key defined tags", "key freeform tags"]: if len(key.defined_tags) != 0: values_for_column_kms = commonTools.export_tags(key, col_header, @@ -210,10 +220,12 @@ def export_keyvaults(inputfile, outdir, service_dir, config, signer, ct, export_ values_for_column_kms) #Write Import Commands to script file - if importCommands!="": - importCommands += "\nterraform plan\n" + init_commands = f'\n######### Writing import for OCI Vaults #########\n\n#!/bin/bash\n{tf_or_tofu} init' + + if importCommands != "": + importCommands += f'\n{tf_or_tofu} plan\n' with open(script_file, 'a') as importCommandsfile: - importCommandsfile.write(importCommands) + importCommandsfile.write(init_commands + importCommands) #Write resource data to input Excel sheet commonTools.write_to_cd3(values_for_column_kms, cd3file, sheetName) diff --git a/cd3_automation_toolkit/Storage/BlockVolume/create_terraform_block_volumes.py b/cd3_automation_toolkit/Storage/BlockVolume/create_terraform_block_volumes.py index dfe1f497b..75b683258 100644 --- a/cd3_automation_toolkit/Storage/BlockVolume/create_terraform_block_volumes.py +++ b/cd3_automation_toolkit/Storage/BlockVolume/create_terraform_block_volumes.py @@ -47,6 +47,9 @@ def create_terraform_block_volumes(inputfile, outdir, service_dir, prefix,ct): # Take backup of files for eachregion in ct.all_regions: tfStr[eachregion] = '' + reg_out_dir = outdir + "/" + eachregion + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) for i in df.index: @@ -265,9 +268,6 @@ def create_terraform_block_volumes(inputfile, outdir, service_dir, prefix,ct): tfStr[reg] = template.render(count=0, region=reg).replace(src,tfStr[reg]) tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) - resource=sheetName.lower() - commonTools.backup_file(reg_out_dir + "/", resource, auto_tfvars_filename) - # Write to TF file tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) outfile = reg_out_dir+ "/" + auto_tfvars_filename diff --git a/cd3_automation_toolkit/Storage/BlockVolume/export_blockvolumes_nonGreenField.py b/cd3_automation_toolkit/Storage/BlockVolume/export_blockvolumes_nonGreenField.py index 1ed17c990..b015a6c8d 100644 --- a/cd3_automation_toolkit/Storage/BlockVolume/export_blockvolumes_nonGreenField.py +++ b/cd3_automation_toolkit/Storage/BlockVolume/export_blockvolumes_nonGreenField.py @@ -14,6 +14,7 @@ from oci.core.blockstorage_client import BlockstorageClient from oci.core.compute_client import ComputeClient from commonTools import * +import subprocess as sp importCommands = {} oci_obj_names = {} @@ -61,7 +62,7 @@ def volume_attachment_info(compute,ct,volume_id,export_compartments): return attachments,attachment_id, instance_name, attachment_type -def print_blockvolumes(region, BVOLS, bvol, compute, ct, values_for_column, ntk_compartment_name, display_names, ad_names,export_compartments): +def print_blockvolumes(region, BVOLS, bvol, compute, ct, values_for_column, ntk_compartment_name, display_names, ad_names,export_compartments,state): volume_comp = '' for blockvols in BVOLS.data: volume_id = blockvols.id @@ -144,13 +145,17 @@ def print_blockvolumes(region, BVOLS, bvol, compute, ct, values_for_column, ntk_ if volume_compartment_id == comp_id and volume_compartment_id not in comp_done_ids: volume_comp = comp_name comp_done_ids.append(volume_compartment_id) + tf_resource = f'module.block-volumes[\\"{block_tf_name}\\"].oci_core_volume.block_volume' + if tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(blockvols.id)}' - importCommands[region.lower()].write("\nterraform import \"module.block-volumes[\\\"" + block_tf_name + "\\\"].oci_core_volume.block_volume\" " + str(blockvols.id)) - if attachment_id != '': - importCommands[region.lower()].write("\nterraform import \"module.block-volumes[\\\"" + block_tf_name + "\\\"].oci_core_volume_attachment.block_vol_instance_attachment[0]\" " + str(attachment_id)) + tf_resource = f'module.block-volumes[\\"{block_tf_name}\\"].oci_core_volume_attachment.block_vol_instance_attachment[0]' + if attachment_id != '' and tf_resource not in state["resources"]: + importCommands[region.lower()] += f'\n{tf_or_tofu} import "{tf_resource}" {str(attachment_id)}' - if asset_assignment_id != '': - importCommands[region.lower()].write("\nterraform import \"module.block-volumes[\\\"" + block_tf_name + "\\\"].oci_core_volume_backup_policy_assignment.volume_backup_policy_assignment[0]\" " + str(asset_assignment_id)) + tf_resource = f'module.block-volumes[\\"{block_tf_name}\\"].oci_core_volume_backup_policy_assignment.volume_backup_policy_assignment[0]' + if asset_assignment_id != '' and tf_resource not in state["resources"]: + importCommands[region.lower()]+= f'\n{tf_or_tofu} import "{tf_resource}" {str(asset_assignment_id)}' pass for col_header in values_for_column: if col_header == 'Region': @@ -199,7 +204,9 @@ def export_blockvolumes(inputfile, outdir, service_dir, config, signer, ct, expo global values_for_vcninfo global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): @@ -217,30 +224,34 @@ def export_blockvolumes(inputfile, outdir, service_dir, config, signer, ct, expo print("Tabs- BlockVolumes will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): - commonTools.backup_file(outdir + "/" + reg +"/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) + importCommands[reg] = '' # Fetch Block Volume Details print("\nFetching details of Block Volumes...") for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Block Volumes #########\n\n") config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"], stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass region = reg.capitalize() compute = ComputeClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) bvol = BlockstorageClient(config=config,retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,signer=signer) for ntk_compartment_name in export_compartments: BVOLS = oci.pagination.list_call_get_all_results(bvol.list_volumes,compartment_id=ct.ntk_compartment_ids[ntk_compartment_name],lifecycle_state="AVAILABLE") - print_blockvolumes(region, BVOLS, bvol, compute, ct, values_for_column, ntk_compartment_name, display_names, ad_names, export_compartments) + print_blockvolumes(region, BVOLS, bvol, compute, ct, values_for_column, ntk_compartment_name, display_names, ad_names, export_compartments,state) # writing volume source into variables file var_data = {} @@ -268,10 +279,12 @@ def export_blockvolumes(inputfile, outdir, service_dir, config, signer, ct, expo commonTools.write_to_cd3(values_for_column, cd3file, sheetName) print("{0} Block Volumes exported into CD3.\n".format(len(values_for_column["Region"]))) - # writing data + init_commands = f'\n#!/bin/bash\n{tf_or_tofu} init\n######### Writing import for Block Volumes #########\n' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Storage/FileSystem/create_terraform_fss.py b/cd3_automation_toolkit/Storage/FileSystem/create_terraform_fss.py index a0cb28d3d..e3108eb47 100644 --- a/cd3_automation_toolkit/Storage/FileSystem/create_terraform_fss.py +++ b/cd3_automation_toolkit/Storage/FileSystem/create_terraform_fss.py @@ -167,7 +167,7 @@ def fss_exports(i, df, tempStr): srcdir = outdir + "/" + eachregion + "/" + service_dir + "/" commonTools.backup_file(srcdir, resource, auto_tfvars_filename) - subnets = parseSubnets(filename) + #subnets = parseSubnets(filename) fss_tf_name = '' for i in df.index: @@ -189,7 +189,7 @@ def fss_exports(i, df, tempStr): if region in commonTools.endNames: break - if region.lower() == 'nan' and str(df.loc[i, 'Compartment Name']).strip().lower() == 'nan' and str(df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).strip().lower() == 'nan' and str(df.loc[i, 'MountTarget Name']).strip().lower() == 'nan' and str(df.loc[i, 'MountTarget SubnetName']).strip().lower() == 'nan': + if region.lower() == 'nan' and str(df.loc[i, 'Compartment Name']).strip().lower() == 'nan' and str(df.loc[i, 'Availability Domain(AD1|AD2|AD3)']).strip().lower() == 'nan' and str(df.loc[i, 'MountTarget Name']).strip().lower() == 'nan' and str(df.loc[i, 'Network Details']).strip().lower() == 'nan': continue region = str(region).lower().strip() @@ -232,23 +232,26 @@ def fss_exports(i, df, tempStr): subnet_id = '' network_compartment_id='' vcn_name='' - if columnname == 'MountTarget SubnetName': - subnet_tf_name = columnvalue.strip() - if ("ocid1.subnet.oc1" in subnet_tf_name): - network_compartment_id = "" + if columnname == 'Network Details': + columnvalue = columnvalue.strip() + if ("ocid1.subnet.oc" in columnvalue): + network_compartment_id = "root" vcn_name = "" - subnet_id = subnet_tf_name - elif subnet_tf_name.lower()!='nan' and subnet_tf_name.lower()!='': - try: - key = region, subnet_tf_name - network_compartment_id = subnets.vcn_subnet_map[key][0] - vcn_name = subnets.vcn_subnet_map[key][1] - subnet_id = subnets.vcn_subnet_map[key][2] - except Exception as e: - print("Invalid Subnet Name specified for row " + str(i + 3) + ". It Doesnt exist in Subnets sheet. Exiting!!!") + subnet_id = columnvalue + elif columnvalue.lower()!='nan' and columnvalue.lower()!='': + if len(columnvalue.split("@")) == 2: + network_compartment_id = commonTools.check_tf_variable(columnvalue.split("@")[0].strip()) + vcn_subnet_name = columnvalue.split("@")[1].strip() + else: + network_compartment_id = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) + vcn_subnet_name = columnvalue + if("::" not in vcn_subnet_name): + print("Invalid Network Details format specified for row " + str(i + 3) + ". Exiting!!!") exit(1) - - tempdict = {'network_compartment_id': commonTools.check_tf_variable(network_compartment_id), 'vcn_name': vcn_name, + else: + vcn_name=vcn_subnet_name.split("::")[0].strip() + subnet_id = vcn_subnet_name.split("::")[1].strip() + tempdict = {'network_compartment_id': network_compartment_id, 'vcn_name': vcn_name, 'subnet_id': subnet_id} if columnname == "Access (READ_ONLY|READ_WRITE)": @@ -366,16 +369,12 @@ def fss_exports(i, df, tempStr): tempStr.update(tempdict) if columnname == "Snapshot Policy": if columnvalue != '': - if "@" in columnvalue: - if len(columnvalue.split("@")) == 2: + if len(columnvalue.split("@")) == 2: snapshot_policy_comp = columnvalue.split("@")[0].strip() snapshot_policy_comp = commonTools.check_tf_variable(snapshot_policy_comp) snapshot_policy_name = columnvalue.split("@")[1].strip() - else: - snapshot_policy_comp = '' - snapshot_policy_name = '' else: - snapshot_policy_comp = '' + snapshot_policy_comp = commonTools.check_tf_variable(str(df.loc[i, 'Compartment Name']).strip()) snapshot_policy_name = columnvalue.strip() else: snapshot_policy_comp = '' diff --git a/cd3_automation_toolkit/Storage/FileSystem/export_fss_nonGreenField.py b/cd3_automation_toolkit/Storage/FileSystem/export_fss_nonGreenField.py index 5e691f90b..aa1994faa 100644 --- a/cd3_automation_toolkit/Storage/FileSystem/export_fss_nonGreenField.py +++ b/cd3_automation_toolkit/Storage/FileSystem/export_fss_nonGreenField.py @@ -9,6 +9,7 @@ import re from oci.config import DEFAULT_LOCATION from commonTools import * +import subprocess as sp fs_source_snapshots = {} fss_all_dict = {} @@ -27,7 +28,7 @@ def add_column_data(reg, cname, AD_name, mt_display_name, vplussubnet, mnt_p_ip, values_for_column_fss[col_header].append(AD_name) elif (col_header == "MountTarget Name"): values_for_column_fss[col_header].append(mt_display_name) - elif (col_header == "MountTarget SubnetName"): + elif (col_header == "Network Details"): values_for_column_fss[col_header].append(vplussubnet) elif (col_header == "MountTarget IP"): values_for_column_fss[col_header].append(mnt_p_ip) @@ -90,7 +91,7 @@ def add_column_data(reg, cname, AD_name, mt_display_name, vplussubnet, mnt_p_ip, values_for_column_fss) -def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availability_domain_name, signer): +def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availability_domain_name, signer,state): file_system = oci.file_storage.FileStorageClient(config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) network = oci.core.VirtualNetworkClient(config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) @@ -101,13 +102,12 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili try: mount_info = oci.pagination.list_call_get_all_results(file_system.list_mount_targets, compartment_id=compartment_id, - availability_domain=availability_domain_name) + availability_domain=availability_domain_name,sort_by="TIMECREATED") list_replications = oci.pagination.list_call_get_all_results(file_system.list_replications, compartment_id=compartment_id, - availability_domain=availability_domain_name) + availability_domain=availability_domain_name,sort_by="timeCreated") list_fss = oci.pagination.list_call_get_all_results(file_system.list_file_systems, - compartment_id=compartment_id, - availability_domain=availability_domain_name) + compartment_id=compartment_id,availability_domain=availability_domain_name,sort_by="TIMECREATED") for fss in list_fss.data: fss_all_dict[fss.id] = fss.display_name replications_dict = {} @@ -124,13 +124,13 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili mnt_info_dict = {} mnt_with_export = [] for mnt in mount_info.data: - mnt_id = mnt.id + mnt_id = str(mnt.id) export_set_id = mnt.export_set_id # Export Set Id mt_display_name = mnt.display_name # Mount Target Name tf_name = commonTools.check_tf_variable(mt_display_name) - importCommands[reg].write( - "\nterraform import \"module.mts[\\\"" + tf_name + "\\\"].oci_file_storage_mount_target.mount_target\" " + str( - mnt_id)) + tf_resource = f'module.mts[\\"{tf_name}\\"].oci_file_storage_mount_target.mount_target' + if tf_resource not in state["resources"]: + importCommands[reg]+=f'\n{tf_or_tofu} import "{tf_resource}" {mnt_id}' subnet_id = mnt.subnet_id private_ip_ids = mnt.private_ip_ids nsg_id = mnt.nsg_ids @@ -143,7 +143,14 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili subnet_info = vnc_info.get_subnet(subnet_id) mnt_sub_name = subnet_info.data.display_name # Subnet-Name vnc_name = vnc_info.get_vcn(subnet_info.data.vcn_id).data.display_name # vcn-Name - vplussubnet = vnc_name + "_" + mnt_sub_name + ntk_compartment_id = vnc_info.get_vcn(subnet_info.data.vcn_id).data.compartment_id # compartment-id + network_compartment_name=cname + for comp_name, comp_id in ntk_compartment_ids.items(): + if comp_id == ntk_compartment_id: + network_compartment_name = comp_name + + + vplussubnet = network_compartment_name+"@"+vnc_name + "::" + mnt_sub_name for ips in private_ip_ids: private_address = vnc_info.get_private_ip(ips) @@ -179,6 +186,7 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili fs_source_snapshot_id = fs_name fs_snapshot_policy_id = file_system_info.data.filesystem_snapshot_policy_id if fs_snapshot_policy_id != '': + policy_comp_name=cname snapshot_policy_info = file_system.get_filesystem_snapshot_policy(filesystem_snapshot_policy_id=fs_snapshot_policy_id) policy_name = snapshot_policy_info.data.display_name policy_comp_id = snapshot_policy_info.data.compartment_id @@ -195,6 +203,8 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili for id,name in fss_all_dict.items(): if id == v['targetid']: targetid = name + else: + targetid = v['targetid'] rep_format = targetid + "::" + str(v['interval']) + "::" + v['displayname'] fss_replication = fss_replication + rep_format + '\n' @@ -202,18 +212,19 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili if (str(fs_id) not in fss): # print(mt_display_name,"-",str(fs_name)) tf_name = commonTools.check_tf_variable(fs_name) - importCommands[reg].write( - "\nterraform import \"module.fss[\\\"" + tf_name + "\\\"].oci_file_storage_file_system.file_system\" " + str( - fs_id)) + tf_resource = f'module.fss[\\"{tf_name}\\"].oci_file_storage_file_system.file_system' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {fs_id}' + fss.append(str(fs_id)) if len(replications_dict) > 0: for k, v in replications_dict.items(): if v['sourceid'] == fs_id: if (str(k) not in rep_ids): tf_rep_name = commonTools.check_tf_variable(v['displayname'].strip()) - importCommands[reg].write( - "\nterraform import \"module.fss-replication[\\\"" + tf_rep_name + "\\\"].oci_file_storage_replication.file_system_replication\" " + str( - k)) + tf_resource = f'module.fss-replication[\\"{tf_rep_name}\\"].oci_file_storage_replication.file_system_replication' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {str(k)}' rep_ids.append(str(k)) elen = (len(einfo_export_data.export_options)) @@ -262,9 +273,10 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili tf_name = commonTools.check_tf_variable( "FSE-" + commonTools.check_tf_variable(mt_display_name) + "-" + commonTools.check_tf_variable( fs_name) + "-" + einfo_path[1:]) - importCommands[reg].write( - "\nterraform import \"module.fss-export-options[\\\"" + tf_name + "\\\"].oci_file_storage_export.export\" " + str( - einfo.id)) # exports import + tf_resource = f'module.fss-export-options[\\"{tf_name}\\"].oci_file_storage_export.export' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {str(einfo.id)}' + ###### code to fetch FSS without any exports ##### fss_all_ids = [] @@ -291,6 +303,7 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili snapshot_policy_info = file_system.get_filesystem_snapshot_policy(filesystem_snapshot_policy_id=fs_snapshot_policy_id) policy_name = snapshot_policy_info.data.display_name policy_comp_id = snapshot_policy_info.data.compartment_id + policy_comp_name=cname for comp_name, comp_id in ntk_compartment_ids.items(): if comp_id == policy_comp_id: policy_comp_name = comp_name @@ -303,6 +316,8 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili for id, name in fss_all_dict.items(): if id == v['targetid']: targetid = name + else: + targetid = v['targetid'] rep_format = targetid + "::" + str(v['interval']) + "::" + v['displayname'] fss_replication = fss_replication + rep_format + '\n' @@ -315,9 +330,9 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili if (str(fss_id) not in fss): # print(mt_display_name,"-",str(fs_name)) tf_name = commonTools.check_tf_variable(fs_name) - importCommands[reg].write( - "\nterraform import \"module.fss[\\\"" + tf_name + "\\\"].oci_file_storage_file_system.file_system\" " + str( - fss_id)) + tf_resource = f'module.fss[\\"{tf_name}\\"].oci_file_storage_file_system.file_system' + if tf_resource not in state["resources"]: + importCommands[reg] += f'\n{tf_or_tofu} import "{tf_resource}" {str(fss_id)}' fss.append(str(fss_id)) ###### code to fetch MT without any exports ##### @@ -345,6 +360,9 @@ def __get_mount_info(cname, ntk_compartment_ids, compartment_id, reg, availabili # Execution of the code begins here def export_fss(inputfile, outdir, service_dir, config1, signer1, ct, export_compartments=[], export_regions=[]): + global tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] input_compartment_names = export_compartments cd3file = inputfile @@ -385,25 +403,29 @@ def export_fss(inputfile, outdir, service_dir, config1, signer1, ct, export_comp all_ads.append(aval.name) # backup of .sh file - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir + "/", resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") - + importCommands[reg] ='' for reg in export_regions: config.__setitem__("region", ct.region_dict[reg]) + state = {'path': f'{outdir}/{reg}/{service_dir}', 'resources': []} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"", "\\\"")) + except Exception as e: + pass for ntk_compartment_name in export_compartments: ads = oci.identity.IdentityClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) for aval in ads.list_availability_domains(compartment_id=config['tenancy']).data: __get_mount_info(ntk_compartment_name, ct.ntk_compartment_ids, ct.ntk_compartment_ids[ntk_compartment_name], reg, aval.name, - signer) + signer,state) # writing volume source into variables file var_data = {} @@ -433,5 +455,8 @@ def export_fss(inputfile, outdir, service_dir, config1, signer1, ct, export_comp # writing data for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + init_commands = f'\n######### Writing import for File Storage #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands + importCommands[reg]) diff --git a/cd3_automation_toolkit/Storage/ObjectStorage/create_terraform_oss.py b/cd3_automation_toolkit/Storage/ObjectStorage/create_terraform_oss.py index de2a30571..ab77d99bb 100644 --- a/cd3_automation_toolkit/Storage/ObjectStorage/create_terraform_oss.py +++ b/cd3_automation_toolkit/Storage/ObjectStorage/create_terraform_oss.py @@ -54,6 +54,9 @@ def create_terraform_oss(inputfile, outdir, service_dir, prefix, ct): # Initialise empty TF string for each region to take backup of files for eachregion in ct.all_regions: tfStr[eachregion] = '' + srcdir = outdir + "/" + eachregion + "/" + service_dir + resource = sheetName.lower() + commonTools.backup_file(srcdir + "/", resource, auto_tfvars_filename) #Declaration bucket_lifecycle_policy = {} @@ -340,6 +343,8 @@ def create_terraform_oss(inputfile, outdir, service_dir, prefix, ct): src = "##Add New OSS Buckets for " + reg.lower() + " here##" tfStr[reg] = oss_template.render(count = 0, region = reg).replace(src, tfStr[reg] + "\n" + src) tfStr[reg] = "".join([s for s in tfStr[reg].strip().splitlines(True) if s.strip("\r\n").strip()]) + + oname[reg]=open(outfile[reg],'w') oname[reg].write(tfStr[reg]) oname[reg].close() diff --git a/cd3_automation_toolkit/Storage/ObjectStorage/export_terraform_oss.py b/cd3_automation_toolkit/Storage/ObjectStorage/export_terraform_oss.py index cb8a02792..425d1361f 100644 --- a/cd3_automation_toolkit/Storage/ObjectStorage/export_terraform_oss.py +++ b/cd3_automation_toolkit/Storage/ObjectStorage/export_terraform_oss.py @@ -19,21 +19,26 @@ sys.path.append(os.getcwd()+"/..") from commonTools import * from dateutil import parser +import subprocess as sp importCommands = {} oci_obj_names = {} -def print_buckets(region, outdir, service_dir, bucket_data, values_for_column, ntk_compartment_name,namespace_name, rp_id, retention_rule_data, rp_details, rp_name,lf_name_list,lf_name,lf_mapping,lf_excl,lf_incl,lf_prefix,ta_map,tgt_map): +def print_buckets(region, outdir, service_dir,state, bucket_data, values_for_column, ntk_compartment_name,namespace_name, rp_id, retention_rule_data, rp_details, rp_name,lf_name_list,lf_name,lf_mapping,lf_excl,lf_incl,lf_prefix,ta_map,tgt_map): buckets_tf_name = commonTools.check_tf_variable(bucket_data.name) - importCommands[region.lower()].write(f'\nterraform import "module.oss-buckets[\\"{buckets_tf_name}\\"].oci_objectstorage_bucket.bucket" 'f'n/{namespace_name}/b/{bucket_data.name}') + tf_resource = f'module.oss-buckets[\\"{buckets_tf_name}\\"].oci_objectstorage_bucket.bucket' + if tf_resource not in state["resources"]: + importCommands[region.lower()]+=f'\n{tf_or_tofu} import "{tf_resource}" n/{namespace_name}/b/{bucket_data.name}' - if rp_name: - importCommands[region.lower()].write(f'\nterraform import "module.oss-buckets[\\"{buckets_tf_name}\\"].oci_objectstorage_replication_policy.replication_policy[0]" 'f'n/{namespace_name}/b/{bucket_data.name}/replicationPolicies/{rp_id}') + tf_resource = f'module.oss-buckets[\\"{buckets_tf_name}\\"].oci_objectstorage_replication_policy.replication_policy[0]' + if rp_name and tf_resource not in state["resources"]: + importCommands[region.lower()]+=f'\n{tf_or_tofu} import "{tf_resource}" n/{namespace_name}/b/{bucket_data.name}/replicationPolicies/{rp_id}' - if bucket_data.object_lifecycle_policy_etag != None: - importCommands[region.lower()].write(f'\nterraform import "module.oss-buckets[\\"{buckets_tf_name}\\"].oci_objectstorage_object_lifecycle_policy.lifecycle_policy[0]" 'f'n/{namespace_name}/b/{bucket_data.name}/l') + tf_resource = f'module.oss-buckets[\\"{buckets_tf_name}\\"].oci_objectstorage_object_lifecycle_policy.lifecycle_policy[0]' + if bucket_data.object_lifecycle_policy_etag != None and tf_resource not in state["resources"]: + importCommands[region.lower()]+=f'\n{tf_or_tofu} import "{tf_resource}" n/{namespace_name}/b/{bucket_data.name}/l' lf_names = lf_name_list if lf_name_list else [''] for lf_name in lf_names: @@ -155,8 +160,10 @@ def export_buckets(inputfile, outdir, service_dir, config, signer, ct, export_co global importCommands global cd3file global reg - global values_for_column + global values_for_column,tf_or_tofu + tf_or_tofu = ct.tf_or_tofu + tf_state_list = [tf_or_tofu, "state", "list"] cd3file = inputfile if ('.xls' not in cd3file): print("\nAcceptable cd3 format: .xlsx") @@ -175,41 +182,49 @@ def export_buckets(inputfile, outdir, service_dir, config, signer, ct, export_co print("Tabs- Buckets will be overwritten during export process!!!\n") # Create backups - resource = 'tf_import_' + sheetName.lower() - file_name = 'tf_import_commands_' + sheetName.lower() + '_nonGF.sh' + resource = 'import_' + sheetName.lower() + file_name = 'import_commands_' + sheetName.lower() + '.sh' for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name if (os.path.exists(script_file)): commonTools.backup_file(outdir + "/" + reg + "/" + service_dir, resource, file_name) - importCommands[reg] = open(script_file, "w") - importCommands[reg].write("#!/bin/bash") - importCommands[reg].write("\n") - importCommands[reg].write("terraform init") + importCommands[reg] = '' # Fetch Bucket Details print("\nFetching details of Buckets...") lifecycle_map = {} + total_resources=0 for reg in export_regions: - importCommands[reg].write("\n\n######### Writing import for Buckets #########\n\n") config.__setitem__("region", ct.region_dict[reg]) region = reg.capitalize() buckets_client = ObjectStorageClient(config=config, retry_strategy = oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) namespace = buckets_client.get_namespace().data namespace_name = namespace + state = {'path':f'{outdir}/{reg}/{service_dir}','resources':[]} + try: + byteOutput = sp.check_output(tf_state_list, cwd=state["path"],stderr=sp.DEVNULL ) + output = byteOutput.decode('UTF-8').rstrip() + for item in output.split('\n'): + state["resources"].append(item.replace("\"","\\\"")) + except Exception as e: + pass + for ntk_compartment_name in export_compartments: ossbuckets = oci.pagination.list_call_get_all_results(buckets_client.list_buckets,namespace,compartment_id = ct.ntk_compartment_ids[ntk_compartment_name]) for bucket in ossbuckets.data: + bucket_name = bucket.name ##buckets info## try: bucket_data = buckets_client.get_bucket(namespace_name, bucket_name, fields=['autoTiering']).data except Exception as e: print("Skipping Bucket "+bucket_name +" because of some issue. Check OCI console for details") + bucket_data=None continue - + total_resources+=1 #Get Retention Policies for bucket retention_policies = buckets_client.list_retention_rules(namespace_name, bucket_name).data retention_rule_data_list = [] @@ -315,13 +330,17 @@ def export_buckets(inputfile, outdir, service_dir, config, signer, ct, export_co else: lf_prefix[lf_name] = [lf_inclusion_prefixes] - print_buckets(region, outdir, service_dir,bucket_data, values_for_column, ntk_compartment_name, namespace_name,rp_id,retention_rule_data,rp_details,rp_name,lf_name_list,lf_name,lf_mapping,lf_excl,lf_incl,lf_prefix,ta_map,tgt_map) + print_buckets(region, outdir, service_dir,state,bucket_data, values_for_column, ntk_compartment_name, namespace_name,rp_id,retention_rule_data,rp_details,rp_name,lf_name_list,lf_name,lf_mapping,lf_excl,lf_incl,lf_prefix,ta_map,tgt_map) commonTools.write_to_cd3(values_for_column, cd3file, sheetName) - print("{0} Buckets exported into CD3.\n".format(len(values_for_column["Region"]))) + print("{0} Buckets exported into CD3.\n".format(total_resources)) + # writing data for reg in export_regions: script_file = f'{outdir}/{reg}/{service_dir}/' + file_name - with open(script_file, 'a') as importCommands[reg]: - importCommands[reg].write('\n\nterraform plan\n') + init_commands = f'\n######### Writing import for Buckets #########\n\n#!/bin/bash\n{tf_or_tofu} init' + if importCommands[reg] != "": + importCommands[reg] += f'\n{tf_or_tofu} plan\n' + with open(script_file, 'a') as importCommandsfile: + importCommandsfile.write(init_commands+importCommands[reg]) \ No newline at end of file diff --git a/cd3_automation_toolkit/cd3FirewallValidator.py b/cd3_automation_toolkit/cd3FirewallValidator.py index c470602c3..c1d106cf4 100644 --- a/cd3_automation_toolkit/cd3FirewallValidator.py +++ b/cd3_automation_toolkit/cd3FirewallValidator.py @@ -1160,4 +1160,6 @@ def validate_firewall_cd3(filename, var_file, prefix, outdir, config,signer,ct): print("\n\nSummary:") print("=======") print("There are no errors in CD3. Please proceed with TF Generation\n") - return "No Error" \ No newline at end of file + return "No Error" + + diff --git a/cd3_automation_toolkit/cd3Validator.py b/cd3_automation_toolkit/cd3Validator.py index 24f79fc98..21bb0d814 100644 --- a/cd3_automation_toolkit/cd3Validator.py +++ b/cd3_automation_toolkit/cd3Validator.py @@ -742,11 +742,15 @@ def validate_dns(filename,comp_ids): rtype = str(dfdns.loc[i, 'RType']).strip() rdata = str(dfdns.loc[i, 'RDATA']).strip() ttl = str(dfdns.loc[i, 'TTL']).strip() - if zone_name.lower() != 'nan' and (domain_name.lower() == 'nan' or rtype.lower() == 'nan' or rdata.lower() == 'nan' or ttl.lower() == 'nan'): - log(f'ROW {i + 3} : Please validate domain, rtype, rdata and ttl for zone {zone_name}. It can not be null') + nan_count = 0 + for item in [domain_name,rtype,rdata,ttl]: + if item.lower() == 'nan': + nan_count +=1 + if nan_count in [1,2,3]: + log(f'ROW {i + 3} : one or more of the required( Domain, RType, RDATA and TTL) parameter is missing for a record creation') mandat_val_check = True - if (domain_name.lower() != 'nan' or rtype.lower() != 'nan' or rdata.lower() != 'nan' or ttl.lower() != 'nan') and zone_name.lower == 'nan': + if 'nan' not in [domain_name.lower(),rtype.lower(),rdata.lower(),ttl.lower()] and zone_name.lower() == 'nan': log(f'ROW {i + 3} : Zone name can not be null') mandat_val_check = True @@ -886,20 +890,23 @@ def validate_instances(filename,comp_ids,subnetobj,vcn_subnet_list,vcn_nsg_list) log(f'ROW {i+3} : Empty value at column Display Name') inst_empty_check = True - if columnname == 'Subnet Name': + if columnname == 'Network Details': if columnvalue.lower()=='nan': - log(f'ROW {i+3} : Empty value at column Subnet Name.') + log(f'ROW {i+3} : Empty value at column Network Details.') inst_empty_check = True else: # Cross check the VCN names in Instances and VCNs sheet - vcn_subnet_check = compare_values(vcn_subnet_list.tolist(), columnvalue,[i, 'Subnet Name', 'SubnetsVLANs']) + #vcn_subnet_check = compare_values(vcn_subnet_list.tolist(), columnvalue,[i, 'Subnet Name', 'SubnetsVLANs']) + if ("::" not in columnvalue): + vcn_subnet_check = True + if columnname == 'Source Details': if columnvalue.lower()== 'nan': log(f'ROW {i+3} : Empty value at column "Source Details".') inst_empty_check = True - elif (not columnvalue.startswith("image::") and not columnvalue.startswith("bootVolume::")): + elif (not columnvalue.startswith("image::") and not columnvalue.startswith("bootVolume::") and not columnvalue.startswith("ocid1.image.oc")): log(f'ROW {i+3} : Wrong value at column Source Details - {columnvalue}. Valid format is image:: or bootVolume::.') inst_invalid_check = True @@ -918,10 +925,11 @@ def validate_instances(filename,comp_ids,subnetobj,vcn_subnet_list,vcn_nsg_list) log(f'ROW {i+3} : Wrong value at column Shape - {columnvalue}.Valid format for Flex Shapes is VM.Standard.E3.Flex::.') inst_invalid_check = True - if vcn_subnet_check==False and columnname == "NSGs": - subnet_name = str(dfinst.loc[i, "Display Name"]).strip() - if(columnvalue!='nan'): - vcn_nsg_check = validate_nsgs_column(i,region,columnvalue,subnet_name,subnetobj,vcn_nsg_list) + + #if vcn_subnet_check==False and columnname == "NSGs": + # subnet_name = str(dfinst.loc[i, "Display Name"]).strip() + # if(columnvalue!='nan'): + # vcn_nsg_check = validate_nsgs_column(i,region,columnvalue,subnet_name,subnetobj,vcn_nsg_list) if any([inst_empty_check, inst_comp_check, inst_invalid_check, vcn_subnet_check,vcn_nsg_check]): print("Null or Wrong value Check failed!!") @@ -1100,13 +1108,13 @@ def validate_fss(filename,comp_ids,subnetobj,vcn_subnet_list,vcn_nsg_list): comp_name = str(df_fss.loc[i, 'Compartment Name']).strip() ad_name = str(df_fss.loc[i, 'Availability Domain(AD1|AD2|AD3)']).strip() mt_name = str(df_fss.loc[i, 'MountTarget Name']).strip() - mt_subnet_name = str(df_fss.loc[i, 'MountTarget SubnetName']).strip() + mt_subnet_name = str(df_fss.loc[i, 'Network Details']).strip() my_list = [region, comp_name.lower(),ad_name.lower(),mt_name.lower(),mt_subnet_name.lower()] if all(j == 'nan' for j in my_list): pass elif 'nan' in my_list: - log(f'ROW {i + 3} : Empty value for any of the columns "Region", "Compartment Name", "Availability Domain(AD1|AD2|AD3)", "MountTarget Name", "MountTarget SubnetName"') + log(f'ROW {i + 3} : Empty value for any of the columns "Region", "Compartment Name", "Availability Domain(AD1|AD2|AD3)", "MountTarget Name", "Network Details"') fss_empty_check = True if region!='nan' and region not in ct.all_regions: @@ -1129,15 +1137,17 @@ def validate_fss(filename,comp_ids,subnetobj,vcn_subnet_list,vcn_nsg_list): log(f'ROW {i+3} : Wrong value at column "Availability Domain" - {columnvalue}.') fss_invalid_check = True - if columnname == 'MountTarget SubnetName': + if columnname == 'Network Details': # Cross check the VCN names in Instances and VCNs sheet if(columnvalue!='nan'): - vcn_subnet_check = compare_values(vcn_subnet_list.tolist(), columnvalue,[i, 'Display Name ', 'SubnetsVLANs']) - - if vcn_subnet_check==False and columnname == "NSGs": - subnet_name = str(df_fss.loc[i, "MountTarget SubnetName"]).strip() - if (columnvalue != 'nan'): - vcn_nsg_check = validate_nsgs_column(i,region,columnvalue,subnet_name,subnetobj,vcn_nsg_list) + # vcn_subnet_check = compare_values(vcn_subnet_list.tolist(), columnvalue,[i, 'Display Name ', 'SubnetsVLANs']) + if ("::" not in columnvalue): + vcn_subnet_check = True + + #if vcn_subnet_check==False and columnname == "NSGs": + # subnet_name = str(df_fss.loc[i, "MountTarget SubnetName"]).strip() + # if (columnvalue != 'nan'): + # vcn_nsg_check = validate_nsgs_column(i,region,columnvalue,subnet_name,subnetobj,vcn_nsg_list) if any([fss_empty_check, fss_comp_check, fss_invalid_check, vcn_subnet_check,vcn_nsg_check]): print("Null or Wrong value Check failed!!") diff --git a/cd3_automation_toolkit/commonTools.py b/cd3_automation_toolkit/commonTools.py old mode 100755 new mode 100644 index 7329954c3..2a25df78c --- a/cd3_automation_toolkit/commonTools.py +++ b/cd3_automation_toolkit/commonTools.py @@ -46,15 +46,25 @@ class commonTools(): drg_auto_RTs = {'Autogenerated Drg Route Table for RPC, VC, and IPSec attachments', 'Autogenerated Drg Route Table for VCN attachments'} drg_auto_RDs = {'Autogenerated Import Route Distribution for ALL routes', 'Autogenerated Import Route Distribution for VCN Routes'} + def setInputParameters(self, prefix, outdir, inputfile, tf_or_tofu): + self.prefix = prefix + self.outdir = outdir + self.inputfile = inputfile + self.tf_or_tofu = tf_or_tofu + + #Read Regions and Protocols Files and Excel_Columns and create dicts def __init__(self): self.all_regions=[] self.home_region="" self.ntk_compartment_ids = {} + self.domain_data = {} self.region_dict={} self.region_ad_dict = {} self.protocol_dict={} self.sheet_dict={} + self.domain_filter = None + self.identity_domain_enabled = False self.reg_filter = None self.comp_filter = None self.default_dns = None @@ -79,6 +89,17 @@ def __init__(self): self.fwl_pol_pattern_filter = None self.attached_policy_only = None + self.fsdr_ex_filename = None + self.fsdr_ex_sheet = None + self.fsdr_ex_ocid = None + self.fsdr_up_filename = None + self.fsdr_up_sheet = None + self.fsdr_up_ocid = None + + self.prefix='' + self.outdir='' + self.inputfile='' + self.tf_or_tofu = '' # When called from wthin OCSWorkVM or user-scripts dir=os.getcwd() @@ -125,6 +146,10 @@ def get_export_filters(self,export_filters): self.comp_filter = (i.split("=")[1])[2:][:-2] self.comp_filter = self.comp_filter if self.comp_filter else "null" + if 'domain_filter' in i: + self.domain_filter = (i.split("=")[1])[2:][:-2] + self.domain_filter = self.domain_filter if self.domain_filter else "null" + if 'default_dns' in i: self.default_dns = (i.split("=")[1])[2:][:-2] @@ -192,6 +217,19 @@ def get_export_filters(self,export_filters): if 'attached_policy_only' in i: self.attached_policy_only = (i.split("=")[1])[2:][:-2] + if 'fsdr_ex_filename' in i: + self.fsdr_ex_filename = (i.split("=")[1])[2:][:-2] + if 'fsdr_ex_sheet' in i: + self.fsdr_ex_sheet = (i.split("=")[1])[2:][:-2] + if 'fsdr_ex_ocid' in i: + self.fsdr_ex_ocid = (i.split("=")[1])[2:][:-2] + if 'fsdr_up_filename' in i: + self.fsdr_up_filename = (i.split("=")[1])[2:][:-2] + if 'fsdr_up_sheet' in i: + self.fsdr_up_sheet = (i.split("=")[1])[2:][:-2] + if 'fsdr_up_ocid' in i: + self.fsdr_up_ocid = (i.split("=")[1])[2:][:-2] + # OCI API Authentication def authenticate(self,auth_mechanism,config_file_path=DEFAULT_LOCATION): @@ -374,14 +412,25 @@ def get_compartment_map(self, var_file, resource_name): return comp_list_fetch + def identity_domain_check(self,config, signer): + config.__setitem__("region", self.region_dict[self.home_region]) + idc = IdentityClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) + try: + domain = idc.list_domains(config["tenancy"]).data + self.identity_domain_enabled = True + except Exception as e: + print("Tenancy is not Identity Domain Enabled") + self.identity_domain_enabled = False + + + def get_identity_domain_data(self,config, signer, resource,var_file): config.__setitem__("region",self.region_dict[self.home_region]) selected_domains_data = {} idc = IdentityClient(config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) - try: - domain = idc.list_domains(config["tenancy"]).data - + self.identity_domain_check(config, signer) + if self.identity_domain_enabled: resource = "Identity Domain Resource" compartments = self.get_compartment_map(var_file, resource) domain_str = "Enter the ',' separated Domain names to export the groups OR Enter 'all' to export from all domains OR leave it Blank to export from default domain : " @@ -398,9 +447,10 @@ def get_identity_domain_data(self,config, signer, resource,var_file): domain_key = compartment + "@" + d.display_name if 'all' in domain_names or str(d.display_name).lower() in domain_names: self.domain_data[domain_key] = d.url + if self.domain_data == {}: + print(f'Input domain does not match in input compartments') - except Exception as e: - print("Tenancy is not Identity Domain Enabled") + else: self.domain_data = {} return self.domain_data diff --git a/cd3_automation_toolkit/example/CD3-Blank-template.xlsx b/cd3_automation_toolkit/example/CD3-Blank-template.xlsx index a257f4f29..ca40f8d17 100644 Binary files a/cd3_automation_toolkit/example/CD3-Blank-template.xlsx and b/cd3_automation_toolkit/example/CD3-Blank-template.xlsx differ diff --git a/cd3_automation_toolkit/example/CD3-CIS-ManagementServices-template.xlsx b/cd3_automation_toolkit/example/CD3-CIS-ManagementServices-template.xlsx index 78988c66b..2aa41cf8d 100644 Binary files a/cd3_automation_toolkit/example/CD3-CIS-ManagementServices-template.xlsx and b/cd3_automation_toolkit/example/CD3-CIS-ManagementServices-template.xlsx differ diff --git a/cd3_automation_toolkit/example/CD3-CIS-template.xlsx b/cd3_automation_toolkit/example/CD3-CIS-template.xlsx index ead7234e2..23f864d5a 100644 Binary files a/cd3_automation_toolkit/example/CD3-CIS-template.xlsx and b/cd3_automation_toolkit/example/CD3-CIS-template.xlsx differ diff --git a/cd3_automation_toolkit/example/CD3-HubSpoke-template.xlsx b/cd3_automation_toolkit/example/CD3-HubSpoke-template.xlsx index 08e8a7dd8..9ff453e09 100644 Binary files a/cd3_automation_toolkit/example/CD3-HubSpoke-template.xlsx and b/cd3_automation_toolkit/example/CD3-HubSpoke-template.xlsx differ diff --git a/cd3_automation_toolkit/example/CD3-SingleVCN-template.xlsx b/cd3_automation_toolkit/example/CD3-SingleVCN-template.xlsx index 515307733..ae61bccf1 100644 Binary files a/cd3_automation_toolkit/example/CD3-SingleVCN-template.xlsx and b/cd3_automation_toolkit/example/CD3-SingleVCN-template.xlsx differ diff --git a/cd3_automation_toolkit/setUpOCI.properties b/cd3_automation_toolkit/setUpOCI.properties index f5ae7405a..1a0e8e52b 100644 --- a/cd3_automation_toolkit/setUpOCI.properties +++ b/cd3_automation_toolkit/setUpOCI.properties @@ -17,6 +17,9 @@ config_file= # Leave it blank if you want single outdir or specify outdir_structure_file.properties containing directory structure for OCI services. outdir_structure_file= +# IaC Tool to be configured - Terraform(specify terraform) or OpenTofu(specify tofu) +tf_or_tofu= + #path to cd3 excel eg /cd3user/tenancies//CD3-Customer.xlsx cd3file= diff --git a/cd3_automation_toolkit/setUpOCI.py b/cd3_automation_toolkit/setUpOCI.py index be0745420..eb74104f9 100644 --- a/cd3_automation_toolkit/setUpOCI.py +++ b/cd3_automation_toolkit/setUpOCI.py @@ -1,5 +1,7 @@ import argparse import configparser +import re + import Database import Identity import Compute @@ -133,7 +135,8 @@ def execute_options(options, *args, **kwargs): menu = 'm' in options quit = 'q' in options else: - pattern = re.compile("Enable(.*)Logs") + pattern1 = re.compile("Enable(.*)Logs") + pattern2 = re.compile("(.*)DR Plan") for option in options: if option.name == "Execute All": continue @@ -141,7 +144,10 @@ def execute_options(options, *args, **kwargs): with section(option.text): option.callback(*args, **kwargs,sub_options=sub_child_options) # Logging function - elif pattern.match(str(option.name)) !=None: + elif pattern1.match(str(option.name)) !=None: + with section(option.text): + option.callback(*args, **kwargs, option=option.name) + elif pattern2.match(str(option.name)) !=None: with section(option.text): option.callback(*args, **kwargs, option=option.name) else: @@ -344,38 +350,37 @@ def export_compartments(inputfile, outdir,config, signer, ct): resource = 'Compartments' Identity.export_identity(inputfile, outdir, service_dir_identity,resource, config, signer, ct) create_identity(prim_options=['Add/Modify/Delete Compartments']) - print("\n\nExecute tf_import_commands_compartments_nonGF.sh script created under home region directory to synch TF with OCI Identity Compartments\n") + print("\n\nExecute import_commands_compartments.sh script created under home region directory to synch TF with OCI Identity Compartments\n") def export_policies(inputfile, outdir,config, signer, ct): resource = 'IAM Policies' compartments = ct.get_compartment_map(var_file, resource) Identity.export_identity(inputfile, outdir, service_dir_identity,resource, config, signer, ct, export_compartments=compartments) create_identity(prim_options=['Add/Modify/Delete Policies']) - print("\n\nExecute tf_import_commands_policies_nonGF.sh script created under home region directory to synch TF with OCI " +resource +"\n") + print("\n\nExecute import_commands_policies.sh script created under home region directory to synch TF with OCI " +resource +"\n") def export_groups(inputfile, outdir,config, signer, ct): resource = 'IAM Groups' - #selected_domains_data = ct.get_identity_domain_data(config, signer, resource,var_file) - selected_domains_data = {} + selected_domains_data = ct.get_identity_domain_data(config, signer, resource,var_file) Identity.export_identity(inputfile, outdir, service_dir_identity,resource, config, signer, ct, export_domains=selected_domains_data) create_identity(prim_options=['Add/Modify/Delete Groups']) - print("\n\nExecute tf_import_commands_groups_nonGF.sh script created under home region directory to synch TF with OCI " +resource +"\n") + print("\n\nExecute import_commands_groups.sh script created under home region directory to synch TF with OCI " +resource +"\n") def export_users(inputfile, outdir,config,signer, ct): resource = 'IAM Users' # check if tenancy is identity_domain enabled - #selected_domains_data = ct.get_identity_domain_data(config, signer, resource,var_file) - Identity.Users.export_users(inputfile, outdir, service_dir_identity, config, signer, ct) + selected_domains_data = ct.get_identity_domain_data(config, signer, resource,var_file) + Identity.Users.export_users(inputfile, outdir, service_dir_identity, config, signer, ct,export_domains=selected_domains_data) create_identity(prim_options=['Add/Modify/Delete Users']) - print("\n\nExecute tf_import_commands_users_nonGF.sh script created under home region directory to synch TF with OCI " +resource +"\n") + print("\n\nExecute import_commands_users.sh script created under home region directory to synch TF with OCI " +resource +"\n") def export_networkSources(inputfile, outdir, config, signer, ct): resource = 'Network Sources' Identity.NetworkSources.export_networkSources(inputfile, outdir, service_dir_identity, config, signer, ct) create_identity(prim_options=['Add/Modify/Delete Network Sources']) - print("\n\nExecute tf_import_commands_networkSources_nonGF.sh script created under home region directory to synch TF with OCI " +resource +"\n") + print("\n\nExecute import_commands_networkSources.sh script created under home region directory to synch TF with OCI " +resource +"\n") def export_governance(prim_options=[]): options = [ @@ -400,7 +405,7 @@ def export_budget(prim_options=[]): compartments = ct.get_compartment_map(var_file, 'Budgets') CostManagement.export_budgets_nongreenfield(inputfile, outdir, service_dir_budget, config, signer, ct,export_regions) create_budgets() - print("\n\nExecute tf_import_commands_budgets_nonGF.sh script created under each region directory to synch TF with OCI Tags\n") + print("\n\nExecute import_commands_budgets.sh script created under each region directory to synch TF with OCI Tags\n") # Update modified path list update_path_list(regions_path=[ct.home_region], service_dirs=[service_dir_budget]) @@ -408,14 +413,14 @@ def export_tags(prim_options=[]): compartments = ct.get_compartment_map(var_file, 'Tagging Objects') Governance.export_tags_nongreenfield(inputfile, outdir, service_dir_tagging, config, signer, ct, export_compartments=compartments) create_tags() - print("\n\nExecute tf_import_commands_tags_nonGF.sh script created under home region directory to synch TF with OCI Tags\n") + print("\n\nExecute import_commands_tags.sh script created under home region directory to synch TF with OCI Tags\n") # Update modified path list update_path_list(regions_path=[ct.home_region], service_dirs=[service_dir_tagging]) def export_quotas(prim_options=[]): Governance.export_quotas_nongreenfield(inputfile, outdir, service_dir_quota, config, signer, ct) create_quotas() - print("\n\nExecute tf_import_commands_quotas_nonGF.sh script created under home region directory to synch TF with OCI Quota\n") + print("\n\nExecute import_commands_quotas.sh script created under home region directory to synch TF with OCI Quota\n") # Update modified path list update_path_list(regions_path=[ct.home_region], service_dirs=[service_dir_quota]) @@ -444,7 +449,7 @@ def export_network(prim_options=[]): execute_options(options, inputfile, outdir, config, signer, ct, export_regions) print("=====================================================================================================================") - print("NOTE: Make sure to execute tf_import_commands_network_major-objects_nonGF.sh before executing the other scripts.") + print("NOTE: Make sure to execute import_commands_network_major-objects.sh before executing the other scripts.") print("=====================================================================================================================") # Update modified path list @@ -486,7 +491,7 @@ def export_networking(inputfile, outdir,config, signer, ct, export_regions): options = [ Option(None, Network.create_terraform_nsg, 'Processing NSGs Tab'), ] execute_options(options, inputfile, outdir, service_dir_nsg, prefix, ct) - print("\n\nExecute tf_import_commands_network_*_nonGF.sh script created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_*.sh script created under each region directory to synch TF with OCI Network objects\n") for service in [service_dir_network,service_dir_vlan,service_dir_nsg]: service_dirs.append(service_dir_network) if service_dir_network not in service_dirs else service_dirs @@ -509,7 +514,7 @@ def export_major_objects(inputfile, outdir, config, signer, ct, export_regions): ] execute_options(options, inputfile, outdir, service_dir_network, prefix, ct, non_gf_tenancy,network_connectivity_in_setupoci='', modify_network=False) - print("\n\nExecute tf_import_commands_network_major-objects_nonGF.sh and tf_import_commands_network_drg_routerules_nonGF.sh scripts created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_major-objects.sh and import_commands_network_drg_routerules.sh scripts created under each region directory to synch TF with OCI Network objects\n") def export_dhcp(inputfile, outdir,config,signer,ct,export_regions): compartments = ct.get_compartment_map(var_file,'DHCP') @@ -518,7 +523,7 @@ def export_dhcp(inputfile, outdir,config,signer,ct,export_regions): Option(None, Network.create_terraform_dhcp_options, 'Processing DHCP Tab'), ] execute_options(options, inputfile, outdir, service_dir_network,prefix, ct, non_gf_tenancy) - print("\n\nExecute tf_import_commands_network_dhcp_nonGF.sh script created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_dhcp.sh script created under each region directory to synch TF with OCI Network objects\n") def export_secrules(inputfile, outdir,config,signer,ct,export_regions): compartments = ct.get_compartment_map(var_file,'SecRulesInOCI') @@ -527,7 +532,7 @@ def export_secrules(inputfile, outdir,config,signer,ct,export_regions): Option(None, Network.modify_terraform_secrules, 'Processing SecRulesinOCI Tab'), ] execute_options(options, inputfile, outdir,service_dir_network, prefix, ct, non_gf_tenancy) - print("\n\nExecute tf_import_commands_network_secrules_nonGF.sh script created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_secrules.sh script created under each region directory to synch TF with OCI Network objects\n") def export_routerules(inputfile, outdir,config,signer,ct,export_regions): compartments = ct.get_compartment_map(var_file,'RouteRulesInOCI') @@ -536,7 +541,7 @@ def export_routerules(inputfile, outdir,config,signer,ct,export_regions): Option(None, Network.modify_terraform_routerules, 'Processing RouteRulesinOCI Tab'), ] execute_options(options, inputfile, outdir, service_dir_network,prefix, ct, non_gf_tenancy) - print("\n\nExecute tf_import_commands_network_routerules_nonGF.sh script created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_routerules.sh script created under each region directory to synch TF with OCI Network objects\n") def export_subnets_vlans(inputfile, outdir,config,signer,ct,export_regions): @@ -555,8 +560,8 @@ def export_subnets_vlans(inputfile, outdir,config,signer,ct,export_regions): execute_options(options, inputfile, outdir, service_dir, prefix, ct, non_gf_tenancy, network_vlan_in_setupoci='vlan') - print("\n\nExecute tf_import_commands_network_subnets_nonGF.sh script created under each region directory to synch TF with OCI Network objects") - print("\nExecute tf_import_commands_network_vlans_nonGF.sh script created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_subnets.sh script created under each region directory to synch TF with OCI Network objects") + print("\nExecute import_commands_network_vlans.sh script created under each region directory to synch TF with OCI Network objects\n") def export_nsg(inputfile, outdir,config,signer,ct,export_regions): @@ -566,7 +571,7 @@ def export_nsg(inputfile, outdir,config,signer,ct,export_regions): Option(None, Network.create_terraform_nsg, 'Processing NSGs Tab'), ] execute_options(options, inputfile, outdir, service_dir_nsg,prefix, ct) - print("\n\nExecute tf_import_commands_network_nsg_nonGF.sh script created under each region directory to synch TF with OCI Network objects\n") + print("\n\nExecute import_commands_network_nsg.sh script created under each region directory to synch TF with OCI Network objects\n") def export_firewall_policies(prim_options=[]): @@ -582,7 +587,7 @@ def export_firewall_policies(prim_options=[]): def export_firewallpolicy(inputfile, outdir, config, signer, ct, export_regions,name_filter=""): compartments = ct.get_compartment_map(var_file, 'Firewall Policies') - filter_str1 = "Enter comma separated list of display name patterns of the Policies or press \"ENTER\" to export all policies:: " + filter_str1 = "Enter comma separated list of display name patterns of the Policies or press \"ENTER\" to export all policies: " if not devops: policy_name_str = input(filter_str1) else: @@ -591,13 +596,13 @@ def export_firewallpolicy(inputfile, outdir, config, signer, ct, export_regions, policies = list(map(lambda x: x.strip(), policy_name_str.split(','))) if policy_name_str else None Security.export_firewallpolicy(inputfile, outdir, service_dir_firewall, config,signer,ct, export_compartments=compartments, export_regions=export_regions,export_policies=policies) create_firewall_policy(inputfile, outdir, service_dir_firewall, prefix, ct,execute_all=True) - print("\n\nExecute tf_import_commands_firewallpolicy_nonGF.sh script created under each region directory to synch TF with OCI Firewall policy objects\n") + print("\n\nExecute import_commands_firewallpolicy.sh script created under each region directory to synch TF with OCI Firewall policy objects\n") def export_firewalls(inputfile, outdir, config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file, 'Firewalls') Security.export_firewall(inputfile, outdir, service_dir_firewall, config,signer,ct, export_compartments=compartments, export_regions=export_regions) create_firewall(inputfile, outdir, service_dir_firewall, prefix, ct) - print("\n\nExecute tf_import_commands_firewall_nonGF.sh script created under each region directory to synch TF with OCI Firewall policy objects\n") + print("\n\nExecute import_commands_firewall.sh script created under each region directory to synch TF with OCI Firewall policy objects\n") def export_compute(prim_options=[]): @@ -614,7 +619,7 @@ def export_dedicatedvmhosts(inputfile, outdir, config, signer, ct, export_region compartments = ct.get_compartment_map(var_file,'Dedicated VM Hosts') Compute.export_dedicatedvmhosts(inputfile, outdir, service_dir_dedicated_vm_host, config, signer, ct, export_compartments=compartments, export_regions=export_regions) create_dedicatedvmhosts(inputfile, outdir, service_dir_dedicated_vm_host, prefix, ct) - print("\n\nExecute tf_import_commands_dedicatedvmhosts_nonGF.sh script created under each region directory to synch TF with OCI Dedicated VM Hosts\n") + print("\n\nExecute import_commands_dedicatedvmhosts.sh script created under each region directory to synch TF with OCI Dedicated VM Hosts\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_dedicated_vm_host]) @@ -636,7 +641,7 @@ def export_instances(inputfile, outdir,config,signer, ct, export_regions): Compute.export_instances(inputfile, outdir, service_dir_instance,config,signer,ct, export_compartments=compartments, export_regions=export_regions, display_names = display_names, ad_names = ad_names) create_instances(inputfile, outdir, service_dir_instance, prefix, ct) - print("\n\nExecute tf_import_commands_instances_nonGF.sh script created under each region directory to synch TF with OCI Instances\n") + print("\n\nExecute import_commands_instances.sh script created under each region directory to synch TF with OCI Instances\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_instance]) @@ -669,7 +674,7 @@ def export_block_volumes(inputfile, outdir,config,signer,ct, export_regions): Storage.export_blockvolumes(inputfile, outdir, service_dir_block_volume, config,signer,ct, export_compartments=compartments, export_regions=export_regions, display_names = display_names, ad_names = ad_names) Storage.create_terraform_block_volumes(inputfile, outdir, service_dir_block_volume, prefix, ct) print( - "\n\nExecute tf_import_commands_blockvolumes_nonGF.sh script created under each region directory to synch TF with OCI Block Volume Objects\n") + "\n\nExecute import_commands_blockvolumes.sh script created under each region directory to synch TF with OCI Block Volume Objects\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_block_volume]) @@ -679,7 +684,7 @@ def export_fss(inputfile, outdir,config, signer, ct, export_regions): Storage.export_fss(inputfile, outdir, service_dir_fss, config,signer,ct, export_compartments=compartments, export_regions=export_regions) Storage.create_terraform_fss(inputfile, outdir, service_dir_fss, prefix, ct) print( - "\n\nExecute tf_import_commands_fss_nonGF.sh script created under each region directory to synch TF with OCI FSS objects\n") + "\n\nExecute import_commands_fss.sh script created under each region directory to synch TF with OCI FSS objects\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_fss]) @@ -688,7 +693,7 @@ def export_buckets(inputfile, outdir, config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file, 'Buckets') Storage.export_buckets(inputfile, outdir, service_dir_object_storage, config,signer,ct, export_compartments=compartments, export_regions=export_regions) Storage.create_terraform_oss(inputfile, outdir, service_dir_object_storage, prefix, ct) - print("\n\nExecute tf_import_commands_buckets_nonGF.sh script created under each region directory to synch TF with OCI Object Storage Buckets\n") + print("\n\nExecute import_commands_buckets.sh script created under each region directory to synch TF with OCI Object Storage Buckets\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_object_storage]) @@ -715,7 +720,7 @@ def export_kms(inputfile, outdir, config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file, 'KMS') Security.export_keyvaults(inputfile, outdir, service_dir_kms, config,signer,ct, export_compartments=compartments, export_regions=export_regions) Security.create_terraform_keyvaults(inputfile, outdir, service_dir_kms, prefix, ct) - print("\n\nExecute tf_import_commands_kms_nonGF.sh script created under each region directory to synch TF with OCI Key Vaults\n") + print("\n\nExecute import_commands_kms.sh script created under each region directory to synch TF with OCI Key Vaults\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_kms]) @@ -723,7 +728,7 @@ def export_lbr(inputfile, outdir,config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'LBR objects') Network.export_lbr(inputfile, outdir, service_dir_loadbalancer, config,signer,ct, export_compartments=compartments, export_regions=export_regions) create_lb(inputfile, outdir, prefix, ct) - print("\n\nExecute tf_import_commands_lbr_nonGF.sh script created under each region directory to synch TF with OCI LBR objects\n") + print("\n\nExecute import_commands_lbr.sh script created under each region directory to synch TF with OCI LBR objects\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_loadbalancer]) @@ -732,7 +737,7 @@ def export_nlb(inputfile, outdir,config,signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'NLB objects') Network.export_nlb(inputfile, outdir, service_dir_networkloadbalancer, config,signer,ct, export_compartments=compartments, export_regions=export_regions) create_nlb(inputfile, outdir, prefix, ct) - print("\n\nExecute tf_import_commands_nlb_nonGF.sh script created under each region directory to synch TF with OCI NLB objects\n") + print("\n\nExecute import_commands_nlb.sh script created under each region directory to synch TF with OCI NLB objects\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_networkloadbalancer]) @@ -751,7 +756,7 @@ def export_dbsystems_vm_bm(inputfile, outdir,config,signer, ct,export_regions): compartments = ct.get_compartment_map(var_file,'VM and BM DB Systems') Database.export_dbsystems_vm_bm(inputfile, outdir, service_dir_dbsystem_vm_bm, config,signer,ct, export_compartments=compartments, export_regions= export_regions) Database.create_terraform_dbsystems_vm_bm(inputfile, outdir, service_dir_dbsystem_vm_bm, prefix, ct) - print("\n\nExecute tf_import_commands_dbsystems-vm-bm_nonGF.sh script created under each region directory to synch TF with DBSystems\n") + print("\n\nExecute import_commands_dbsystems-vm-bm.sh script created under each region directory to synch TF with DBSystems\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_dbsystem_vm_bm]) @@ -761,7 +766,7 @@ def export_exa_infra_vmclusters(inputfile, outdir,config, signer, ct, export_reg Database.export_exa_infra(inputfile, outdir, service_dir_database_exacs, config,signer,ct, export_compartments=compartments, export_regions= export_regions) Database.export_exa_vmclusters(inputfile, outdir, service_dir_database_exacs, config,signer,ct, export_compartments=compartments, export_regions= export_regions) create_exa_infra_vmclusters(inputfile, outdir, prefix,ct) - print("\n\nExecute tf_import_commands_exa-infra_nonGF.sh and tf_import_commands_exa-vmclusters_nonGF.sh scripts created under each region directory to synch TF with Exa-Infra and Exa-VMClusters\n") + print("\n\nExecute import_commands_exa-infra.sh and import_commands_exa-vmclusters.sh scripts created under each region directory to synch TF with Exa-Infra and Exa-VMClusters\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_database_exacs]) @@ -770,7 +775,7 @@ def export_adbs(inputfile, outdir,config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'ADBs') Database.export_adbs(inputfile, outdir, service_dir_adb, config,signer,ct, export_compartments=compartments, export_regions= export_regions) Database.create_terraform_adb(inputfile, outdir, service_dir_adb, prefix, ct) - print("\n\nExecute tf_import_commands_adb_nonGF.sh script created under each region directory to synch TF with OCI ADBs\n") + print("\n\nExecute import_commands_adb.sh script created under each region directory to synch TF with OCI ADBs\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_adb]) @@ -792,25 +797,25 @@ def export_notifications(inputfile, outdir, service_dir, config, signer, ct, exp compartments = ct.get_compartment_map(var_file,'Notifications') ManagementServices.export_notifications(inputfile, outdir, service_dir, config,signer,ct, export_compartments=compartments, export_regions=export_regions) ManagementServices.create_terraform_notifications(inputfile, outdir, service_dir, prefix, ct) - print("\n\nExecute tf_import_commands_notifications_nonGF.sh script created under each region directory to synch TF with OCI Notifications\n") + print("\n\nExecute import_commands_notifications.sh script created under each region directory to synch TF with OCI Notifications\n") def export_events(inputfile, outdir, service_dir, config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'Events') ManagementServices.export_events(inputfile, outdir, service_dir, config,signer,ct, export_compartments=compartments, export_regions=export_regions) ManagementServices.create_terraform_events(inputfile, outdir, service_dir, prefix, ct) - print("\n\nExecute tf_import_commands_events_nonGF.sh script created under each region directory to synch TF with OCI Events\n") + print("\n\nExecute import_commands_events.sh script created under each region directory to synch TF with OCI Events\n") def export_alarms(inputfile, outdir, service_dir, config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'Alarms') ManagementServices.export_alarms(inputfile, outdir, service_dir, config,signer,ct, export_compartments=compartments, export_regions=export_regions) ManagementServices.create_terraform_alarms(inputfile, outdir,service_dir, prefix, ct) - print("\n\nExecute tf_import_commands_alarms_nonGF.sh script created under each region directory to synch TF with OCI Alarms\n") + print("\n\nExecute import_commands_alarms.sh script created under each region directory to synch TF with OCI Alarms\n") def export_service_connectors(inputfile, outdir, service_dir, config, signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'Service Connectors') ManagementServices.export_service_connectors(inputfile, outdir, service_dir, config,signer,ct, export_compartments=compartments, export_regions=export_regions) ManagementServices.create_service_connectors(inputfile, outdir, service_dir, prefix, ct) - print("\n\nExecute tf_import_commands_serviceconnectors_nonGF.sh script created under each region directory to synch TF with OCI Service Connectors\n") + print("\n\nExecute import_commands_serviceconnectors.sh script created under each region directory to synch TF with OCI Service Connectors\n") def export_developer_services(prim_options=[]): options = [Option("Export OKE cluster and Nodepools", export_oke, 'Exporting OKE'), @@ -825,7 +830,7 @@ def export_oke(inputfile, outdir, config,signer, ct, export_regions): compartments = ct.get_compartment_map(var_file,'OKE') DeveloperServices.export_oke(inputfile, outdir, service_dir_oke,config,signer,ct, export_compartments=compartments, export_regions=export_regions) DeveloperServices.create_terraform_oke(inputfile, outdir, service_dir_oke,prefix, ct) - print("\n\nExecute tf_import_commands_oke_nonGF.sh script created under each region directory to synch TF with OKE\n") + print("\n\nExecute import_commands_oke.sh script created under each region directory to synch TF with OKE\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_oke]) @@ -834,7 +839,7 @@ def export_sddc(prim_options=[]): compartments = ct.get_compartment_map(var_file,'SDDCs') SDDC.export_sddc(inputfile, outdir, service_dir_sddc,config,signer,ct, export_compartments=compartments, export_regions=export_regions) SDDC.create_terraform_sddc(inputfile, outdir, service_dir_sddc, prefix, ct) - print("\n\nExecute tf_import_commands_sddcs_nonGF.sh script created under each region directory to synch TF with SDDC\n") + print("\n\nExecute import_commands_sddcs.sh script created under each region directory to synch TF with SDDC\n") # Update modified path list update_path_list(regions_path=export_regions, service_dirs=[service_dir_sddc]) @@ -890,6 +895,7 @@ def fetch_protocols(outdir, outdir_struct, ct): ################## Create Functions ########################## def create_identity(prim_options=[]): + ct.identity_domain_check(config,signer) options = [ Option('Add/Modify/Delete Compartments', Identity.create_terraform_compartments, 'Processing Compartments Tab'), Option('Add/Modify/Delete Groups', Identity.create_terraform_groups, 'Processing Groups Tab'), @@ -1171,6 +1177,7 @@ def create_lb(inputfile, outdir, prefix, ct): Option(None, Network.create_listener, 'Creating Listeners'), Option(None, Network.create_path_route_set, 'Creating Path Route Sets'), Option(None, Network.create_ruleset, 'Creating Rule Sets'), + Option(None, Network.create_lb_routing_policy, 'Creating Routing Policies'), ] execute_options(options, inputfile, outdir, service_dir_loadbalancer, prefix, ct) # Update modified path list @@ -1215,7 +1222,7 @@ def create_exa_infra_vmclusters(inputfile, outdir, prefix,ct): def create_terraform_adb(inputfile, outdir, prefix,ct): - Database.create_terraform_dbsystems_vm_bm(inputfile, outdir, service_dir_adb, prefix, ct) + Database.create_terraform_adb(inputfile, outdir, service_dir_adb, prefix, ct) # Update modified path list update_path_list(regions_path=subscribed_regions, service_dirs=[service_dir_adb]) @@ -1239,10 +1246,16 @@ def create_management_services(execute_all=False,prim_options=[]): def create_developer_services(execute_all=False,prim_options=[]): - options = [ - Option("Upload current terraform files/state to Resource Manager", create_rm_stack, 'Creating RM Stack'), - Option("Add/Modify/Delete OKE Cluster and Nodepools", create_oke, 'Creating OKE cluster and Nodepool') - ] + if tf_or_tofu == 'terraform': + options = [ + Option("Upload current terraform files/state to Resource Manager", create_rm_stack, 'Creating RM Stack'), + Option("Add/Modify/Delete OKE Cluster and Nodepools", create_oke, 'Creating OKE cluster and Nodepool') + ] + elif tf_or_tofu=='tofu': + options = [ + Option("Add/Modify/Delete OKE Cluster and Nodepools", create_oke, 'Creating OKE cluster and Nodepool') + ] + if prim_options: options = match_options(options, prim_options) else: @@ -1335,7 +1348,8 @@ def create_security_services(prim_options=[]): def run_utility(prim_options=[]): options = [Option('CIS Compliance Check Script', initiate_cis_scan, 'CIS Compliance Check Script'), - Option('ShowOCI Report', run_showoci, 'ShowOCI Report') + Option('ShowOCI Report', run_showoci, 'ShowOCI Report'), + Option('OCI FSDR', run_oci_fsdr, 'OCI FSDR') ] if prim_options: options = match_options(options, prim_options) @@ -1377,15 +1391,21 @@ def initiate_cis_scan(outdir, prefix, config_file,sub_options=[]): execute_options(options, outdir, prefix, config_file) def start_cis_download(outdir, prefix, config_file): - print("Downloading the script file as 'cis_reports.py' at location "+os.getcwd()) + current_dir=os.path.dirname(os.path.abspath(__file__)) + print("Downloading the script file as 'cis_reports.py' at location "+current_dir+"/../othertools/") resp = requests.get("https://raw.githubusercontent.com/oracle-quickstart/oci-cis-landingzone-quickstart/main/scripts/cis_reports.py") resp_contents = resp.text - with open("cis_reports.py", "w", encoding="utf-8") as fd: + with open(current_dir+"/../othertools/cis_reports.py", "w", encoding="utf-8") as fd: fd.write(resp_contents) + + #cmdpath = os.path.dirname(os.path.abspath(__file__)) + "/../" + #shutil.move(os.getcwd()+"/../othertools/cis_reports.py", os.getcwd()+"/../othertools/cis_reports.py") print("Download complete!!") def start_cis_scan(outdir, prefix, config_file): - cmd = "python cis_reports.py" + cmdpath = os.path.dirname(os.path.abspath(__file__))+ "/../othertools/" + cmd = "python "+cmdpath+"cis_reports.py" + if auth_mechanism == "instance_principal": cmd += " -ip" elif auth_mechanism == "session_token": @@ -1399,14 +1419,16 @@ def start_cis_scan(outdir, prefix, config_file): split = str.split(cmd) dirname = prefix + "_cis_report" resource = "cis_report" + if outdir[len(outdir)-1]=="/": + outdir=outdir.rsplit("/",2)[0]+"/othertools_files" + else: + outdir = outdir.rsplit("/", 1)[0] + "/othertools_files" out_rep = outdir + '/'+ dirname #config = "--config "+ config - commonTools.backup_file(outdir, resource, dirname) + commonTools.backup_file(outdir, resource, dirname) if not os.path.exists(out_rep): os.makedirs(out_rep) - else: - commonTools.backup_file(outdir, resource, out_rep) out = ['--report-directory', out_rep] cmd = cmd +" "+ out[0] + " "+out[1] @@ -1416,22 +1438,28 @@ def start_cis_scan(outdir, prefix, config_file): execute(split, config_file) def get_latest_showoci(outdir, prefix,config_file): - print("Getting latest showoci report script") - if (os.path.isdir("/tmp/oci-python-sdk")): - shutil.rmtree("/tmp/oci-python-sdk") - cmd = "git clone https://github.com/oracle/oci-python-sdk /tmp/oci-python-sdk" + current_dir = os.path.dirname(os.path.abspath(__file__)) + print("Getting latest showoci report script at location "+current_dir+"/../othertools/") + + cmdpath=os.path.dirname(os.path.abspath(__file__)) + "/../othertools/" + tag= "oci-python-sdk" + + if (os.path.isdir(cmdpath+tag)): + shutil.rmtree(cmdpath+tag) + cmd = "git clone https://github.com/oracle/oci-python-sdk "+cmdpath+tag split = str.split(cmd) - execute(split,config_file) - if (os.path.isdir("/cd3user/oci_tools/oci-python-sdk")): - shutil.rmtree("/cd3user/oci_tools/oci-python-sdk") - shutil.move("/tmp/oci-python-sdk", "/cd3user/oci_tools/oci-python-sdk") + execute(split, config_file) + #shutil.move("/tmp/oci-python-sdk", cmdpath+tag) print("Download complete!!") def execute_showoci(outdir, prefix, config_file_path): - if not os.path.isfile("/cd3user/oci_tools/oci-python-sdk/examples/showoci/showoci.py"): + cmdpath = os.path.dirname(os.path.abspath(__file__)) + "/../othertools/" + tag = "oci-python-sdk" + if not os.path.isfile(cmdpath+tag+"/examples/showoci/showoci.py"): get_latest_showoci(outdir, prefix, config_file=config_file_path) - cmd = "python /cd3user/oci_tools/oci-python-sdk/examples/showoci/showoci.py -a" + cmd = "python "+cmdpath+tag+"/examples/showoci/showoci.py -a" + if auth_mechanism == "instance_principal": cmd += " -ip" elif auth_mechanism == "session_token": @@ -1439,16 +1467,19 @@ def execute_showoci(outdir, prefix, config_file_path): else: cmd += " -cf "+config_file_path split = str.split(cmd) + dirname = prefix + "_showoci_report" resource = "showoci_report" + if outdir[len(outdir) - 1] == "/": + outdir = outdir.rsplit("/", 2)[0] + "/othertools_files" + else: + outdir = outdir.rsplit("/", 1)[0] + "/othertools_files" out_rep = outdir + '/' + dirname # config = "--config "+ config - commonTools.backup_file(outdir, resource, dirname) + commonTools.backup_file(outdir, resource, dirname) if not os.path.exists(out_rep): os.makedirs(out_rep) - else: - commonTools.backup_file(outdir, resource, out_rep) out_file = out_rep+"/"+prefix out = ['-csv', out_file] cmd = cmd + " " + out[0] + " " + out[1] @@ -1469,6 +1500,94 @@ def run_showoci(outdir, prefix, config_file,sub_options=[]): options = show_options(options, quit=True, menu=True, index=1) execute_options(options, outdir, prefix, config_file) +def export_update_dr_plan(outdir, prefix, config_file_path,option=''): + print("Use Excel Template oci-fsdr-plan-template.xlsx at /cd3user/oci_tools/othertools/oci-fsdr for the export") + tag = "oci-fsdr" + + if option.lower().__contains__("export"): + c="export" + input1 = "Please enter excel file name where DR plan will be exported; Leave blank to create with name '$prefix_" + tag + "-plan.xlsx at /cd3user/tenancies//othertools_files: ': " + input2 = "Please enter sheet name in the excel where DR plan will be exported(without spaces); Leave blank to create with name 'FSDR-Plan': " + + elif option.lower().__contains__("update"): + c="update" + input1 = "Please enter excel file name from where DR plan will be updated; Leave blank to read file with name '$prefix_" + tag + "-plan.xlsx': " + input2 = "Please enter sheet name in the excel from where DR plan will be updated(without spaces); Leave blank to read sheet with name 'FSDR-Plan': " + + cmdpath = os.path.dirname(os.path.abspath(__file__))+"/../othertools/"+tag+"/"+c+"_drplan.py" + + if not os.path.isfile(cmdpath): + print(cmdpath+" doesnt exist. Exiitng!!!") + exit(1) + + input3 = "Please enter DR Plan OCID which needs to be exported/updated: " + + + if not devops: + filename = input(input1) + sheetname = input(input2) + fsdrocid = input(input3) + + else: + if option.lower().__contains__("export"): + filename = ct.fsdr_ex_filename + sheetname = ct.fsdr_ex_sheet + fsdrocid = ct.fsdr_ex_ocid + elif option.lower().__contains__("update"): + filename = ct.fsdr_up_filename + sheetname = ct.fsdr_up_sheet + fsdrocid = ct.fsdr_up_ocid + + + if filename == '': + filename = prefix + "_"+tag+"-plan.xlsx" + if sheetname == '': + sheetname = 'FSDR-Plan' + if fsdrocid == '': + print("OCID cannot be empty. Exiting!!!") + exit(1) + + # Build command to execute + if outdir[len(outdir) - 1] == "/": + outdir = outdir.rsplit("/", 2)[0] + "/othertools_files" + else: + outdir = outdir.rsplit("/", 1)[0] + "/othertools_files" + out_file = outdir + '/' + filename + + cmd = "python "+cmdpath+ " " + + if auth_mechanism == "instance_principal": + cmd += " -i" + elif auth_mechanism == "session_token": + cmd += " -t" + + cmd += " -c "+config_file_path + + cmd += " -o " + fsdrocid + " -s \"" + sheetname + "\" -f " + out_file + + + if not os.path.exists(outdir): + os.makedirs(outdir) + # Take backup of existing excel sheet + #if option.lower().__contains__("export"): + # commonTools.backup_file(outdir, tag, filename) + + split = str.split(cmd) + print("Executing: " + cmd) + execute(split, config_file_path) + + +def run_oci_fsdr(outdir, prefix, config_file,sub_options=[]): + options = [ + Option("Export DR Plan", export_update_dr_plan, 'Exporting DR Plan'), + Option("Update DR Plan", export_update_dr_plan, 'Updating DR Plan'), + ] + if sub_options: + options = match_options(options, sub_options) + else: + options = show_options(options, quit=True, menu=True, index=1) + execute_options(options, outdir, prefix, config_file) + def execute(command,config_file): export_cmd_windows = "set OCI_CONFIG_HOME="+config_file export_cmd_linux = "export OCI_CONFIG_HOME=" + config_file @@ -1572,7 +1691,7 @@ def clone_firewall_policy( inputfile, outdir, service_dir, config, signer, ct): #Security.clone_firewallpolicy(inputfile, outdir, service_dir, config, signer, ct, export_compartments=compartments, export_regions=export_regions, export_firewall=firewall, export_policy=policy) print("Proceeding with tfvars generation...") create_firewall_policy(inputfile, outdir, service_dir, prefix, ct,execute_all=True) - #print("\n\nExecute tf_import_commands_Firewallpolicy_nonGF.sh script created under each region directory to synch TF with OCI Firewall policy objects\n") + #print("\n\nExecute import_commands_Firewallpolicy.sh script created under each region directory to synch TF with OCI Firewall policy objects\n") def delete_firewall_policy(inputfile, outdir, service_dir, config, signer, ct): @@ -1666,6 +1785,7 @@ def create_firewall(inputfile, outdir, service_dir, prefix, ct,sub_options=[]): inputfile = setUpOCI_props.get('Default','cd3file').strip() outdir = setUpOCI_props.get('Default', 'outdir').strip() + tf_or_tofu = setUpOCI_props.get('Default', 'tf_or_tofu').strip().lower() prefix = setUpOCI_props.get('Default', 'prefix').strip() auth_mechanism = setUpOCI_props.get('Default', 'auth_mechanism').strip().lower() config_file_path = setUpOCI_props.get('Default', 'config_file').strip() or DEFAULT_LOCATION @@ -1708,6 +1828,7 @@ def create_firewall(inputfile, outdir, service_dir, prefix, ct,sub_options=[]): ct=None ct = commonTools() config,signer = ct.authenticate(auth_mechanism, config_file_path) +ct.setInputParameters(prefix,outdir,inputfile,tf_or_tofu) if devops: # Set Export filters from devops @@ -1732,7 +1853,8 @@ def create_firewall(inputfile, outdir, service_dir, prefix, ct,sub_options=[]): # If single outdir, get service names from /cd3user/oci_tools/cd3_automation_toolkit/user-scripts/.outdir_structure_file.properties if len(outdir_struct.items())==0: single_outdir_config = configparser.RawConfigParser() - single_outdir_config.read("/cd3user/oci_tools/cd3_automation_toolkit/user-scripts/.outdir_structure_file.properties") + outdir_config_file = os.path.dirname(os.path.abspath(__file__))+"/user-scripts/.outdir_structure_file.properties" + single_outdir_config.read(outdir_config_file) for item,val in single_outdir_config.items("Default"): varname = "service_dir_" + str(item.replace("-", "_")).strip() exec(varname + "= \"\"",globals()) @@ -1823,7 +1945,7 @@ def create_firewall(inputfile, outdir, service_dir, prefix, ct,sub_options=[]): Option('Logging Services', create_logging, 'Logging Services'), Option('Software-Defined Data Centers - OCVS', create_sddc, 'Processing SDDC Tabs'), Option('CD3 Services', cd3_services, 'CD3 Services'), - Option('3rd Party Services', run_utility,'3rd Party Services') + Option('Other OCI Tools', run_utility,'Other OCI Tools') ] export_regions = ct.all_regions diff --git a/cd3_automation_toolkit/shell_script.sh b/cd3_automation_toolkit/shell_script.sh index cce9129ff..cdad19f6d 100644 --- a/cd3_automation_toolkit/shell_script.sh +++ b/cd3_automation_toolkit/shell_script.sh @@ -13,7 +13,7 @@ sudo dnf install python-pip -y #sudo ln -s /usr/bin/pip3 /usr/bin/pip # Install required Python packages -pip install --user oci-cli==3.39.0 +pip install --user oci-cli==3.44.4 pip install --user pycryptodomex==3.10.1 pip install --user regex==2022.10.31 pip install --user numpy==1.26.4 @@ -42,10 +42,16 @@ echo "PATH=\$PATH:/cd3user/.local/bin" >> /cd3user/.bashrc #sudo dnf install -y https://yum.oracle.com/repo/OracleLinux/OL9/developer/x86_64/getPackage/terraform-1.3.6-1.el9.x86_64.rpm sudo dnf install -y wget sudo dnf install -y unzip -sudo wget https://releases.hashicorp.com/terraform/1.3.6/terraform_1.3.6_linux_amd64.zip -unzip terraform_1.3.6_linux_amd64.zip +#sudo wget https://releases.hashicorp.com/terraform/1.3.6/terraform_1.3.6_linux_amd64.zip +sudo wget https://releases.hashicorp.com/terraform/1.5.7/terraform_1.5.7_linux_amd64.zip +unzip terraform_1.5.7_linux_amd64.zip sudo mv terraform /usr/local/sbin/ -sudo rm terraform_1.3.6_linux_amd64.zip +sudo rm terraform_1.5.7_linux_amd64.zip + +# Download and Install OpenTofu +sudo wget --content-disposition "https://packagecloud.io/opentofu/tofu/packages/rpm_any/rpm_any/tofu-1.6.2-1.x86_64.rpm/download.rpm?distro_version_id=227" +sudo rpm -i tofu-1.6.2-1.x86_64.rpm +sudo rm tofu-1.6.2-1.x86_64.rpm # Download and install OPA curl -L -o opa https://openpolicyagent.org/downloads/v0.55.0/opa_linux_amd64_static diff --git a/cd3_automation_toolkit/user-scripts/createTenancyConfig.py b/cd3_automation_toolkit/user-scripts/createTenancyConfig.py index 46574d160..3ecb2973c 100644 --- a/cd3_automation_toolkit/user-scripts/createTenancyConfig.py +++ b/cd3_automation_toolkit/user-scripts/createTenancyConfig.py @@ -120,7 +120,7 @@ def create_devops_resources(config,signer): repo_state = item.lifecycle_state repo_id = item.id if repo_state != "ACTIVE": - print("Repository exists with name("+repo_name+") but is not in ACTIVE state. Please retry with different customer_name. Exiting...") + print("Repository exists with name("+repo_name+") but is not in ACTIVE state. Please retry with different prefix. Exiting...") exit(1) else: repo_url = item.ssh_url @@ -190,15 +190,36 @@ def update_devops_config(prefix,git_config_file, repo_ssh_url,files_in_repo,dir_ else: dir_structure = "Single_Outdir" - file = open(jenkins_properties_file_path, "w+") - file.write("git_url= \""+repo_ssh_url+"\"\n" - "regions="+str(ct.all_regions)+"\n" - "services="+str(dir_values)+"\n" - "outdir_structure=[\""+dir_structure+"\"]\n") + try: + jenkins_config = configparser.RawConfigParser() + jenkins_config.read(jenkins_properties_file_path) + + # Added this to restrict to single prefix for current release. + num_of_sections = jenkins_config.sections() + if len(num_of_sections)<1: + if (prefix in jenkins_config.sections()): + jenkins_config.set(prefix,'regions',str(ct.all_regions)) + jenkins_config.set(prefix, 'services', str(dir_values)) + else: + jenkins_config.add_section(prefix) + jenkins_config.set(prefix, 'git_url', "\""+repo_ssh_url+"\"") + jenkins_config.set(prefix, 'regions', str(ct.all_regions)) + jenkins_config.set(prefix, 'services', str(dir_values)) + jenkins_config.set(prefix, 'outdir_structure', "[\""+dir_structure+"\"]") + jenkins_config.set(prefix, 'tf_or_tofu', "\"" + tf_or_tofu + "\"") + + # Dont do anything for multiple prefixes in this release + + file = open(jenkins_properties_file_path, "w") + jenkins_config.write(file) + + except Exception as e: + print(e) + file.close() # Update Environment variable for jenkins - yaml_file_path = jenkins_dir + "/jcasc.yaml" + yaml_file_path = jenkins_install + "/jcasc.yaml" if (os.path.exists(yaml_file_path)): with open(yaml_file_path) as yaml_file: cfg = yaml.load(yaml_file, Loader=yaml.FullLoader) @@ -210,7 +231,7 @@ def update_devops_config(prefix,git_config_file, repo_ssh_url,files_in_repo,dir_ subprocess.run(['git', 'config', '--global', 'init.defaultBranch', "main"], cwd=devops_dir) subprocess.run(['git', 'config', '--global', 'safe.directory', devops_dir], cwd=devops_dir) f = open(devops_dir + ".gitignore", "w") - git_ignore_file_data = ".DS_Store\n*tfstate*\n*terraform*\ntfplan.out\ntfplan.json\n*backup*\ntf_import_commands*\n*cis_report*\n*showoci_report*\n*.safe\n*stacks.zip\n*cd3Validator*" + git_ignore_file_data = ".DS_Store\n*tfstate*\n*terraform*\ntfplan.out\ntfplan.json\n*backup*\nimport_commands*\n*cis_report*\n*showoci_report*\n*.safe\n*stacks.zip\n*cd3Validator*" f.write(git_ignore_file_data) f.close() # Cleanup existing "origin" remote and create required one @@ -229,7 +250,7 @@ def update_devops_config(prefix,git_config_file, repo_ssh_url,files_in_repo,dir_ f.close() exit(1) - for f in glob.glob(jenkins_dir + "/*.groovy"): + for f in glob.glob(jenkins_install + "/*.groovy"): shutil.copy2(f, devops_dir) # Create local branch "main" from remote "main" subprocess.run(['git', 'checkout', '-B', 'main','-q'], cwd=devops_dir,stdout=DEVNULL) @@ -312,14 +333,14 @@ def create_bucket(config, signer): variables_example_file = modules_dir + "/variables_example.tf" setupoci_props_toolkit_file_path = toolkit_dir + "/setUpOCI.properties" -jenkins_dir = '' +jenkins_install = toolkit_dir + "/../jenkins_install" #if hasattr(os.environ,'JENKINS_INSTALL'): if environ.get('JENKINS_INSTALL') is not None: - jenkins_dir = os.environ['JENKINS_INSTALL'] + jenkins_install = os.environ['JENKINS_INSTALL'] -prefix = config.get('Default', 'customer_name').strip() +prefix = config.get('Default', 'prefix').strip() if prefix == "" or prefix == "\n": - print("Invalid Customer Name. Please try again......Exiting !!") + print("Invalid Prefix. Please try again......Exiting !!") exit(1) prefixes=[] @@ -332,11 +353,11 @@ def create_bucket(config, signer): if prefixes !=[]: if prefix in prefixes: - print("WARNING!!! Container has already been successfuly connected to the tenancy with same customer_name. Please proceed only if you re-running the script for new region subscription") + print("WARNING!!! Container has already been successfuly connected to the tenancy with same prefix. Please proceed only if you re-running the script for new region subscription") else: - print("WARNING!!! Container has already been successfully connected to the tenancy with these values of customer_name: "+str(list(set(prefixes)))) - print("WARNING!!! Toolkit usage with Jenkins has not been tested with running this script multiple times with different values of customer_name in the properties file") - print("Jenkins is configured for the customer_name used for the first successful execution of the script.") + print("WARNING!!! Container has already been successfully connected to the tenancy with these values of prefixes: "+str(list(set(prefixes)))) + print("WARNING!!! Toolkit usage with Jenkins has not been tested with running this script multiple times with different values of prefix in the properties file") + print("Jenkins is configured for the prefix used for the first successful execution of the script.") inp = input("\nDo you want to proceed (y/n):") if inp.lower()=="n": exit(1) @@ -403,6 +424,10 @@ def create_bucket(config, signer): outdir_structure_file = config.get('Default', 'outdir_structure_file').strip() ssh_public_key = config.get('Default', 'ssh_public_key').strip() + tf_or_tofu = config.get('Default', 'tf_or_tofu').strip().lower() + if tf_or_tofu == "" or tf_or_tofu == "\n": + tf_or_tofu = "terraform" + ## Advanced parameters ## remote_state = config.get('Default', 'use_remote_state').strip().lower() remote_state_bucket = config.get('Default', 'remote_state_bucket_name').strip() @@ -458,6 +483,8 @@ def create_bucket(config, signer): os.makedirs(config_files) if not os.path.exists(outdir_safe): os.makedirs(outdir_safe) +if not os.path.exists(customer_tenancy_dir+'/othertools_files'): + os.makedirs(customer_tenancy_dir+'/othertools_files') dir_values = [] @@ -491,7 +518,6 @@ def create_bucket(config, signer): print("\nUsing different directories for OCI services as per the input outdir_structure_file..........") else: print("\nUsing single out directory for resources..........") - ################ Get service names here only ######################## # 2. Move Private PEM key and Session Token file _session_token_file='' @@ -723,6 +749,7 @@ def create_bucket(config, signer): setupoci_props_toolkit_file_data = setupoci_props_toolkit_file_data.replace("auth_mechanism=", "auth_mechanism=" + auth_mechanism) setupoci_props_toolkit_file_data = setupoci_props_toolkit_file_data.replace("config_file=", "config_file="+config_file_path) setupoci_props_toolkit_file_data = setupoci_props_toolkit_file_data.replace("outdir_structure_file=", "outdir_structure_file="+_outdir_structure_file) +setupoci_props_toolkit_file_data = setupoci_props_toolkit_file_data.replace("tf_or_tofu=", "tf_or_tofu="+tf_or_tofu) f = open(setupoci_props_file_path, "w+") f.write(setupoci_props_toolkit_file_data) @@ -859,12 +886,15 @@ def create_bucket(config, signer): #remove depends_on for single outdir region_dir = terraform_files + "/" + region + "/" single_outdir_config = configparser.RawConfigParser() - single_outdir_config.read("/cd3user/oci_tools/cd3_automation_toolkit/user-scripts/.outdir_structure_file.properties") + outdir_config_file = os.path.dirname(os.path.abspath(__file__)) + "/.outdir_structure_file.properties" + + single_outdir_config.read(outdir_config_file) keys = [] for key, val in single_outdir_config.items("Default"): keys.append(key) for file in os.listdir(region_dir): - name=file.removesuffix(".tf") + #name=file.removesuffix(".tf") + name = file[:-len(".tf")] if name in keys: file=region_dir+"/"+file with open(file, 'r+') as tf_file: diff --git a/cd3_automation_toolkit/user-scripts/tenancyconfig.properties b/cd3_automation_toolkit/user-scripts/tenancyconfig.properties index d5283792f..875ed1033 100644 --- a/cd3_automation_toolkit/user-scripts/tenancyconfig.properties +++ b/cd3_automation_toolkit/user-scripts/tenancyconfig.properties @@ -4,9 +4,8 @@ ## Required Parameters ## ################################################################################################################## -# Friendly name for the Customer Tenancy eg: demotenancy; The generated .auto.tfvars files will be prefixed with this -# customer_name. -customer_name= +# Friendly name for the Customer Tenancy eg: demotenancy; The generated .auto.tfvars files will be prefixed with this. +prefix= tenancy_ocid= @@ -40,6 +39,13 @@ fingerprint= #or outdir_structure_file=/cd3user/oci_tools/cd3_automation_toolkit/user-scripts/outdir_structure_file.properties + +# IaC Tool to be configured - Terraform or OpenTofu +# Default is terraform +# To use OpenTofu, specify tofu +tf_or_tofu=terraform + + # SSH Key for launched instances; Use '\n' as the delimiter to add multiple ssh keys. # Example: "ssh-rsa AAXXX......yhdlo\nssh-rsa AAxxskj...edfwf" # Optional diff --git a/cd3_automation_toolkit/user-scripts/terraform/adb.tf b/cd3_automation_toolkit/user-scripts/terraform/adb.tf index ead0d5a95..7f4f2b448 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/adb.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/adb.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Module Block - Autonomous database ## Create autonomous database diff --git a/cd3_automation_toolkit/user-scripts/terraform/backend.tf b/cd3_automation_toolkit/user-scripts/terraform/backend.tf index 16bc5577a..72183ffbe 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/backend.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/backend.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*This line will be removed when using remote state # !!! WARNING !!! Terraform State Lock is not supported with OCI Object Storage. # Pre-Requisite: Create a version enabled object storage bucket to store the state file. diff --git a/cd3_automation_toolkit/user-scripts/terraform/block-volume.tf b/cd3_automation_toolkit/user-scripts/terraform/block-volume.tf index f593e6b3f..2553b9766 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/block-volume.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/block-volume.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - BlockVolume # Create BlockVolume and Block Volume Backup Policy @@ -20,30 +21,30 @@ module "block-volumes" { attachment_type = each.value.attachment_type attach_to_instance = each.value.attach_to_instance != null ? length(regexall("ocid1.instance.oc*", each.value.attach_to_instance)) > 0 ? each.value.attach_to_instance : merge(module.instances.*...)[each.value.attach_to_instance]["instance_tf_id"] : null #attach_to_instance = length(each.value.attach_to_instance) > 0 ? [data.oci_core_instances.instance[each.value.display_name].instances[0].id] : [] - availability_domain = each.value.availability_domain != "" && each.value.availability_domain != null ? data.oci_identity_availability_domains.availability_domains.availability_domains[each.value.availability_domain].name : null - compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null - vpus_per_gb = each.value.vpus_per_gb != null ? each.value.vpus_per_gb : null - device = each.value.device - defined_tags = each.value.defined_tags - display_name = each.value.display_name - freeform_tags = each.value.freeform_tags - is_auto_tune_enabled = each.value.is_auto_tune_enabled - kms_key_id = each.value.kms_key_id - size_in_gbs = each.value.size_in_gbs != null ? each.value.size_in_gbs : null - block_tf_policy = each.value.backup_policy != null ? each.value.backup_policy : null - policy_tf_compartment_id = each.value.policy_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.policy_compartment_id)) > 0 ? each.value.policy_compartment_id : var.compartment_ocids[each.value.policy_compartment_id]) : null - autotune_policies = each.value.autotune_policies - source_details = each.value.source_details - block_volume_replicas = each.value.block_volume_replicas + availability_domain = each.value.availability_domain != "" && each.value.availability_domain != null ? data.oci_identity_availability_domains.availability_domains.availability_domains[each.value.availability_domain].name : null + compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null + vpus_per_gb = each.value.vpus_per_gb != null ? each.value.vpus_per_gb : null + device = each.value.device + defined_tags = each.value.defined_tags + display_name = each.value.display_name + freeform_tags = each.value.freeform_tags + is_auto_tune_enabled = each.value.is_auto_tune_enabled + kms_key_id = each.value.kms_key_id + size_in_gbs = each.value.size_in_gbs != null ? each.value.size_in_gbs : null + block_tf_policy = each.value.backup_policy != null ? each.value.backup_policy : null + policy_tf_compartment_id = each.value.policy_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.policy_compartment_id)) > 0 ? each.value.policy_compartment_id : var.compartment_ocids[each.value.policy_compartment_id]) : null + autotune_policies = each.value.autotune_policies + source_details = each.value.source_details + block_volume_replicas = each.value.block_volume_replicas block_volume_replicas_deletion = each.value.block_volume_replicas_deletion #Volume Attachment Optional Params # attachment_display_name = each.value.attachment_display_name # encryption_in_transit_type = each.value.encryption_in_transit_type # Applicable when attachment_type=iscsi is_pv_encryption_in_transit_enabled = each.value.is_pv_encryption_in_transit_enabled # Applicable when attachment_type=paravirtualized - is_read_only = each.value.is_read_only - is_shareable = each.value.is_shareable - use_chap = each.value.use_chap - is_agent_auto_iscsi_login_enabled = each.value.is_agent_auto_iscsi_login_enabled # Applicable when attachment_type=iscsi - blockvolume_source_ocids = var.blockvolume_source_ocids + is_read_only = each.value.is_read_only + is_shareable = each.value.is_shareable + use_chap = each.value.use_chap + is_agent_auto_iscsi_login_enabled = each.value.is_agent_auto_iscsi_login_enabled # Applicable when attachment_type=iscsi + blockvolume_source_ocids = var.blockvolume_source_ocids } diff --git a/cd3_automation_toolkit/user-scripts/terraform/budget.tf b/cd3_automation_toolkit/user-scripts/terraform/budget.tf index 522488095..48efa5807 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/budget.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/budget.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Cost Management # Create Budgets and Rule Alerts @@ -38,9 +39,9 @@ module "budgets" { #Required amount = each.value.amount - compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]):var.tenancy_ocid - - reset_period = each.value.reset_period != null ? each.value.reset_period : "MONTHLY" + compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : var.tenancy_ocid + + reset_period = each.value.reset_period != null ? each.value.reset_period : "MONTHLY" #Optional budget_processing_period_start_offset = each.value.budget_processing_period_start_offset @@ -51,12 +52,12 @@ module "budgets" { processing_period_type = each.value.processing_period_type budget_start_date = each.value.processing_period_type == "SINGLE_USE" ? each.value.budget_start_date : null budget_end_date = each.value.processing_period_type == "SINGLE_USE" ? each.value.budget_end_date : null - + #target_compartment_id = each.value.target_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.target_compartment_id)) > 0 ? each.value.target_compartment_id : var.compartment_ocids[each.value.target_compartment_id]) : null - + target_type = each.value.target_type #targets = each.value.targets - - targets = each.value.target_type == "COMPARTMENT" ? (length(regexall("ocid1.compartment.oc*", each.value.targets[0])) > 0 ? each.value.targets : [var.compartment_ocids[each.value.targets[0]]]) : each.value.targets + + targets = each.value.target_type == "COMPARTMENT" ? (length(regexall("ocid1.compartment.oc*", each.value.targets[0])) > 0 ? each.value.targets : [var.compartment_ocids[each.value.targets[0]]]) : each.value.targets } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/cloud-guard.tf b/cd3_automation_toolkit/user-scripts/terraform/cloud-guard.tf index 352a087c7..e374b31c6 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/cloud-guard.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/cloud-guard.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Security # Create Cloud Guard Configuration and Cloud Guard Targets diff --git a/cd3_automation_toolkit/user-scripts/terraform/database-exacs.tf b/cd3_automation_toolkit/user-scripts/terraform/database-exacs.tf index 7dfc1583d..1de378f45 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/database-exacs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/database-exacs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################ # Module Block - Database # Create ExaInfra diff --git a/cd3_automation_toolkit/user-scripts/terraform/dbsystem-vm-bm.tf b/cd3_automation_toolkit/user-scripts/terraform/dbsystem-vm-bm.tf index 8cffe73e2..1018a0a2e 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/dbsystem-vm-bm.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/dbsystem-vm-bm.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################ # Module Block - Database # Create DB Systems VM BM diff --git a/cd3_automation_toolkit/user-scripts/terraform/dedicated-vm-host.tf b/cd3_automation_toolkit/user-scripts/terraform/dedicated-vm-host.tf index 74eb287de..fbad3413c 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/dedicated-vm-host.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/dedicated-vm-host.tf @@ -1,4 +1,5 @@ -#// Copyright (c) 2021, 2022, Oracle and/or its affiliates. +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. # ################################### ## Module Block - Dedicated VM Host diff --git a/cd3_automation_toolkit/user-scripts/terraform/dns.tf b/cd3_automation_toolkit/user-scripts/terraform/dns.tf index 4175ac5fd..d295f8bc5 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/dns.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/dns.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# #################### ### DNS-Resolver ### #################### @@ -88,7 +91,7 @@ data "oci_dns_views" "resolver_views_data" { ### Module ### module "dns-resolvers" { - source = "./modules/network/dns/dns_resolver" + source = "./modules/network/dns/dns_resolver" # depends_on = [module.nsgs] # Uncomment to create NSG and DNS Resolvers together for_each = var.resolvers != null ? var.resolvers : {} target_resolver_id = data.oci_core_vcn_dns_resolver_association.resolver_vcn_dns_resolver_association[each.key].*.dns_resolver_id[0] diff --git a/cd3_automation_toolkit/user-scripts/terraform/firewall.tf b/cd3_automation_toolkit/user-scripts/terraform/firewall.tf index 4818d8443..dfeddcb58 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/firewall.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/firewall.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# data "oci_core_vcns" "firewall_vcns" { for_each = var.firewalls != null ? var.firewalls : {} compartment_id = each.value.network_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.network_compartment_id)) > 0 ? each.value.network_compartment_id : var.compartment_ocids[each.value.network_compartment_id]) : var.compartment_ocids[each.value.network_compartment_id] @@ -194,8 +197,8 @@ output "vcn_log_group_map" { */ module "fw-logs" { - source = "./modules/managementservices/log" - for_each = (var.fw_logs != null || var.fw_logs != {}) ? var.fw_logs : {} + source = "./modules/managementservices/log" + for_each = (var.fw_logs != null || var.fw_logs != {}) ? var.fw_logs : {} # Logs #Required diff --git a/cd3_automation_toolkit/user-scripts/terraform/fss.tf b/cd3_automation_toolkit/user-scripts/terraform/fss.tf index dbe367f14..39b64ee40 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/fss.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/fss.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Storage # Create FSS @@ -53,11 +54,11 @@ module "fss" { compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null #Optional - defined_tags = each.value.defined_tags - display_name = each.value.display_name - freeform_tags = each.value.freeform_tags - kms_key_id = each.value.kms_key_id - source_snapshot_id = each.value.source_snapshot != null ? (length(regexall("ocid1.snapshot.oc*", each.value.source_snapshot)) > 0 ? each.value.source_snapshot : lookup(var.fss_source_ocids,each.value.source_snapshot,null)): null + defined_tags = each.value.defined_tags + display_name = each.value.display_name + freeform_tags = each.value.freeform_tags + kms_key_id = each.value.kms_key_id + source_snapshot_id = each.value.source_snapshot != null ? (length(regexall("ocid1.snapshot.oc*", each.value.source_snapshot)) > 0 ? each.value.source_snapshot : lookup(var.fss_source_ocids, each.value.source_snapshot, null)) : null filesystem_snapshot_policy_id = each.value.snapshot_policy policy_compartment_id = each.value.policy_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.policy_compartment_id)) > 0 ? each.value.policy_compartment_id : var.compartment_ocids[each.value.policy_compartment_id]) : var.compartment_ocids[each.value.compartment_id] } @@ -81,13 +82,13 @@ module "fss-replication" { for_each = (var.fss_replication != null || var.fss_replication != {}) ? var.fss_replication : {} #Required - compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc1*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null - source_id = length(regexall("ocid1.filesystem.oc1*", each.value.source_id)) > 0 ? each.value.source_id : merge(module.fss.*...)[each.value.source_id]["fss_tf_id"] - target_id = length(regexall("ocid1.filesystem.oc1*", each.value.target_id)) > 0 ? each.value.target_id : merge(module.fss.*...)[each.value.target_id]["fss_tf_id"] + compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc1*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null + source_id = length(regexall("ocid1.filesystem.oc1*", each.value.source_id)) > 0 ? each.value.source_id : merge(module.fss.*...)[each.value.source_id]["fss_tf_id"] + target_id = length(regexall("ocid1.filesystem.oc1*", each.value.target_id)) > 0 ? each.value.target_id : merge(module.fss.*...)[each.value.target_id]["fss_tf_id"] #Optional - defined_tags = each.value.defined_tags - display_name = each.value.display_name - freeform_tags = each.value.freeform_tags + defined_tags = each.value.defined_tags + display_name = each.value.display_name + freeform_tags = each.value.freeform_tags replication_interval = each.value.replication_interval } @@ -120,8 +121,8 @@ output "log_group_map" { */ module "nfs-logs" { - source = "./modules/managementservices/log" - for_each = (var.nfs_logs != null || var.nfs_logs != {}) ? var.nfs_logs : {} + source = "./modules/managementservices/log" + for_each = (var.nfs_logs != null || var.nfs_logs != {}) ? var.nfs_logs : {} # Logs #Required diff --git a/cd3_automation_toolkit/user-scripts/terraform/identity.tf b/cd3_automation_toolkit/user-scripts/terraform/identity.tf index a83c307e9..e9d97d380 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/identity.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/identity.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Identity # Create Compartments @@ -158,13 +159,15 @@ output "sub_compartments_level5_map" { ############################ module "iam-groups" { + source = "./modules/identity/iam-group" for_each = var.groups - + depends_on = [module.iam-users] tenancy_ocid = var.tenancy_ocid group_name = each.value.group_name group_description = each.value.group_description matching_rule = each.value.matching_rule + members = lookup(each.value, "members", []) #Optional defined_tags = each.value.defined_tags @@ -217,16 +220,13 @@ output "policies_id_map" { module "iam-users" { source = "./modules/identity/iam-user" - depends_on = [module.iam-groups] + #depends_on = [module.iam-groups] for_each = var.users user_name = each.value.name user_description = each.value.description user_email = each.value.email - group_membership = each.value.group_membership != null ? each.value.group_membership : null - #group_membership = each.value.group_membership != null ? length(regexall("ocid1.groupmembership.oc*", each.value.group_membership.0)) > 0 ? each.value.group_membership.0 : merge(module.iam-groups.*...)[each.value.group_membership.0]["group_tf_id"] : null tenancy_ocid = var.tenancy_ocid - disable_capabilities = each.value.disable_capabilities != null ? each.value.disable_capabilities : null - + enabled_capabilities = each.value.enabled_capabilities != null ? each.value.enabled_capabilities : null #Optional defined_tags = each.value.defined_tags @@ -277,4 +277,64 @@ module "iam-network-sources" { #vcn_comp_map = each.value.vcn_comp_map != null ? each.value.vcn_comp_map : null defined_tags = try(each.value.defined_tags, null) freeform_tags = try(each.value.freeform_tags, null) +} +############################ +# Module Block - Identity +# Create Identity Domain Groups +############################ +data "oci_identity_domains" "iam_domains" { + for_each = merge(var.identity_domain_groups,var.identity_domain_users) + # Required + compartment_id = var.compartment_ocids[each.value.compartment_id] + # Optional + display_name = each.value.idcs_endpoint +} + +module "groups" { + + depends_on = [module.users] + + source = "./modules/identity/identity-domain-group" + for_each = var.identity_domain_groups + + group_name = each.value.group_name + group_description = each.value.group_description + matching_rule = each.value.matching_rule + compartment_id = each.value.compartment_id != "root" ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : var.tenancy_ocid + identity_domain = data.oci_identity_domains.iam_domains[each.key].domains[0] + tenancy_ocid = var.tenancy_ocid + members = each.value.members != null ? each.value.members : [] + + #Optional + defined_tags = each.value.defined_tags + freeform_tags_key = each.value.freeform_tags != null ? each.value.freeform_tags.key : null + freeform_tags_value = each.value.freeform_tags != null ? each.value.freeform_tags.value : null + +} + +############################ +# Module Block - Identity +# Create Identity Domain Users +############################ + +module "users" { + source = "./modules/identity/identity-domain-user" + #depends_on = [module.iam-groups] + for_each = var.identity_domain_users + user_name = each.value.user_name + family_name = each.value.family_name + identity_domain = data.oci_identity_domains.iam_domains[each.key].domains[0] + compartment_id = each.value.compartment_id != "root" ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : var.tenancy_ocid + description = each.value.description + email = each.value.email + tenancy_ocid = var.tenancy_ocid + groups = each.value.groups != null ? each.value.groups : null + + enabled_capabilities = each.value.enabled_capabilities + + #Optional + defined_tags = each.value.defined_tags + freeform_tags_key = each.value.freeform_tags != null ? each.value.freeform_tags.key : null + freeform_tags_value = each.value.freeform_tags != null ? each.value.freeform_tags.value : null + } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/instance.tf b/cd3_automation_toolkit/user-scripts/terraform/instance.tf index 10b191ea0..cd10c1e88 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/instance.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/instance.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Module Block - Instances ## Create Instance @@ -21,7 +22,7 @@ data "oci_core_vcns" "oci_vcns" { } module "instances" { - source = "./modules/compute/instance" + source = "./modules/compute/instance" # depends_on = [module.nsgs] # Uncomment to create NSG and Instances together for_each = var.instances != null ? var.instances : {} availability_domain = each.value.availability_domain != "" && each.value.availability_domain != null ? data.oci_identity_availability_domains.availability_domains.availability_domains[each.value.availability_domain].name : "" diff --git a/cd3_automation_toolkit/user-scripts/terraform/kms.tf b/cd3_automation_toolkit/user-scripts/terraform/kms.tf index d6bd1f57e..fb1051c13 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/kms.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/kms.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################ # Module Block - Security # Create KMS Vault and Key @@ -13,10 +14,10 @@ module "vaults" { compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null #Optional - defined_tags = each.value.defined_tags - display_name = each.value.display_name - freeform_tags = each.value.freeform_tags - vault_type = each.value.vault_type + defined_tags = each.value.defined_tags + display_name = each.value.display_name + freeform_tags = each.value.freeform_tags + vault_type = each.value.vault_type replica_region = each.value.replica_region } @@ -28,14 +29,14 @@ module "keys" { compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null #Optional - defined_tags = each.value.defined_tags - display_name = each.value.display_name - freeform_tags = each.value.freeform_tags - algorithm = each.value.algorithm != null ? each.value.algorithm : "AES" - length = each.value.length != null ? each.value.length : 32 - curve_id = each.value.curve_id != null?each.value.curve_id: null - management_endpoint = merge(module.vaults.*...)[each.value.vault_name]["management_endpoint_tf_id"] - protection_mode = each.value.protection_mode - is_auto_rotation_enabled = each.value.is_auto_rotation_enabled - rotation_interval_in_days = each.value.rotation_interval_in_days !=null ? each.value.rotation_interval_in_days : 60 + defined_tags = each.value.defined_tags + display_name = each.value.display_name + freeform_tags = each.value.freeform_tags + algorithm = each.value.algorithm != null ? each.value.algorithm : "AES" + length = each.value.length != null ? each.value.length : 32 + curve_id = each.value.curve_id != null ? each.value.curve_id : null + management_endpoint = merge(module.vaults.*...)[each.value.vault_name]["management_endpoint_tf_id"] + protection_mode = each.value.protection_mode + is_auto_rotation_enabled = each.value.is_auto_rotation_enabled + rotation_interval_in_days = each.value.rotation_interval_in_days != null ? each.value.rotation_interval_in_days : 60 } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/loadbalancer.tf b/cd3_automation_toolkit/user-scripts/terraform/loadbalancer.tf index b3831f5f9..ea0eb5e11 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/loadbalancer.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/loadbalancer.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Network # Create Load Balancers @@ -18,7 +19,11 @@ data "oci_certificates_management_certificates" "certificates_backendsets" { data "oci_core_instances" "instances" { # depends_on = [module.instances] # Uncomment to create Compute and Load Balancers together for_each = var.backends != null ? var.backends : {} - state = "RUNNING" + #state = "RUNNING" + filter { + name = "state" + values = ["RUNNING","STOPPED"] + } #Required compartment_id = each.value.instance_compartment != null && each.value.instance_compartment != "" ? (length(regexall("ocid1.compartment.oc*", each.value.instance_compartment)) > 0 ? each.value.instance_compartment : var.compartment_ocids[each.value.instance_compartment]) : var.tenancy_ocid } @@ -245,6 +250,24 @@ output "rule_sets_id_map" { } */ +module "routing-policies" { + source = "./modules/loadbalancer/lb-routing-policy" + for_each = var.lb_routing_policies != null ? var.lb_routing_policies : {} + + condition_language_version = each.value.condition_language_version != null ? each.value.condition_language_version : null + load_balancer_id = length(regexall("ocid1.loadbalancer.oc*", each.value.load_balancer_id)) > 0 ? each.value.load_balancer_id : merge(module.load-balancers.*...)[each.value.load_balancer_id]["load_balancer_tf_id"] + name = each.value.name != null ? each.value.name : null + #backend_set_name = each.value.backend_set_name != null ? merge(module.backend-sets.*...)[each.value.backend_set_name].backend_set_tf_name : null + rules = each.value.rules != null ? each.value.rules : [] + +} + +/* +output "routing_policy_tf_id_map" { + value = [ for k,v in merge(module.routing-policies.*...) : v.routing_policy_tf_id ] +} +*/ + ############################# # Module Block - LBaaS Logging # Create Log Groups and Logs @@ -273,8 +296,8 @@ output "log_group_map" { */ module "loadbalancer-logs" { - source = "./modules/managementservices/log" - for_each = (var.loadbalancer_logs != null || var.loadbalancer_logs != {}) ? var.loadbalancer_logs : {} + source = "./modules/managementservices/log" + for_each = (var.loadbalancer_logs != null || var.loadbalancer_logs != {}) ? var.loadbalancer_logs : {} # Logs #Required diff --git a/cd3_automation_toolkit/user-scripts/terraform/managementservices.tf b/cd3_automation_toolkit/user-scripts/terraform/managementservices.tf index a7d0f1d57..5f5bf3799 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/managementservices.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/managementservices.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - ManagementServices # Create Alarms diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/main.tf index 498a7a67e..89c3ca674 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/main.tf @@ -1,4 +1,5 @@ -#// Copyright (c) 2021, 2022, Oracle and/or its affiliates. +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. # ##################################### ## Resource Block - Dedicated VM Host diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/outputs.tf index 7528dd246..aa79e5921 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################### # Outputs Block - Dedicated VM Host # Create Dedicated VM Hosts diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/variables.tf index 98265098f..faa823096 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/dedicated-vm-host/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ##################################### # Variables Block - Dedicated VM Host # Create Dedicated VM Hosts diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/data.tf index 1c6f63a29..bf70bd1b1 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Instance ## Create Instance and Boot Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/main.tf index 683be11a2..176be951a 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Resource Block - Instance ## Create Instance and Boot Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/outputs.tf index 8dcb1e603..3b5a4861d 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Instance # Create Instance and Boot Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/variables.tf index d4a9e000e..0ac0265fe 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/compute/instance/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Instance # Create Instance and Boot Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/main.tf index 7a0cd1ff8..84fa36ddd 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Cost Management ## Create Budget Alert Rule diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/outputs.tf index dca802816..c6b372a1d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Cost Management ## Create Budget Alert Rule diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/variables.tf index 3f91592fe..bed2a0870 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget-alert-rule/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Cost Management ## Create Budget Alert Rule diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/main.tf index ce7d548fe..e12eeadcb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Cost Management ## Create Budget diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/outputs.tf index e764f433f..626d9c9dc 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Cost Management ## Create Budget diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/variables.tf index 809464db0..c95df7ea3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/costmanagement/budget/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Cost Management ## Create Budget diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/data.tf index 4d1cf1f93..b3f74ce95 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Autonomous database ## Create autonomous database diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/main.tf index 01af2c253..725197132 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Autonomous database ## Create autonomous database diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/outputs.tf index 912510ed3..0e5c6b0d3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Autonomous database ## Create autonomous database diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/variables.tf index 57f05d2a6..ef4faad3d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/adb/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Autonomous database ## Create autonomous database diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/data.tf index ad18dc09d..cd87e2b7b 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Database # Create ExaVMClusters diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/main.tf index 0d383dd2f..10a259dde 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Database # Create Database VM BM diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/outputs.tf index 8f17e57a9..2a09f2901 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Database # Create Database VM BM diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/variables.tf index b44c16409..1e1fbd27d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/dbsystem-vm-bm/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Database # Create Database VM BM diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/main.tf index 046e006bf..f094810cb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Database # Create ExaInfra diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/outputs.tf index 2e8334ba9..4823317e1 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Database # Create ExaInfra diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/variables.tf index a5e910da4..970e3b841 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-infra/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Database # Create ExaInfra diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/data.tf index 9a8582bdf..73a7e88e9 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Database # Create ExaVMClusters diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/main.tf index 9eff6bbc7..7c673ff3a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Database # Create ExaVMClusters diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/outputs.tf index 0e20768ac..0b3d680bc 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Database # Create ExaVMClusters diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/variables.tf index e6993622f..f3a8de2cf 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/database/exa-vmcluster/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Database # Create ExaVMClusters diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/main.tf index 48e4c1c13..1583c8986 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Governance # Create Quota Policies diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/outputs.tf index db715e18b..d0992446e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Governance # Create Tag Defaults diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/variables.tf index 0adcecddf..2099b7e3e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/quota-policy/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2024, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Governance # Create Tag Defaults diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/main.tf index 29a1cfa08..7cf5e0b2e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Governance # Create Tag Defaults diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/outputs.tf index ebada5fbb..848fe37a9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Governance # Create Tag Defaults diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/variables.tf index aa04d95ce..35a00cd20 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-default/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Governance # Create Tag Defaults diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/main.tf index a0d13f8d8..899106559 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Governance # Create Tag Key diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/outputs.tf index 2240ac8b4..98a76c847 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Governance # Create Tag Key diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/variables.tf index ae55d4432..d667638a1 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-key/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Governance # Create Tag Key diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/main.tf index f7e5efae4..94b51a63f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Governance # Create Namespaces diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/outputs.tf index 8bd3d22f6..f4431a6d1 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Governance # Create Namespaces diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/variables.tf index 2520deecc..ee83f574d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/governance/tagging/tag-namespace/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Governance # Create Namespaces diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/main.tf index 234691b73..3a1551dca 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Identity # Create Compartments diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/outputs.tf index 9d83d5f39..90279442c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Identity # Create Compartments diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/variables.tf index 0c3dc9e71..d905ee8ef 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-compartment/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Identity # Create Compartments diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/data.tf index 28ec24b94..d269b4e3f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# data "oci_identity_users" "users" { compartment_id = var.tenancy_ocid diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/main.tf index 351e5cfb8..04b5b1b0a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/main.tf @@ -1,42 +1,45 @@ // Copyright (c) 2021, 2022, Oracle and/or its affiliates. - ############################ # Resource Block - Identity # Create Groups ############################ - +locals { + user_ids = { + for user in data.oci_identity_users.users.users : + user.name => user.id + } +} resource "oci_identity_group" "group" { count = (var.matching_rule != "" && var.matching_rule != null) ? 0 : 1 - #Required compartment_id = var.tenancy_ocid description = var.group_description name = var.group_name - #Optional defined_tags = var.defined_tags freeform_tags = var.freeform_tags - } - +resource "oci_identity_user_group_membership" "user_group_membership" { + for_each = { + for member in var.members : member => member + } + group_id = oci_identity_group.group[0].id + user_id = local.user_ids[each.key] +} ############################ # Resource Block - Identity # Create Dynamic Groups ############################ - resource "oci_identity_dynamic_group" "dynamic_group" { count = (var.matching_rule != "" && var.matching_rule != null) ? 1 : 0 - #Required compartment_id = var.tenancy_ocid description = var.group_description matching_rule = var.matching_rule name = var.group_name - #Optional defined_tags = var.defined_tags freeform_tags = var.freeform_tags - lifecycle { ignore_changes = [defined_tags["Oracle-Tags.CreatedOn"], defined_tags["Oracle-Tags.CreatedBy"]] } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/outputs.tf index e67e22c80..2cc96b96f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Identity # Create Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/variables.tf index eaed9ad59..34f008c83 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-group/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Identity # Create Groups @@ -11,6 +12,18 @@ variable "tenancy_ocid" { default = null } +variable "members" { + description = "List of members" + type = list(string) + default = [] +} + +variable "group_membership" { + type = list(string) + description = "The name of the group user is member of." + default = [] +} + variable "group_name" { type = string description = "The name you assign to the group during creation. The name must be unique across all compartments in the tenancy." diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/main.tf index bc1aa67d1..947e8b280 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Identity # Create network source diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/outputs.tf index 4d099bc10..486188256 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Identity # Create Network Source diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/variables.tf index 80a858f32..00de50594 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-network-sources/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Identity # Create Users diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/main.tf index c9e7fec03..8b7c496cc 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Resource Block - Identity # Create Policies diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/outputs.tf index f43e40b4b..54ce2fb37 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Identity # Create Policies diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/variables.tf index aec81b98d..1735ec69d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-policy/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Identity # Create Policies diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/data.tf index 431eb5395..7856ec049 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Identity # Create Users diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/main.tf index 2ab4abf88..0a7f253c9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Identity # Create Users @@ -19,22 +20,14 @@ resource "oci_identity_user" "user" { } -resource "oci_identity_user_group_membership" "user_group_membership" { - count = var.group_membership != null ? length(var.group_membership) : 0 - depends_on = [oci_identity_user.user] - user_id = oci_identity_user.user.id - group_id = length(regexall("ocid1.group.oc*", var.group_membership[count.index])) > 0 ? var.group_membership[count.index] : data.oci_identity_groups.iam_groups.groups[index(data.oci_identity_groups.iam_groups.groups.*.name, var.group_membership[count.index])].id -} - resource "oci_identity_user_capabilities_management" "user_capabilities_management" { - count = var.disable_capabilities != null ? 1 : 0 + count = var.enabled_capabilities != null ? 1 : 0 depends_on = [oci_identity_user.user] user_id = oci_identity_user.user.id - can_use_api_keys = var.disable_capabilities != null && contains(var.disable_capabilities, "can_use_api_keys") ? false : true - can_use_auth_tokens = var.disable_capabilities != null && contains(var.disable_capabilities, "can_use_auth_tokens") ? false : true - can_use_console_password = var.disable_capabilities != null && contains(var.disable_capabilities, "can_use_console_password") ? false : true - can_use_customer_secret_keys = var.disable_capabilities != null && contains(var.disable_capabilities, "can_use_customer_secret_keys") ? false : true - can_use_smtp_credentials = var.disable_capabilities != null && contains(var.disable_capabilities, "can_use_smtp_credentials") ? false : true - + can_use_api_keys = contains(var.enabled_capabilities, "api_keys") ? true :false + can_use_auth_tokens = contains(var.enabled_capabilities, "auth_tokens") ? true :false + can_use_console_password = contains(var.enabled_capabilities, "console_password") ? true :false + can_use_customer_secret_keys = contains(var.enabled_capabilities, "customer_secret_keys") ? true :false + can_use_smtp_credentials = contains(var.enabled_capabilities, "smtp_credentials") ? true :false } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/outputs.tf index 8a228692b..0fae36c7f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Identity # Create Users diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/variables.tf index ce1086d34..c06fc7010 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/iam-user/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - Identity # Create Users @@ -52,9 +53,9 @@ variable "user_email" { default = null } -variable "disable_capabilities" { +variable "enabled_capabilities" { type = list(string) - description = "The name of the capabilities disabled for user" + description = "The name of the capabilities enabled for user" default = [] } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/data.tf new file mode 100644 index 000000000..bf3cd9ffc --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/data.tf @@ -0,0 +1,31 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################# +## Data Block - Identity +# Create Groups +############################# +/* +data "oci_identity_domains" "iam_domains" { + # Required + compartment_id = var.compartment_id + # Optional + display_name = var.idcs_endpoint + +}*/ + +############################ +# Data Source Block - Identity +# Get User Information by Email +############################ + + +data "oci_identity_domains_users" "users" { + idcs_endpoint = var.identity_domain.url +} + + + + + + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/main.tf new file mode 100644 index 000000000..3df671155 --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/main.tf @@ -0,0 +1,120 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################ +# Resource Block - Identity +# Create Groups +############################ +locals { + user_ids = { + for user in data.oci_identity_domains_users.users.users : + user.user_name => user.id + } +} + +resource "oci_identity_domains_group" "group" { + count = (var.matching_rule == "" || var.matching_rule == null) ? 1 : 0 + #Required + display_name = var.group_name + attribute_sets = ["all"] + attributes = "members" + idcs_endpoint = var.identity_domain.url + schemas = [ + "urn:ietf:params:scim:schemas:core:2.0:Group", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:OCITags", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:group:Group", + ] + timeouts {} + urnietfparamsscimschemasoracleidcsextensiongroup_group { + description = var.group_description + } + + dynamic "members" { + for_each = {for k in var.members: k=>k} + content { + type = "User" + value = local.user_ids[members.value] + } + } + + urnietfparamsscimschemasoracleidcsextension_oci_tags { + + # Optional + dynamic "defined_tags" { + for_each = var.defined_tags != null ? var.defined_tags : [] + content { + key = defined_tags.value.key + namespace = defined_tags.value.namespace + value = defined_tags.value.value + } + } + dynamic "freeform_tags" { + for_each = var.freeform_tags_key != null && var.freeform_tags_value != null ? [1] : [] + content { + key = var.freeform_tags_key + value = var.freeform_tags_value + } + } + } + + # Add the lifecycle block to ignore changes to specified attributes + lifecycle { + ignore_changes = [ + schemas, + urnietfparamsscimschemasoracleidcsextension_oci_tags["defined_tags.CreatedOn"], + urnietfparamsscimschemasoracleidcsextension_oci_tags["defined_tags.CreatedBy"], + ] + } +} + +############################ +# Resource Block - Identity +# Create Dynamic Groups +############################ + +resource "oci_identity_domains_dynamic_resource_group" "dynamic_group" { + count = (var.matching_rule != "" && var.matching_rule != null) ? 1 : 0 + + #Required + display_name = var.group_name + attribute_sets = ["all"] + attributes = "matching_rule" + idcs_endpoint = var.identity_domain.url + matching_rule = var.matching_rule + schemas = [ + "urn:ietf:params:scim:schemas:oracle:idcs:DynamicResourceGroup", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:OCITags", + ] + description = var.group_description + timeouts {} + + urnietfparamsscimschemasoracleidcsextension_oci_tags { + + # Optional + dynamic "defined_tags" { + for_each = var.defined_tags != null ? var.defined_tags : [] + content { + key = defined_tags.value.key + namespace = defined_tags.value.namespace + value = defined_tags.value.value + } + } + + dynamic "freeform_tags" { + for_each = var.freeform_tags_key != null && var.freeform_tags_value != null ? [1] : [] + content { + key = var.freeform_tags_key + value = var.freeform_tags_value + } + } + } + # Add the lifecycle block to ignore changes to specified attributes + lifecycle { + ignore_changes = [ + schemas, + urnietfparamsscimschemasoracleidcsextension_oci_tags["defined_tags.CreatedOn"], + urnietfparamsscimschemasoracleidcsextension_oci_tags["defined_tags.CreatedBy"], + ] + } +} + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/oracle_provider_req.tf new file mode 100644 index 000000000..f1f97aaeb --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/oracle_provider_req.tf @@ -0,0 +1,10 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +terraform { + required_providers { + oci = { + source = "oracle/oci" + } + } +} \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/outputs.tf new file mode 100644 index 000000000..0ddcf583d --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/outputs.tf @@ -0,0 +1,19 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################ +# Output Block - Identity +# Create Groups +############################ +output "group_id_map" { + description = "Group ocid" + value = zipmap(oci_identity_domains_group.group.*.display_name, oci_identity_domains_group.group.*.id) +} + +output "dynamic_group_id_map" { + description = "Dynamic Group ocid" + value = zipmap(oci_identity_domains_dynamic_resource_group.dynamic_group.*.display_name, oci_identity_domains_dynamic_resource_group.dynamic_group.*.id) +} + + + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/variables.tf new file mode 100644 index 000000000..6330456d5 --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-group/variables.tf @@ -0,0 +1,83 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################ +# Variables Block - Identity +# Create Groups +############################ + +variable "compartment_id" { + description = "The compartment ID information" + type = string + default = null +} + +variable "user_id" { + description = "Id of the user" + type = string + default = null +} + +/*variable "members" { + type = list(object({ + type = string + value = string + })) + default = [] +}*/ + +variable "members" { + description = "List of email ids of the users" + type = list(string) +} + + +variable "identity_domain" { +default = {} +} + + +variable "tenancy_ocid" { + type = string + description = "The OCID of the tenancy." + default = null +} + +variable "group_name" { + type = string + description = "The name you assign to the group during creation. The name must be unique across all compartments in the tenancy." + default = null +} + +variable "group_description" { + type = string + description = "The description you assign to the Group. Does not have to be unique, and it's changeable. " + default = null +} + +variable "matching_rule" { + type = string + description = "The matching rule associated with the dynamic group" + default = "" +} + +variable "defined_tags" { + description = "Defined tags for the group" + type = list(object({ + key = string + namespace = string + value = string + })) + default = [] +} + +variable "freeform_tags_key" { + type = string + default = "" +} + +variable "freeform_tags_value" { + type = string + default = "" +} + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/data.tf new file mode 100644 index 000000000..bf2968dab --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/data.tf @@ -0,0 +1,15 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################# +## Data Block - Identity +# Create Users +############################# + +/*data "oci_identity_domains" "iam_domains" { + # Required + compartment_id = var.compartment_id + # Optional + display_name = var.idcs_endpoint + +}*/ \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/main.tf new file mode 100644 index 000000000..9ec42d61d --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/main.tf @@ -0,0 +1,74 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################ +# Resource Block - Identity +# Create Users +############################ + +resource "oci_identity_domains_user" "user" { + + #Required + schemas = ["urn:ietf:params:scim:schemas:core:2.0:User", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:userState:User", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:OCITags", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:capabilities:User", + "urn:ietf:params:scim:schemas:oracle:idcs:extension:user:User"] + description = var.description + name { + family_name = var.family_name + } + idcs_endpoint = var.identity_domain.url + user_name = var.user_name + emails { + primary = "true" + secondary = "false" + type = "work" + value = var.email + verified = "false" + } + + urnietfparamsscimschemasoracleidcsextensioncapabilities_user { + + can_use_api_keys = contains(var.enabled_capabilities, "api_keys") ? true :false + can_use_auth_tokens = contains(var.enabled_capabilities, "auth_tokens") ? true :false + can_use_console_password = contains(var.enabled_capabilities, "console_password") ? true :false + can_use_customer_secret_keys = contains(var.enabled_capabilities, "customer_secret_keys") ? true :false + can_use_smtp_credentials = contains(var.enabled_capabilities, "smtp_credentials") ? true :false + can_use_db_credentials = contains(var.enabled_capabilities, "db_credentials") ? true :false + can_use_oauth2client_credentials = contains(var.enabled_capabilities, "oauth2client_credentials") ? true :false + } + dynamic "urnietfparamsscimschemasoracleidcsextension_oci_tags" { + for_each = var.defined_tags != null ? [1] :[] + content{ + # Optional + dynamic "defined_tags" { + for_each = var.defined_tags + content { + key = defined_tags.value.key + namespace = defined_tags.value.namespace + value = defined_tags.value.value + } + } + dynamic "freeform_tags" { + for_each = var.freeform_tags_key != null && var.freeform_tags_value != null ? [1] : [] + content { + key = var.freeform_tags_key + value = var.freeform_tags_value + } + } + } + } + lifecycle { + ignore_changes = [ + schemas, + urnietfparamsscimschemasoracleidcsextension_oci_tags["defined_tags.CreatedOn"], + urnietfparamsscimschemasoracleidcsextension_oci_tags["defined_tags.CreatedBy"], + emails + ] + } +} + + + + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/oracle_provider_req.tf new file mode 100644 index 000000000..f1f97aaeb --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/oracle_provider_req.tf @@ -0,0 +1,10 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +terraform { + required_providers { + oci = { + source = "oracle/oci" + } + } +} \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/outputs.tf new file mode 100644 index 000000000..7072738fb --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/outputs.tf @@ -0,0 +1,13 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################ +# Output Block - Identity +# Create Users +############################ + +output "user_id_map" { + description = "user ocid" + value = zipmap(oci_identity_domains_user.user.*.user_name, oci_identity_domains_user.user.*.id) +} + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/variables.tf new file mode 100644 index 000000000..d7437b3a6 --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/identity/identity-domain-user/variables.tf @@ -0,0 +1,95 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +############################ +# Variables Block - Identity +# Create Users +############################ + +variable "tenancy_ocid" { + type = string + default = null +} + +variable "compartment_id" { + type = string + default = null +} + +variable "user_name" { + type = string + description = "The name you assign to the user during creation. The name must be unique across all compartments in the tenancy." + default = null +} +variable "user_id" { + description = "email id of the user" + type = string + default = null +} + +variable "description" { + type = string + description = "The description of the user." + default = null +} + +variable "group_name" { + type = string + description = "The name of the group." + default = null +} + +variable "group_id" { + type = string + description = "The id of the group." + default = null +} + +variable "groups" { + type = list(string) + description = "The name of the group user is member of." + default = [] +} + + +variable "family_name" { + description = "Family Name of the user" + type = string + default = "Default" +} + +variable "identity_domain" { +default = {} +} + +variable "email" { + type = string + description = "The email you assign to the User. Does not have to be unique, and it's changeable. " + default = null +} + +variable "enabled_capabilities" { + type = list(string) + description = "The name of the capabilities enabled for user" + default = [] +} + +variable "defined_tags" { + description = "Defined tags for the group" + type = list(object({ + key = string + namespace = string + value = string + })) + default = [] +} + +variable "freeform_tags_key" { + type = string + default = "" +} + +variable "freeform_tags_value" { + type = string + default = "" +} \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/main.tf index 8f399a326..8e479b3af 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Public IP Pool ## Create Public IP Pool diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/outputs.tf index 3171b8e3f..ad798570a 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Public IP Pool ## Create Public IP Pool diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/variables.tf index 63b81c625..742c3b969 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/public-ip-pool/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Public IP Pool ## Create Public IP Pool diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/main.tf index c415f5906..e7b223da4 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Reserved IP ## Create Reserved IP diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/outputs.tf index f18a545bc..ec16fd816 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Reserved IP ## Create Reserved IP diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/variables.tf index 4c923f5f8..cea383746 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/reserved-public-ip/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Reserved IP ## Create Reserved IP diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/main.tf index ff73225d7..7212baf37 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Secondary Private IP ## Create Secondary Private IP diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/outputs.tf index da766644b..032bcba06 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Secondary Private IP ## Create Secondary Private IP diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/variables.tf index b64127c5b..48f8dd44e 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/ip/secondary-private-ip/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Secondary Private IP ## Create Secondary Private IP diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/main.tf index 8e1d91c9b..1c6869e4c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Backend Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/outputs.tf index e788b4326..b1e581086 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Backend Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/variables.tf index b4e3b1135..75533f676 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend-set/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Backend Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/main.tf index e999b14a1..4c097b945 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Backend diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/outputs.tf index 9324a0b4c..2e2f3865d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Backend diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/variables.tf index 6de352d53..a9614bc31 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-backend/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Backend diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/main.tf index fe90890fa..74bbded28 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Certificate diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/outputs.tf index 6e752af8e..161cee4fb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Certificate diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/variables.tf index ce467b0ad..ce2e4c3c8 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-certificate/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Certificate diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/main.tf index 3c1d071a6..1daeebbfa 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Cipher Suite diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/outputs.tf index 9e4092e0c..739d39450 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Cipher Suite diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/variables.tf index be9d8c999..734b56704 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-cipher-suite/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Cipher Suite diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/main.tf index 3a948b8e4..aa29e3641 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Hostname diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/outputs.tf index c9554d6ac..43217da71 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Hostname diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/variables.tf index a2af3590b..ffcf729c6 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-hostname/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Hostname diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/main.tf index bdd48c5d4..7a2c0d703 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Listener diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/outputs.tf index 57fc162ae..9867b170b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Listener diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/variables.tf index 7cb3c2fa6..e723de7be 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-listener/variables.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Listener diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/data.tf index 943ba1534..cc2d284b1 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Load Balancers ## Create Load Balancers diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/main.tf index 5e8e09f23..cbb649556 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/outputs.tf index ee3cbf949..eca8bc0e3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/variables.tf index 6f20012c9..39cfc2054 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-load-balancer/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/main.tf index 21dfb7b3d..e3c1fdc62 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Path Route Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/outputs.tf index 3ff264bae..5735c99bd 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Path Route Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/variables.tf index e750a6f97..752ab3615 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-path-route-set/variables.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Path Route Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/main.tf new file mode 100755 index 000000000..fd4680494 --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/main.tf @@ -0,0 +1,28 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +##################################### +# Resource Block - Load Balancer +# Create Load Balancer Routing Policy +##################################### + +resource "oci_load_balancer_load_balancer_routing_policy" "load_balancer_routing_policy" { + #Required + condition_language_version = var.condition_language_version + load_balancer_id = var.load_balancer_id + name = var.name + + dynamic rules { + for_each = var.rules != null ? var.rules : [] + content { + condition = rules.value.condition + name = rules.value.name + actions { + name = "FORWARD_TO_BACKENDSET" + backend_set_name = rules.value.backend_set_name + } + } + } + + +} diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/oracle_provider_req.tf new file mode 100755 index 000000000..f1f97aaeb --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/oracle_provider_req.tf @@ -0,0 +1,10 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +terraform { + required_providers { + oci = { + source = "oracle/oci" + } + } +} \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/outputs.tf new file mode 100755 index 000000000..0c178d33e --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/outputs.tf @@ -0,0 +1,12 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +##################################### +# Output Block - Load Balancer +# Create Load Balancer Routing Policy +##################################### + +output "id" { + description = "The OCID of the load balancer routing policy." + value = oci_load_balancer_load_balancer_routing_policy.load_balancer_routing_policy.id +} diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/variables.tf new file mode 100755 index 000000000..14303c244 --- /dev/null +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-routing-policy/variables.tf @@ -0,0 +1,27 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# +##################################### +# Variables Block - Load Balancer +# Create Load Balancer Routing Policy +##################################### + +variable "condition_language_version" { + description = "The version of the condition language." + type = string +} + +variable "load_balancer_id" { + description = "The OCID of the load balancer." + type = string +} + +variable "name" { + description = "The name of the load balancer routing policy." + type = string +} + +variable "rules" { + type = list(any) + default = null +} \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/main.tf index fcd6fdf5b..2614f070b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Load Balancer # Create Load Balancer Rule Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/outputs.tf index 584b365b3..99d900e28 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Load Balancer # Create Load Balancer Rule Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/variables.tf index 62ff5c694..62223596b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/loadbalancer/lb-rule-set/variables.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Load Balancer # Create Load Balancer Rule Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/main.tf index a63151473..056e500fa 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - ManagementServices # Create Alarms diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/outputs.tf index aa5bf12a0..2c51e71d1 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - ManagementServices # Create Alarms diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/variables.tf index c452baae3..d6e33c369 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/alarm/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - ManagementServices # Create Alarms diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/main.tf index 819a42661..1c896c30e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - ManagementServices # Create Events diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/outputs.tf index dbb99f712..d209aa961 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - ManagementServices # Create Events diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/variables.tf index 419c4ff9b..7b297bb92 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/event/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - ManagementServices # Create Events diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/main.tf index 31ee0c8ec..921643fff 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Module Block - Logging # Create Log Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/outputs.tf index f4eec2ef8..a007e4536 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Output Block - Logging # Create Log Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/variables.tf index 84b247d76..67af2d470 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log-group/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - Logging # Create Log Groups and Logs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/main.tf index bd82c649d..cbdde8934 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Module Block - Logging # Create Logs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/outputs.tf index ba26947d8..80e268416 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - ManagementServices # Create Log diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/variables.tf index d15680af1..f12c9df10 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/log/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - Logging # Create Log Groups and Logs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/main.tf index b0efebdeb..253535843 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - ManagementServices # Create Notifications_Subscriptions diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/outputs.tf index 680bf9fd5..fed34382a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - ManagementServices # Create Notifications_Subscriptions diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/variables.tf index c4185339b..f53a165a3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-subscription/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - ManagementServices # Create Notifications_Subscriptions diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/main.tf index 92272c91c..b471cc175 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - ManagementServices # Create Notifications_Topics diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/outputs.tf index 5af6eabd0..9c650d061 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - ManagementServices # Create Notifications_Topics diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/variables.tf index 5ab194d04..47d1f8ddb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/notification-topic/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variables Block - ManagementServices # Create Notifications_Topics diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/data.tf index 27a5d1757..b719e5a2c 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# #################################### # Data Block - Service Connector # Create Service Connector Hub diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/main.tf index 46f846eea..15cfbd7a4 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/main.tf @@ -1,4 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# #################################### # Resource Block - Service Connector # Create Service Connector Hub diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/outputs.tf index 57cb6eeb6..79c8838c3 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# #################################### # Outputs Block - Service Connector # Create Service Connector Hub diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/variables.tf index ed47bac45..ac5c44815 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/managementservices/service-connector/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ##################################### # Variables Block - Service Connector # Create Service Connector Hub diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/main.tf index 6e72c96f8..a7db4a8ae 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Custom DHCP Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/outputs.tf index cde7c6f3d..0560ef019 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Custom DHCP Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/variables.tf index f4dd4aed9..ef052dc51 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/custom-dhcp/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Custom DHCP Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/main.tf index ae94e804e..1cb92d334 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Default DHCP Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/outputs.tf index 7562b8297..659c98d5d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Default DHCP Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/variables.tf index e3228bc2c..6ebdfe01e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/default-dhcp/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Default DHCP Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/main.tf index bb046cf53..d02f618fd 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################## # Resource Block - DNS resolver and Endpoint # ############################################## diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/outputs.tf index 0e4ed7bac..2b94893a1 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/outputs.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Resolver# ############################ diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/variables.tf index 46bbf60e3..72521cd2c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/dns_resolver/variables.tf @@ -1,4 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - DNS Zone # ############################# diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/main.tf index 289d93fab..48cc677bf 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ########################## # Resource Block - rrset # ########################## diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/outputs.tf index 2f2b98a7d..f1a73a7c4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/outputs.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Steering Policy # ############################ diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/variables.tf index 97a5ba42d..ab5c26062 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/rrset/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - DNS Zone # ############################# diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/main.tf index d9cb73078..e94f4c48c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ######################### # Resource Block - View # ######################### diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/outputs.tf index a21041821..e8e76377a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/outputs.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - DNS view # ############################ diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/variables.tf index 144602b15..54580d640 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/view/variables.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - DNS View # ############################# diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/main.tf index bed261607..8744cb492 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ######################## # Resource Block - DNS # ######################## diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/outputs.tf index 79f1b5ea0..551e20e8f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/outputs.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - DNS Zone # ############################ diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/variables.tf index ffbce8bea..e394dc6f9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/dns/zone/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - DNS Zone # ############################# diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/main.tf index 4d730b2d4..0a4d02825 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/main.tf @@ -1,4 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Dynamic Routing Gateway Attachment diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/outputs.tf index 5e8cb7d9e..2b0a6a2ca 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Dynamic Routing Gateway Attachment diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/variables.tf index e14680a0e..bdc25216b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-attachment/variables.tf @@ -1,4 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Dynamic Routing Gateway Attachment diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/main.tf index 6b2d20198..8c95ae009 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ########################################## # Resource Block - Network # Create DRG Route Distributions Statement diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/outputs.tf index b85b39bcb..a44f039aa 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################ # Output Block - Network # Create DRG Route Distribution Statement diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/variables.tf index e4748b732..a81214e7a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution-statement/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################################ # Variable Block - Network # Create DRG Route Distribution Statement diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/main.tf index 7f4c7c402..1577e7de7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create DRG Route Distribution diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/outputs.tf index 0fda2bcd6..4dbf1ff77 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create DRG Route Distribution diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/variables.tf index 5f6995249..414a79706 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-distribution/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create DRG Route Distribution diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/main.tf index 41dd17dbf..286c0a109 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create DRG Route Rule diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/outputs.tf index 67bb12156..794ddcef2 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create DRG Route Rule diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/variables.tf index 725cff72d..9e14716eb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-rule/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create DRG Route Rule diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/main.tf index b44173bc6..b722949ba 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create DRG Route Table diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/outputs.tf index 372a96412..dd22fdc4e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create DRG Route Table diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/variables.tf index 46cde7dcd..dbca51b0f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg-route-table/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create DRG Route Table diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/main.tf index 64463e877..7fd3c2bbf 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Dynamic Routing Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/outputs.tf index 4ec5c15bb..b9c50bf63 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Dynamic Routing Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/variables.tf index 313d8ccad..c2f0e0e23 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/drg/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Dynamic Routing Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/main.tf index 9f650a9a8..29cd74ded 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Internet Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/outputs.tf index 5103f460c..40532745a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Internet Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/variables.tf index 6000efaab..e3cafc6f4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/igw/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Internet Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/main.tf index ff3a6aafe..1635f7b87 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Local Peering Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/outputs.tf index ec1ebd8a5..e4d818bae 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Local Peering Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/variables.tf index 46d7ee16d..2dae28891 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/lpg/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Local Peering Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/main.tf index 59752cac0..fddef2165 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create NAT Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/outputs.tf index ce3dc5338..341c1bb6d 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create NAT Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/variables.tf index d13868eb1..cc974013f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/ngw/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create NAT Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/main.tf index f5d2c4ed6..5d90a5aa6 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Network Security Group Rules diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/outputs.tf index 21bfd8ee9..724632e16 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Output Block - Networking # Create Network Security Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/variables.tf index b751c2eac..761d423d7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg-rule/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - Network # Create Network Security Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/main.tf index f415fafc0..898299763 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Network Security Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/outputs.tf index 457338b3b..e4cb4b326 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Output Block - Network # Create Network Security Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/variables.tf index 1b57ccc3a..e566c2828 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/nsg/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - Network # Create Network Security Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/main.tf index 39b85fa71..e3abe2bb0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Route Table diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/outputs.tf index 17d745e33..82b0e1b32 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Route Table diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/variables.tf index 6f5e19418..a93ddfa28 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/route-table/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Route Table diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/main.tf index 3b0e6d4b9..6fcec4e4a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Security List diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/outputs.tf index 79001cebf..d33b87c04 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Security List diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/variables.tf index 311b7f39c..9279daae8 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sec-list/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Security List diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/main.tf index 8d7421e99..af456e858 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Service Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/outputs.tf index 4e6823115..e9b572f11 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create Service Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/variables.tf index 5d37c11fa..6fb23edfc 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/sgw/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create Service Gateway diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/main.tf index d854a30c2..f822ae0c4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create Subnets diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/outputs.tf index e6410f665..1364137e9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Output Block - Network # Create Subnets diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/variables.tf index 6c6ef0d55..d79a40340 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/subnet/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Variable Block - Network # Create Subnets diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/main.tf index 6926738ef..43a488159 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create VCNs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/outputs.tf index 4a8822a55..15ec741e0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Network # Create VCNs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/variables.tf index 70d4b56e1..ceeb05d84 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vcn/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create VCNs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/data.tf index 74b845e1f..a99c14ac5 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - VLAN ## Create VLANs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/main.tf index 84c68ba1e..024c50fc4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Network # Create VLANs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/outputs.tf index 2961f92cd..1869b6704 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - VLAN # Create VLANs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/variables.tf index 741f57a53..d41592cf2 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/network/vlan/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Network # Create VLANs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/data.tf index 0a34582db..edeaa5d61 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/data.tf @@ -1,12 +1,17 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Data Block - Network Load Balancer # Create Network Load Balancer Backend ####################################### data "oci_core_instances" "nlb_instances" { - state = "RUNNING" + #state = "RUNNING" + filter { + name = "state" + values = ["RUNNING","STOPPED"] + } compartment_id = var.instance_compartment } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/main.tf index c8dc6c1a8..43079a11c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Resource Block - Network Load Balancer # Create Network Load Balancer Backend diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/outputs.tf index 723bc7804..4000d8885 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Output Block - Network Load Balancer # Create Network Load Balancer Backend diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/variables.tf index e56315b5b..806796e25 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backend/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Variable Block - Network Load Balancer # Create Network Load Balancer Backend diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/main.tf index 0987fbc3a..694b90957 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Resource Block - Network Load Balancer # Create Network Load Balancer Backend Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/outputs.tf index 0e231b4e2..466eeb389 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Resource Block - Network Load Balancer # Create Network Load Balancer Backend Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/variables.tf index 5f88dd94e..c9225034c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-backendset/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Variable Block - Network Load Balancer # Create Network Load Balancer Backend Set diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/main.tf index e7a2763d2..763ab03a2 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Resource Block - Network Load Balancer # Create Network Load Balancer Listener diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/outputs.tf index ef440063e..be81e3cab 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Output Block - Network Load Balancer # Create Network Load Balancer Listener diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/variables.tf index 8c4971e97..d5931b149 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb-listener/variables.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Variable Block - Network Load Balancer # Create Network Load Balancer Listener diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/data.tf index 70810e523..4eea41e7c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Data Block - Network Load Balancer # Create Network Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/main.tf index a7e27c964..511d8d62e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/main.tf @@ -1,6 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Resource Block - Network Load Balancer # Create Network Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/outputs.tf index a30c1f806..a60d87d23 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Output Block - Network Load Balancer # Create Network Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/variables.tf index 1e8a18c97..b51edf3a5 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/networkloadbalancer/nlb/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ######################################### # Variable Block - Network Load Balancer # Create Network Load Balancer diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/data.tf index 781f3c69e..665ee0c22 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Cluster ## Create Cluster diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/main.tf index 21b51bb11..9f0ead2d8 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/main.tf @@ -1,7 +1,6 @@ -# Copyright 2017, 2021 Oracle Corporation and/or affiliates. -# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl - - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_containerengine_cluster" "cluster" { compartment_id = var.compartment_id kubernetes_version = var.kubernetes_version diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/outputs.tf index 35bfb6e9e..2377b7009 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Cluster # Create Cluster diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/variables.tf index a45c67ee2..8bfd59b69 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/cluster/variables.tf @@ -1,6 +1,6 @@ -# Copyright 2017, 2019 Oracle Corporation and/or affiliates. -# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string description = "The OCID of the compartment" diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/data.tf index 738bddd9e..821d7c030 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Nodepool ## Create Nodepool and nodes diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/main.tf index ea604f9c9..2bd4762e9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/main.tf @@ -1,6 +1,6 @@ -# Copyright 2017, 2021 Oracle Corporation and/or affiliates. -# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_containerengine_node_pool" "nodepool" { cluster_id = var.cluster_name compartment_id = var.compartment_id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/outputs.tf index 6a9a80b54..8d764468b 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Nodepool # Create Nodepool and nodes diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/variables.tf index d3a391b0a..65aff7d4f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/nodepool/variables.tf @@ -1,6 +1,6 @@ -# Copyright 2017, 2019 Oracle Corporation and/or affiliates. -# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "tenancy_ocid" { type = string description = "The OCID of the tenancy" diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/data.tf index e8f9e1d9e..7bd2d9167 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Nodepool ## Create Nodepool and nodes diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/main.tf index e42f627ac..03874f8d2 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/main.tf @@ -1,6 +1,6 @@ -# Copyright 2017, 2021 Oracle Corporation and/or affiliates. -# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_containerengine_virtual_node_pool" "virtual_nodepool" { #Required cluster_id = var.cluster_name diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/outputs.tf index cc73dc459..95fdad8c0 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Nodepool # Create Nodepool and nodes diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/variables.tf index da0bba184..61be06540 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/oke/virtual-nodepool/variables.tf @@ -1,6 +1,6 @@ -# Copyright 2017, 2019 Oracle Corporation and/or affiliates. -# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "tenancy_ocid" { type = string description = "The OCID of the tenancy" diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/main.tf index f294c7e73..45f2d66b5 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - SDDC Cluster # Create SDDC Cluster diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/oracle_provider_req.tf index e52742e05..f1f97aaeb 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/outputs.tf index 921f98057..a81741b06 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Custom Backup Policy # Create Custom Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/variables.tf index cdcd153e0..9b6ff0ec9 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc-cluster/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - SDDC # Create SDDC diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/main.tf index dbee99918..067981893 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - SDDC # Create SDDC diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/oracle_provider_req.tf index e52742e05..f1f97aaeb 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/outputs.tf index 3abd8bd2f..75a40316f 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Outputs Block - Custom Backup Policy # Create Custom Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/variables.tf index 6f796ee23..575cea0a6 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/sddc/sddc/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - SDDC # Create SDDC diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/main.tf index adc62b7c7..6852c0ce0 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Security ## Create Cloud Guard Config diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/outputs.tf index d43779016..bf0769c30 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Security ## Create Cloud Guard Config diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/variables.tf index 2526790e6..67877c898 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-configuration/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Security ## Create Cloud Guard Config diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/data.tf index 3a78bca75..135a75cab 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Data Block - Security ## Create Cloud Guard Target @@ -7,9 +8,10 @@ locals { detector_recipes = { - "OCI Activity Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_activity_detector_recipes.detector_recipe_collection[0].items[0].id - "OCI Configuration Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_config_detector_recipes.detector_recipe_collection[0].items[0].id - "OCI Threat Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_threat_detector_recipes.detector_recipe_collection[0].items[0].id + "OCI Activity Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_activity_detector_recipes.detector_recipe_collection[0].items[0].id + "OCI Configuration Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_config_detector_recipes.detector_recipe_collection[0].items[0].id + "OCI Threat Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_threat_detector_recipes.detector_recipe_collection[0].items[0].id + "OCI Instance Security Detector Recipe" = data.oci_cloud_guard_detector_recipes.root_instance_security_detector_recipes.detector_recipe_collection[0].items[0].id } responder_recipes = { "OCI Responder Recipe" = data.oci_cloud_guard_responder_recipes.root_responder_recipes.responder_recipe_collection[0].items[0].id @@ -39,3 +41,11 @@ data "oci_cloud_guard_detector_recipes" "root_threat_detector_recipes" { compartment_id = var.tenancy_ocid display_name = "OCI Threat Detector Recipe" } + +data "oci_cloud_guard_detector_recipes" "root_instance_security_detector_recipes" { + #Required + compartment_id = var.tenancy_ocid + display_name = "OCI Instance Security Detector Recipe" +} + + diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/main.tf index d726d1143..73fe7352e 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Security ## Create Cloud Guard Target diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/outputs.tf index 261c819b8..855f6e75e 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Security ## Create Cloud Guard Target diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/variables.tf index ce91ee2c8..879b48033 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/cloud-guard-target/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Security ## Create Cloud Guard Target diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/data.tf index 12fa5c62d..c96b8e4cf 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/data.tf @@ -1,3 +1,7 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# + /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/main.tf index d2e61a439..a22af5cb4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_address_list" "network_firewall_policy_address_list" { name = var.address_list_name network_firewall_policy_id = var.network_firewall_policy_id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/output.tf index 95c6fb0b6..2c18d09a7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "address_tf_id" { value = oci_network_firewall_network_firewall_policy_address_list.network_firewall_policy_address_list.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/variable.tf index eb7642317..e4c22c9b7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/address-list/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/data.tf index 12fa5c62d..84adb07b0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/main.tf index 51537bbb6..818d9d3d6 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_application_group" "network_firewall_policy_application_group" { #Required apps = var.apps diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/output.tf index 77d7cf03d..8ee1e5007 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "application_group_tf_id" { value = oci_network_firewall_network_firewall_policy_application_group.network_firewall_policy_application_group.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/variable.tf index 1d45ba563..7b27c2d8c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application-group/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/data.tf index 12fa5c62d..c96b8e4cf 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/data.tf @@ -1,3 +1,7 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# + /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/main.tf index 30727d2a8..f12da7418 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/main.tf @@ -1,3 +1,7 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# + resource "oci_network_firewall_network_firewall_policy_application" "network_firewall_policy_application" { #Required icmp_type = var.icmp_type diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/output.tf index 41b2674b2..8815064ee 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "application_tf_id" { value = oci_network_firewall_network_firewall_policy_application.network_firewall_policy_application.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/variable.tf index b15202365..70038b794 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/application/variable.tf @@ -1,4 +1,6 @@ - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/data.tf index 12fa5c62d..84adb07b0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/main.tf index a45aa3b3b..5ea06de6a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_decryption_profile" "network_firewall_policy_decryption_profile" { #Required name = var.profile_name diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/output.tf index 368e1abb2..3c4dc8c22 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "decrypt_profile_tf_id" { value = oci_network_firewall_network_firewall_policy_decryption_profile.network_firewall_policy_decryption_profile.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/variable.tf index ffc947420..d276adfb4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-profile/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/data.tf index 12fa5c62d..84adb07b0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/main.tf index 1d27a890a..21907bf91 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_decryption_rule" "network_firewall_policy_decryption_rule" { lifecycle { ignore_changes = [position] diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/output.tf index ab1ef8232..37b6bac46 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "decrypt_rules_tf_id" { value = oci_network_firewall_network_firewall_policy_decryption_rule.network_firewall_policy_decryption_rule.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/variable.tf index e1e4ef3a3..c2c39971c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/decryption-rules/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/main.tf index ba7771d23..26080e053 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy" "network_firewall_policy" { compartment_id = var.compartment_id display_name = var.display_name diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/output.tf index e7be38d6d..8d29874a0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "policy_tf_id" { value = oci_network_firewall_network_firewall_policy.network_firewall_policy.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/variable.tf index 8d7759010..5c1090559 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall-policy/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/data.tf index 68978ed4b..f08704ff4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# data "oci_core_vcns" "firewall_vcn" { compartment_id = var.compartment_id != null ? var.compartment_id : var.compartment_id display_name = var.vcn_name != null ? var.vcn_name : var.vcn_name diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/main.tf index bdddd67c0..ebfd7ba4e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall" "network_firewall" { compartment_id = var.compartment_id network_firewall_policy_id = var.network_firewall_policy_id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/output.tf index f0c342847..28bbf2120 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "firewall_tf_id" { value = oci_network_firewall_network_firewall.network_firewall.id } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/variable.tf index a7a9b50f0..602ee82ea 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/firewall/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/data.tf index ab898fd7b..272cd2a8b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# data "oci_kms_vaults" "fw_vault" { compartment_id = var.compartment_id != null ? var.compartment_id : var.compartment_id filter { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/main.tf index f45c5be94..8744045b2 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_mapped_secret" "network_firewall_policy_mapped_secret" { #Required name = var.secret_name diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/output.tf index a2fdd82ce..88965265a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "secret_tf_id" { value = oci_network_firewall_network_firewall_policy_mapped_secret.network_firewall_policy_mapped_secret.id } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/variable.tf index c555f9753..8e2cc4ec4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/secret/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/data.tf index 12fa5c62d..84adb07b0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/main.tf index 31902d6c0..80c98920c 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_security_rule" "network_firewall_policy_security_rule" { lifecycle { ignore_changes = [position] diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/output.tf index 40b4b4ee4..accc3767e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "secrules_tf_id" { value = oci_network_firewall_network_firewall_policy_security_rule.network_firewall_policy_security_rule.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/variable.tf index b759c5fbf..97bca7440 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/security-rules/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/data.tf index a68341946..1a2c14ea7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /* locals { services = var.services != null ? flatten(tolist([for sid in var.services : (length(regexall("ocid1.networkfirewallpolicy.oc*", sid)) > 0 ? [sid] : data.oci_network_firewall_network_firewall_policy_services.fw-services[sid].*.name)])) : null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/main.tf index d46283087..b993571af 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_service_list" "network_firewall_policy_service_list" { name = var.service_list_name network_firewall_policy_id = var.network_firewall_policy_id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/output.tf index 9a04cbbf4..f1a063863 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "service-list_tf_id" { value = oci_network_firewall_network_firewall_policy_service_list.network_firewall_policy_service_list.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/variable.tf index f65b569a1..9dbb07890 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service-list/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/data.tf index 12fa5c62d..84adb07b0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/main.tf index 8344d4b56..657c44210 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_service" "network_firewall_policy_service" { name = var.service_name network_firewall_policy_id = var.network_firewall_policy_id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/output.tf index c38136fd8..b562e93e3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "service_tf_id" { value = oci_network_firewall_network_firewall_policy_service.network_firewall_policy_service.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/variable.tf index 5c5a81467..ddb8513f7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/service/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/data.tf index 12fa5c62d..84adb07b0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# /*locals { policy_ocid = data.oci_network_firewall_network_firewall_policies.fw-policy.network_firewall_policy_summary_collection[*].id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/main.tf index cf567b421..389e3dad4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/main.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# resource "oci_network_firewall_network_firewall_policy_url_list" "network_firewall_policy_url_list" { name = var.urllist_name network_firewall_policy_id = var.network_firewall_policy_id diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/output.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/output.tf index 3fd27e55c..582c004c3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/output.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/output.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# output "url_tf_id" { value = oci_network_firewall_network_firewall_policy_url_list.network_firewall_policy_url_list.id } \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/variable.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/variable.tf index fc19daba0..2cc455ee4 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/variable.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/firewall/url-list/variable.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# variable "compartment_id" { type = string default = null diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/main.tf index 0dfecb00e..cab5263bb 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Security ## Create Key diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/outputs.tf index 82cfbd999..b2db28c8d 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Security ## Create Key diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/variables.tf index 402458ff3..61e039d4f 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/key/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Security ## Create Key diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/main.tf index bce4c2eba..426e477e7 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Security ## Create Vault diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/outputs.tf index d724ebb85..387dd64f2 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Security ## Create Vault diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/variables.tf index d7a1ff879..cb5d4fdf5 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/security/vault/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Security ## Create Vault diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/data.tf index 6c3cd8445..308445be9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Data Block - Block Volume ## Create Block Volume and Block Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/main.tf index 9e0622da1..4a9e26ec7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Block Volume ## Create Block Volume diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/outputs.tf index 8db484811..cbb156d6f 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Block Volume ## Create Block Volume and Block Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/variables.tf index 085500ff0..5374df283 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/block-volume/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Block Volume ## Create Block Volume and Block Volume Backup Policy diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/main.tf index c9601b14a..299758867 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Storage # Create Export Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/outputs.tf index a7baa5742..1e860a953 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Storage # Create Export Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/variables.tf index 6b5ab792c..94dbffbe6 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/export-option/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Storage # Create Export Options diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/main.tf index dbf9487d9..d7b733c57 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Storage # Create FSS Replication diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/outputs.tf index b1aa0f3c0..816961a67 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Storage # Create FSS Replication diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/variables.tf index 1bf4d7e70..f500bc280 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss-replication/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Storage # Create FSS Replication diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/data.tf index 0cf9aa829..a39d4d252 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/data.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# data "oci_file_storage_filesystem_snapshot_policies" "filesystem_snapshot_policies" { #Required count = var.filesystem_snapshot_policy_id != null ? 1 : 0 diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/main.tf index 695fbf4a6..e01f6d4c7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Storage # Create FSS @@ -17,7 +18,5 @@ resource "oci_file_storage_file_system" "file_system" { kms_key_id = var.kms_key_id source_snapshot_id = var.source_snapshot_id filesystem_snapshot_policy_id = var.filesystem_snapshot_policy_id != null ? (length(regexall("ocid1.filesystemsnapshotpolicy.oc*", var.filesystem_snapshot_policy_id)) > 0 ? var.filesystem_snapshot_policy_id : data.oci_file_storage_filesystem_snapshot_policies.filesystem_snapshot_policies[0].filesystem_snapshot_policies[0].id) : null - lifecycle { - ignore_changes = [source_snapshot_id] - } + } diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/outputs.tf index afbd0f265..339f0ec47 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Storage # Create FSS diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/variables.tf index 90dd950ae..b1dab2b4b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/fss/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Storage # Create FSS diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/data.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/data.tf index 97d467587..4e666441a 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# ## Data Block - Storage ## Create MT diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/main.tf index 6aef590e1..444c734f2 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Storage # Create MTs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/outputs.tf index 264b035fa..e4fb51aea 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Output Block - Storage # Create MTs diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/variables.tf index 16032ac1b..697bf75be 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/file-storage/mount-target/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Variable Block - Storage # Create MTs @@ -63,4 +64,7 @@ variable "vcn_names" { default = [] } -variable "network_compartment_id" {} \ No newline at end of file +variable "network_compartment_id" { + type = string + default = null +} \ No newline at end of file diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/main.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/main.tf index 5048dcc8e..c4e9ad776 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/main.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/main.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Resource Block - Object Storage ## Create Object Storage diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/oracle_provider_req.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/oracle_provider_req.tf index e52742e05..f1f97aaeb 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/oracle_provider_req.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/oracle_provider_req.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# terraform { required_providers { oci = { diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/outputs.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/outputs.tf index 2af878e22..b16b6cfb9 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/outputs.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/outputs.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ ## Outputs Block - Object Storage ## Create Object Storage diff --git a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/variables.tf b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/variables.tf index 4c418d2d2..fdc72b72b 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/variables.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/modules/storage/object-storage/variables.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################# ## Variables Block - Object Storage ## Create Object Storage diff --git a/cd3_automation_toolkit/user-scripts/terraform/network.tf b/cd3_automation_toolkit/user-scripts/terraform/network.tf index c1ba6e280..890d153e7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/network.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/network.tf @@ -1,13 +1,15 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ################################ # Data Block - Network # DRG Route Rules and DRG Route Distributions ################################ locals { - all_route_tables = merge(var.route_tables,var.default_route_tables) - all_seclists = merge(var.seclists,var.default_seclists) + all_route_tables = merge(var.route_tables, var.default_route_tables) + all_seclists = merge(var.seclists, var.default_seclists) + gateway_rt_status = { for k, v in local.all_route_tables : k => (v.gateway_route_table == null ? false : v.gateway_route_table) } } @@ -84,11 +86,11 @@ module "igws" { vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] #Optional - enabled = each.value.enable_igw # Defaults to true by terraform hashicorp - defined_tags = each.value.defined_tags - display_name = each.value.igw_name != null ? each.value.igw_name : null - freeform_tags = each.value.freeform_tags - route_table_id = (each.value.route_table_id != "" && each.value.route_table_id != null) ? (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(module.gateway-route-tables.*...)[each.value.route_table_id]["route_table_ids"]) : null + enabled = each.value.enable_igw # Defaults to true by terraform hashicorp + defined_tags = each.value.defined_tags + display_name = each.value.igw_name != null ? each.value.igw_name : null + freeform_tags = each.value.freeform_tags + route_table_id = (each.value.route_table_id != "" && each.value.route_table_id != null) ? (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(module.gateway-route-tables.*...)[each.value.route_table_id]["route_table_ids"]) : null } @@ -114,9 +116,9 @@ module "ngws" { vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] #Optional - block_traffic = each.value.block_traffic # Defaults to false by terraform hashicorp - public_ip_id = each.value.public_ip_id - route_table_id = (each.value.route_table_id != "" && each.value.route_table_id != null) ? (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(module.gateway-route-tables.*...)[each.value.route_table_id]["route_table_ids"]) : null + block_traffic = each.value.block_traffic # Defaults to false by terraform hashicorp + public_ip_id = each.value.public_ip_id + route_table_id = (each.value.route_table_id != "" && each.value.route_table_id != null) ? (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(module.gateway-route-tables.*...)[each.value.route_table_id]["route_table_ids"]) : null defined_tags = each.value.defined_tags display_name = each.value.ngw_name @@ -143,11 +145,11 @@ module "sgws" { vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] #Optional - defined_tags = each.value.defined_tags - display_name = each.value.sgw_name != null ? each.value.sgw_name : null - freeform_tags = each.value.freeform_tags - service = each.value.service != "" ? (contains(split("-", each.value.service), "all") == true ? "all" : "objectstorage") : "all" - route_table_id = (each.value.route_table_id != "" && each.value.route_table_id != null) ? (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(module.gateway-route-tables.*...)[each.value.route_table_id]["route_table_ids"]) : null + defined_tags = each.value.defined_tags + display_name = each.value.sgw_name != null ? each.value.sgw_name : null + freeform_tags = each.value.freeform_tags + service = each.value.service != "" ? (contains(split("-", each.value.service), "all") == true ? "all" : "objectstorage") : "all" + route_table_id = (each.value.route_table_id != "" && each.value.route_table_id != null) ? (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(module.gateway-route-tables.*...)[each.value.route_table_id]["route_table_ids"]) : null } /* @@ -299,16 +301,16 @@ module "drg-attachments" { source = "./modules/network/drg-attachment" for_each = (var.drg_attachments != null || var.drg_attachments != {}) ? var.drg_attachments : {} - drg_display_name = each.value.display_name - defined_tags = each.value.defined_tags - freeform_tags = each.value.freeform_tags - drg_id = length(regexall("ocid1.drg.oc*", each.value.drg_id)) > 0 ? each.value.drg_id : ((each.value.drg_id != "" && each.value.drg_id != null) ? merge(module.drgs.*...)[each.value.drg_id]["drg_tf_id"] : each.value.drg_id) - drg_route_table_id = length(regexall("ocid1.drgroutetable.oc*", each.value.drg_route_table_id)) > 0 ? each.value.drg_route_table_id : ((each.value.drg_route_table_id != "" && each.value.drg_route_table_id != null) ? merge(module.drg-route-tables.*...)[each.value.drg_route_table_id]["drg_route_table_tf_id"] : null) - vcns_tf_id = merge(module.vcns.*...) - route_table_tf_id = merge(module.route-tables.*...) + drg_display_name = each.value.display_name + defined_tags = each.value.defined_tags + freeform_tags = each.value.freeform_tags + drg_id = length(regexall("ocid1.drg.oc*", each.value.drg_id)) > 0 ? each.value.drg_id : ((each.value.drg_id != "" && each.value.drg_id != null) ? merge(module.drgs.*...)[each.value.drg_id]["drg_tf_id"] : each.value.drg_id) + drg_route_table_id = length(regexall("ocid1.drgroutetable.oc*", each.value.drg_route_table_id)) > 0 ? each.value.drg_route_table_id : ((each.value.drg_route_table_id != "" && each.value.drg_route_table_id != null) ? merge(module.drg-route-tables.*...)[each.value.drg_route_table_id]["drg_route_table_tf_id"] : null) + vcns_tf_id = merge(module.vcns.*...) + route_table_tf_id = merge(module.route-tables.*...) #default_route_table_tf_id = merge(module.default-route-tables.*...) - drg_attachments = var.drg_attachments - key_name = each.key + drg_attachments = var.drg_attachments + key_name = each.key } @@ -403,9 +405,9 @@ module "security-lists" { #Required compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null - vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] + vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] manage_default_resource_id = merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_security_list_id"] - default_seclist = var.default_seclists != {} ? contains(keys(var.default_seclists), each.key) ? true : false : false + default_seclist = var.default_seclists != {} ? contains(keys(var.default_seclists), each.key) ? true : false : false key_name = each.key defined_tags = each.value.defined_tags @@ -426,14 +428,15 @@ output "seclist_id_map" { ############################ module "route-tables" { - source = "./modules/network/route-table" - for_each = {for k,v in local.all_route_tables : k => v if ! v.gateway_route_table} + source = "./modules/network/route-table" + #for_each = {for k,v in local.all_route_tables : k => v if ! v.gateway_route_table} + for_each = { for k, v in local.all_route_tables : k => v if !local.gateway_rt_status[k] } #Required compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] - default_route_table = var.default_route_tables != {} ? contains(keys(var.default_route_tables), each.key) ? true : false : false + default_route_table = var.default_route_tables != {} ? contains(keys(var.default_route_tables), each.key) ? true : false : false manage_default_resource_id = merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_route_table_id"] #Optional @@ -455,22 +458,23 @@ module "route-tables" { module "gateway-route-tables" { - source = "./modules/network/route-table" - for_each = {for k,v in local.all_route_tables : k => v if v.gateway_route_table } + source = "./modules/network/route-table" + #for_each = {for k,v in local.all_route_tables : k => v if v.gateway_route_table } + for_each = { for k, v in local.all_route_tables : k => v if local.gateway_rt_status[k] } #Required compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null vcn_id = length(regexall("ocid1.vcn.oc*", each.value.vcn_id)) > 0 ? each.value.vcn_id : merge(module.vcns.*...)[each.value.vcn_id]["vcn_tf_id"] - default_route_table = var.default_route_tables != {} ? contains(keys(var.default_route_tables), each.key) ? true : false : false + default_route_table = var.default_route_tables != {} ? contains(keys(var.default_route_tables), each.key) ? true : false : false manage_default_resource_id = merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_route_table_id"] #Optional - defined_tags = each.value.defined_tags - display_name = each.value.display_name != null ? each.value.display_name : null - freeform_tags = each.value.freeform_tags - key_name = each.key - drg_id = merge(module.drgs.*...) - rt_details = local.all_route_tables + defined_tags = each.value.defined_tags + display_name = each.value.display_name != null ? each.value.display_name : null + freeform_tags = each.value.freeform_tags + key_name = each.key + drg_id = merge(module.drgs.*...) + rt_details = local.all_route_tables gateway_route_table = each.value.gateway_route_table } @@ -601,17 +605,17 @@ module "subnets" { cidr_block = each.value.cidr_block #Optional - dns_label = each.value.dns_label - ipv6cidr_block = each.value.ipv6cidr_block - defined_tags = each.value.defined_tags - display_name = each.value.display_name - freeform_tags = each.value.freeform_tags - prohibit_internet_ingress = each.value.prohibit_internet_ingress - prohibit_public_ip_on_vnic = each.value.prohibit_public_ip_on_vnic - availability_domain = each.value.availability_domain != "" && each.value.availability_domain != null ? data.oci_identity_availability_domains.availability_domains.availability_domains[each.value.availability_domain].name : "" - dhcp_options_id = each.value.dhcp_options_id == null || each.value.dhcp_options_id == "" ? merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_dhcp_id"] : (length(regexall("ocid1.dhcpoptions.oc*", each.value.dhcp_options_id)) > 0 ? each.value.dhcp_options_id : merge(module.custom-dhcps.*...)[each.value.dhcp_options_id]["custom_dhcp_tf_id"]) + dns_label = each.value.dns_label + ipv6cidr_block = each.value.ipv6cidr_block + defined_tags = each.value.defined_tags + display_name = each.value.display_name + freeform_tags = each.value.freeform_tags + prohibit_internet_ingress = each.value.prohibit_internet_ingress + prohibit_public_ip_on_vnic = each.value.prohibit_public_ip_on_vnic + availability_domain = each.value.availability_domain != "" && each.value.availability_domain != null ? data.oci_identity_availability_domains.availability_domains.availability_domains[each.value.availability_domain].name : "" + dhcp_options_id = each.value.dhcp_options_id == null || each.value.dhcp_options_id == "" ? merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_dhcp_id"] : (length(regexall("ocid1.dhcpoptions.oc*", each.value.dhcp_options_id)) > 0 ? each.value.dhcp_options_id : merge(module.custom-dhcps.*...)[each.value.dhcp_options_id]["custom_dhcp_tf_id"]) #route_table_id = each.value.route_table_id == null || each.value.route_table_id == "" ? merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_route_table_id"] : (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : contains(keys(merge(module.gateway-route-tables.*...)), each.value.route_table_id) ? merge(module.gateway-route-tables.*...)[each.value.route_table_id] ["route_table_ids"] : merge(module.route-tables.*...)[each.value.route_table_id]["route_table_ids"]) - route_table_id = each.value.route_table_id == null || each.value.route_table_id == "" ? merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_route_table_id"] : (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(merge(module.gateway-route-tables.*...),merge(module.route-tables.*...))[each.value.route_table_id]["route_table_ids"]) + route_table_id = each.value.route_table_id == null || each.value.route_table_id == "" ? merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_route_table_id"] : (length(regexall("ocid1.routetable.oc*", each.value.route_table_id)) > 0 ? each.value.route_table_id : merge(merge(module.gateway-route-tables.*...), merge(module.route-tables.*...))[each.value.route_table_id]["route_table_ids"]) security_list_ids = length(each.value.security_list_ids) == 0 ? [merge(module.vcns.*...)[each.value.vcn_id]["vcn_default_security_list_id"]] : each.value.security_list_ids @@ -653,8 +657,8 @@ output "vcn_log_group_map" { */ module "vcn-logs" { - source = "./modules/managementservices/log" - for_each = (var.vcn_logs != null || var.vcn_logs != {}) ? var.vcn_logs : {} + source = "./modules/managementservices/log" + for_each = (var.vcn_logs != null || var.vcn_logs != {}) ? var.vcn_logs : {} # Logs #Required diff --git a/cd3_automation_toolkit/user-scripts/terraform/networkloadbalancer.tf b/cd3_automation_toolkit/user-scripts/terraform/networkloadbalancer.tf index dedd1ece4..e027d13d0 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/networkloadbalancer.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/networkloadbalancer.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Module Block - Network Load Balancer # Create Network Load Balancer @@ -60,11 +61,11 @@ module "nlb-backend-sets" { ip_version = each.value.ip_version is_preserve_source = each.value.is_preserve_source #healthcheck parameters - domain_name = each.value.domain_name - query_class = each.value.query_class - query_type = each.value.query_type - rcodes = each.value.rcodes - transport_protocol = each.value.transport_protocol + domain_name = each.value.domain_name + query_class = each.value.query_class + query_type = each.value.query_type + rcodes = each.value.rcodes + transport_protocol = each.value.transport_protocol protocol = each.value.protocol interval_in_millis = each.value.interval_in_millis @@ -79,7 +80,7 @@ module "nlb-backend-sets" { } module "nlb-backends" { - source = "./modules/networkloadbalancer/nlb-backend" + source = "./modules/networkloadbalancer/nlb-backend" # depends_on = [module.instances] # Uncomment to create Network and NLBs together for_each = var.nlb_backends != null ? var.nlb_backends : {} backend_set_name = merge(module.nlb-backend-sets.*...)[each.value.backend_set_name]["nlb_backend_set_tf_name"] diff --git a/cd3_automation_toolkit/user-scripts/terraform/nsg.tf b/cd3_automation_toolkit/user-scripts/terraform/nsg.tf index 41bf93cc0..b9554b7c8 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/nsg.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/nsg.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################# # Module Block - Network # Create Network Security Groups diff --git a/cd3_automation_toolkit/user-scripts/terraform/object-storage.tf b/cd3_automation_toolkit/user-scripts/terraform/object-storage.tf index c315380eb..915e9c379 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/object-storage.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/object-storage.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Object Storage # Create Object Storage Policies @@ -100,8 +101,8 @@ output "oss_log_group_map" { */ module "oss-logs" { - source = "./modules/managementservices/log" - for_each = var.oss_logs != null ? var.oss_logs : {} + source = "./modules/managementservices/log" + for_each = var.oss_logs != null ? var.oss_logs : {} # Logs #Required diff --git a/cd3_automation_toolkit/user-scripts/terraform/oci-data.tf b/cd3_automation_toolkit/user-scripts/terraform/oci-data.tf index 149570768..bc2bbfbe3 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/oci-data.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/oci-data.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Resource Block - Identity # Fetch Compartments diff --git a/cd3_automation_toolkit/user-scripts/terraform/oke.tf b/cd3_automation_toolkit/user-scripts/terraform/oke.tf index 869298049..ba077dae7 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/oke.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/oke.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Module Block - OKE # Create OKE clusters and Nodepools @@ -135,26 +136,26 @@ module "nodepools" { } module "virtual-nodepools" { - source = "./modules/oke/virtual-nodepool" - for_each = var.virtual-nodepools - tenancy_ocid = var.tenancy_ocid - display_name = each.value.display_name - availability_domain = each.value.availability_domain - fault_domains = each.value.fault_domains - cluster_name = length(regexall("ocid1.cluster.oc*", each.value.cluster_name)) > 0 ? each.value.cluster_name : merge(module.clusters.*...)[each.value.cluster_name]["cluster_tf_id"] - compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null - network_compartment_id = each.value.network_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.network_compartment_id)) > 0 ? each.value.network_compartment_id : var.compartment_ocids[each.value.network_compartment_id]) : null - vcn_names = [each.value.vcn_name] - node_shape = each.value.node_shape - initial_virtual_node_labels = each.value.initial_virtual_node_labels - taints = each.value.taints - subnet_id = length(regexall("ocid1.subnet.oc*", each.value.subnet_id)) > 0 ? each.value.subnet_id : data.oci_core_subnets.oci_subnets_virtual_worker[each.key].subnets.*.id[0] - size = each.value.size - pod_nsg_ids = each.value.pod_nsg_ids - pod_subnet_id = (length(regexall("ocid1.subnet.oc*", each.value.pod_subnet_id)) > 0 ? each.value.pod_subnet_id : data.oci_core_subnets.oci_subnets_virtual_pod[each.key].subnets.*.id[0]) - worker_nsg_ids = each.value.worker_nsg_ids - node_defined_tags = each.value.node_defined_tags - node_freeform_tags = each.value.node_freeform_tags - nodepool_defined_tags = each.value.nodepool_defined_tags - nodepool_freeform_tags = each.value.nodepool_freeform_tags + source = "./modules/oke/virtual-nodepool" + for_each = var.virtual-nodepools + tenancy_ocid = var.tenancy_ocid + display_name = each.value.display_name + availability_domain = each.value.availability_domain + fault_domains = each.value.fault_domains + cluster_name = length(regexall("ocid1.cluster.oc*", each.value.cluster_name)) > 0 ? each.value.cluster_name : merge(module.clusters.*...)[each.value.cluster_name]["cluster_tf_id"] + compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null + network_compartment_id = each.value.network_compartment_id != null ? (length(regexall("ocid1.compartment.oc*", each.value.network_compartment_id)) > 0 ? each.value.network_compartment_id : var.compartment_ocids[each.value.network_compartment_id]) : null + vcn_names = [each.value.vcn_name] + node_shape = each.value.node_shape + initial_virtual_node_labels = each.value.initial_virtual_node_labels + taints = each.value.taints + subnet_id = length(regexall("ocid1.subnet.oc*", each.value.subnet_id)) > 0 ? each.value.subnet_id : data.oci_core_subnets.oci_subnets_virtual_worker[each.key].subnets.*.id[0] + size = each.value.size + pod_nsg_ids = each.value.pod_nsg_ids + pod_subnet_id = (length(regexall("ocid1.subnet.oc*", each.value.pod_subnet_id)) > 0 ? each.value.pod_subnet_id : data.oci_core_subnets.oci_subnets_virtual_pod[each.key].subnets.*.id[0]) + worker_nsg_ids = each.value.worker_nsg_ids + node_defined_tags = each.value.node_defined_tags + node_freeform_tags = each.value.node_freeform_tags + nodepool_defined_tags = each.value.nodepool_defined_tags + nodepool_freeform_tags = each.value.nodepool_freeform_tags } diff --git a/cd3_automation_toolkit/user-scripts/terraform/provider.tf b/cd3_automation_toolkit/user-scripts/terraform/provider.tf index 9a69c981b..3a75cbc5e 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/provider.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/provider.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Provider Block # OCI @@ -17,8 +18,8 @@ provider "oci" { terraform { required_providers { oci = { - source = "oracle/oci" - version = "5.40.0" + source = "oracle/oci" + version = "6.3.0" } } } diff --git a/cd3_automation_toolkit/user-scripts/terraform/quota.tf b/cd3_automation_toolkit/user-scripts/terraform/quota.tf index a9227e9e2..8f064a684 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/quota.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/quota.tf @@ -1,17 +1,18 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ####################################### # Module Block - QUOTA POLICIES # Create Quota policies ####################################### module "quota_policies" { - source = "./modules/governance/quota-policy" - for_each = var.quota_policies - tenancy_ocid = var.tenancy_ocid - quota_description = each.value.quota_description - quota_name = each.value.quota_name - quota_statements = each.value.quota_statements - defined_tags = each.value.defined_tags - freeform_tags = each.value.freeform_tags + source = "./modules/governance/quota-policy" + for_each = var.quota_policies + tenancy_ocid = var.tenancy_ocid + quota_description = each.value.quota_description + quota_name = each.value.quota_name + quota_statements = each.value.quota_statements + defined_tags = each.value.defined_tags + freeform_tags = each.value.freeform_tags } diff --git a/cd3_automation_toolkit/user-scripts/terraform/sddc.tf b/cd3_automation_toolkit/user-scripts/terraform/sddc.tf index c052d46bc..11fbc5e1b 100755 --- a/cd3_automation_toolkit/user-scripts/terraform/sddc.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/sddc.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################ # Module Block SDDC # Create SDDC @@ -14,38 +17,38 @@ locals { } ]]) - ds_vols = flatten([ for key, val in var.sddcs : [ - for item in concat(local.mgmt_vols[val.display_name],local.wkld_vols[val.display_name]): { - volume_display_name = item.volume_display_name - volume_compartment_id = item.volume_compartment_id - } + ds_vols = flatten([for key, val in var.sddcs : [ + for item in concat(local.mgmt_vols[val.display_name], local.wkld_vols[val.display_name]) : { + volume_display_name = item.volume_display_name + volume_compartment_id = item.volume_compartment_id + } ]]) mgmt_vols = { for key, val in var.sddcs : - val.display_name => try([for item in val.management_datastore: { - volume_compartment_id = try(split("@", item)[0],null) - volume_display_name = try(split("@", item)[1],null) - }],[])} + val.display_name => try([for item in val.management_datastore : { + volume_compartment_id = try(split("@", item)[0], null) + volume_display_name = try(split("@", item)[1], null) + }], []) } wkld_vols = { for key, val in var.sddcs : - val.display_name => try([ for item in val.workload_datastore: - { - volume_compartment_id = try(split("@", item)[0],null) - volume_display_name = try(split("@", item)[1],null) - }] ,[])} + val.display_name => try([for item in val.workload_datastore : + { + volume_compartment_id = try(split("@", item)[0], null) + volume_display_name = try(split("@", item)[1], null) + }], []) } - management_datastores = { for key,val in var.sddcs : key => (val.management_datastore != null ? [for value in val.management_datastore: data.oci_core_volumes.ds_volumes[split("@", value)[1]].volumes.*.id[0]] : []) + management_datastores = { for key, val in var.sddcs : key => (val.management_datastore != null ? [for value in val.management_datastore : data.oci_core_volumes.ds_volumes[split("@", value)[1]].volumes.*.id[0]] : []) } - workload_datastores = {for key,val in var.sddcs: key => (val.workload_datastore != null ? [for value in val.workload_datastore: data.oci_core_volumes.ds_volumes[split("@", value)[1]].volumes.*.id[0]] : []) - } - } + workload_datastores = { for key, val in var.sddcs : key => (val.workload_datastore != null ? [for value in val.workload_datastore : data.oci_core_volumes.ds_volumes[split("@", value)[1]].volumes.*.id[0]] : []) + } +} data "oci_core_volumes" "ds_volumes" { - for_each = {for value in local.ds_vols : value.volume_display_name => value.volume_compartment_id if value.volume_display_name != null } - compartment_id = each.value != null ? (length(regexall("ocid1.compartment.oc1*", each.value)) > 0 ? each.value : var.compartment_ocids[each.value]) : var.compartment_ocids[each.value] - display_name = each.key - state = "AVAILABLE" + for_each = { for value in local.ds_vols : value.volume_display_name => value.volume_compartment_id if value.volume_display_name != null } + compartment_id = each.value != null ? (length(regexall("ocid1.compartment.oc1*", each.value)) > 0 ? each.value : var.compartment_ocids[each.value]) : var.compartment_ocids[each.value] + display_name = each.key + state = "AVAILABLE" } @@ -66,7 +69,7 @@ data "oci_core_subnets" "oci_subnets_sddc" { data "oci_core_vlans" "sddc_vlan_id" { #Required - for_each = { for vlan in local.vlan_config : vlan.display_name => vlan if vlan.display_name != null} + for_each = { for vlan in local.vlan_config : vlan.display_name => vlan if vlan.display_name != null } compartment_id = each.value.compartment_id display_name = each.key vcn_id = each.value.vcn_id @@ -95,7 +98,7 @@ module "sddcs" { initial_host_shape_name = each.value.initial_host_shape_name != "" ? each.value.initial_host_shape_name : null capacity_reservation_id = each.value.capacity_reservation_id != "" ? each.value.capacity_reservation_id : null initial_cluster_display_name = each.value.initial_cluster_display_name != "" ? each.value.initial_cluster_display_name : null #new addition - display_name = each.value.display_name != "" ? each.value.display_name : null #edited + display_name = each.value.display_name != "" ? each.value.display_name : null #edited defined_tags = each.value.defined_tags != {} ? each.value.defined_tags : {} freeform_tags = each.value.freeform_tags != {} ? each.value.freeform_tags : {} hcx_action = each.value.hcx_action != "" ? each.value.hcx_action : null @@ -121,7 +124,7 @@ module "sddcs" { ############################################ locals { - vlan_ids_sddc_cluster = ["nsx_edge_uplink1vlan_id", "nsx_edge_uplink2vlan_id","nsx_edge_vtep_vlan_id", "nsx_vtep_vlan_id", "vmotion_vlan_id", "vsan_vlan_id", "vsphere_vlan_id", "replication_vlan_id", "provisioning_vlan_id", "hcx_vlan_id"] + vlan_ids_sddc_cluster = ["nsx_edge_uplink1vlan_id", "nsx_edge_uplink2vlan_id", "nsx_edge_vtep_vlan_id", "nsx_vtep_vlan_id", "vmotion_vlan_id", "vsan_vlan_id", "vsphere_vlan_id", "replication_vlan_id", "provisioning_vlan_id", "hcx_vlan_id"] vlan_config_sddc_cluster = flatten([for index in local.vlan_ids_sddc_cluster : [ for key, val in var.sddc-clusters : { #(index) = lookup(val, index, 0) @@ -143,31 +146,31 @@ locals { deduplicated_vlan_list = values(local.deduplicated_vlan_config) - ds_vols_sddc_cluster = flatten([ for key, val in var.sddc-clusters : [ - #for item in concat(local.mgmt_vols_sddc_cluster[val.display_name],local.wkld_vols_sddc_cluster[val.display_name]): { - for item in local.wkld_vols_sddc_cluster[val.display_name]: { - volume_display_name = item.volume_display_name - volume_compartment_id = item.volume_compartment_id - } + ds_vols_sddc_cluster = flatten([for key, val in var.sddc-clusters : [ + #for item in concat(local.mgmt_vols_sddc_cluster[val.display_name],local.wkld_vols_sddc_cluster[val.display_name]): { + for item in local.wkld_vols_sddc_cluster[val.display_name] : { + volume_display_name = item.volume_display_name + volume_compartment_id = item.volume_compartment_id + } ]]) wkld_vols_sddc_cluster = { for key, val in var.sddc-clusters : - val.display_name => try([ for item in val.workload_datastore: - { - volume_compartment_id = try(split("@", item)[0],null) - volume_display_name = try(split("@", item)[1],null) - }] ,[])} + val.display_name => try([for item in val.workload_datastore : + { + volume_compartment_id = try(split("@", item)[0], null) + volume_display_name = try(split("@", item)[1], null) + }], []) } - workload_datastores_sddc_cluster = {for key,val in var.sddc-clusters: key => (val.workload_datastore != null ? [for value in val.workload_datastore: data.oci_core_volumes.ds_volumes_sddc_cluster[split("@", value)[1]].volumes.*.id[0]] : []) - } - } + workload_datastores_sddc_cluster = { for key, val in var.sddc-clusters : key => (val.workload_datastore != null ? [for value in val.workload_datastore : data.oci_core_volumes.ds_volumes_sddc_cluster[split("@", value)[1]].volumes.*.id[0]] : []) + } +} data "oci_core_volumes" "ds_volumes_sddc_cluster" { - for_each = {for value in local.ds_vols_sddc_cluster : value.volume_display_name => value.volume_compartment_id if value.volume_display_name != null } - compartment_id = each.value != null ? (length(regexall("ocid1.compartment.oc1*", each.value)) > 0 ? each.value : var.compartment_ocids[each.value]) : var.compartment_ocids[each.value] - display_name = each.key - state = "AVAILABLE" + for_each = { for value in local.ds_vols_sddc_cluster : value.volume_display_name => value.volume_compartment_id if value.volume_display_name != null } + compartment_id = each.value != null ? (length(regexall("ocid1.compartment.oc1*", each.value)) > 0 ? each.value : var.compartment_ocids[each.value]) : var.compartment_ocids[each.value] + display_name = each.key + state = "AVAILABLE" } @@ -189,18 +192,18 @@ data "oci_core_subnets" "oci_subnets_sddc_cluster" { data "oci_core_vlans" "sddc_cluster_vlan_id" { #depends_on = [module.vlans] #Required - for_each = { for vlan in local.deduplicated_vlan_list: vlan.display_name => vlan if vlan.display_name != null} + for_each = { for vlan in local.deduplicated_vlan_list : vlan.display_name => vlan if vlan.display_name != null } compartment_id = each.value.compartment_id display_name = each.key vcn_id = each.value.vcn_id } data "oci_ocvp_sddcs" "oci_sddcs" { - depends_on = [module.sddcs] - for_each = var.sddc-clusters != null ? var.sddc-clusters : {} - compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc1*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null - display_name = each.value.sddc_id - state = "ACTIVE" + depends_on = [module.sddcs] + for_each = var.sddc-clusters != null ? var.sddc-clusters : {} + compartment_id = each.value.compartment_id != null ? (length(regexall("ocid1.compartment.oc1*", each.value.compartment_id)) > 0 ? each.value.compartment_id : var.compartment_ocids[each.value.compartment_id]) : null + display_name = each.value.sddc_id + state = "ACTIVE" } module "sddc-clusters" { diff --git a/cd3_automation_toolkit/user-scripts/terraform/tagging.tf b/cd3_automation_toolkit/user-scripts/terraform/tagging.tf index 6e5008092..d60a7ebbf 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/tagging.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/tagging.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # Module Block - Storage # Create Tag Namespaces, Tag Keys and Default Tags diff --git a/cd3_automation_toolkit/user-scripts/terraform/variables_example.tf b/cd3_automation_toolkit/user-scripts/terraform/variables_example.tf index fae17eaf4..051b05172 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/variables_example.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/variables_example.tf @@ -1,5 +1,6 @@ -// Copyright (c) 2021, 2022, Oracle and/or its affiliates. - +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################ # # Variables Block @@ -250,6 +251,7 @@ variable "groups" { type = map(object({ group_name = string group_description = string + members = optional(list(string), []) matching_rule = optional(string) defined_tags = optional(map(any)) freeform_tags = optional(map(any)) @@ -257,12 +259,27 @@ variable "groups" { default = {} } +variable "identity_domain_groups" { + type = map(object({ + group_name = string + group_description = string + idcs_endpoint = string + compartment_id = string + matching_rule = optional(string) + defined_tags = optional(list(map(any))) + freeform_tags = optional(list(map(any))) + members = optional(list(string)) + })) + default = {} +} + + variable "users" { type = map(object({ name = string description = string email = string - disable_capabilities = optional(list(string)) + enabled_capabilities = optional(list(string)) group_membership = optional(list(string)) defined_tags = optional(map(any)) freeform_tags = optional(map(any)) @@ -270,6 +287,23 @@ variable "users" { default = {} } +variable "identity_domain_users" { + type = map(object({ + family_name = string + idcs_endpoint = string + user_name = string + description = optional(string) + compartment_id = string + groups = optional(list(string)) + email = string + enabled_capabilities = list(string) + defined_tags = optional(list(map(any))) + freeform_tags = optional(list(map(any))) + })) + default = {} +} + + variable "networkSources" { type = map(object({ name = string @@ -504,40 +538,40 @@ variable "default_seclists" { variable "route_tables" { type = map(object({ - compartment_id = string - vcn_id = string - display_name = optional(string) - defined_tags = optional(map(any)) - freeform_tags = optional(map(any)) - route_rules_igw = list(map(any)) - route_rules_ngw = list(map(any)) - route_rules_sgw = list(map(any)) - route_rules_drg = list(map(any)) - route_rules_lpg = list(map(any)) - route_rules_ip = list(map(any)) - gateway_route_table = optional(bool,false) - default_route_table = optional(bool,false) + compartment_id = string + vcn_id = string + display_name = optional(string) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) + route_rules_igw = list(map(any)) + route_rules_ngw = list(map(any)) + route_rules_sgw = list(map(any)) + route_rules_drg = list(map(any)) + route_rules_lpg = list(map(any)) + route_rules_ip = list(map(any)) + gateway_route_table = optional(bool) + default_route_table = optional(bool) -})) -default = {} + })) + default = {} } variable "default_route_tables" { type = map(object({ - compartment_id = string - vcn_id = string - display_name = optional(string) - defined_tags = optional(map(any)) - freeform_tags = optional(map(any)) - route_rules_igw = list(map(any)) - route_rules_ngw = list(map(any)) - route_rules_sgw = list(map(any)) - route_rules_drg = list(map(any)) - route_rules_lpg = list(map(any)) - route_rules_ip = list(map(any)) - gateway_route_table = optional(bool,false) - default_route_table = optional(bool,false) -})) + compartment_id = string + vcn_id = string + display_name = optional(string) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) + route_rules_igw = list(map(any)) + route_rules_ngw = list(map(any)) + route_rules_sgw = list(map(any)) + route_rules_drg = list(map(any)) + route_rules_lpg = list(map(any)) + route_rules_ip = list(map(any)) + gateway_route_table = optional(bool) + default_route_table = optional(bool) + })) default = {} } @@ -673,73 +707,73 @@ variable "data_drg_route_table_distributions" { #################### variable "zones" { -type = map(object({ -compartment_id = string -display_name = string -view_compartment_id = optional(string) -view_id = optional(string) -zone_type = optional(string) -scope = optional(string) -freeform_tags = optional(map(any)) -defined_tags = optional(map(any)) -})) -default = {} + type = map(object({ + compartment_id = string + display_name = string + view_compartment_id = optional(string) + view_id = optional(string) + zone_type = optional(string) + scope = optional(string) + freeform_tags = optional(map(any)) + defined_tags = optional(map(any)) + })) + default = {} } variable "views" { -type = map(object({ -compartment_id = string -display_name = string -scope = optional(string) -freeform_tags = optional(map(any)) -defined_tags = optional(map(any)) -})) + type = map(object({ + compartment_id = string + display_name = string + scope = optional(string) + freeform_tags = optional(map(any)) + defined_tags = optional(map(any)) + })) default = {} } variable "rrsets" { -type = map(object({ -compartment_id = optional(string) -view_compartment_id = optional(string) -view_id = optional(string) -zone_id = string -domain = string -rtype = string -ttl = number -rdata = optional(list(string)) -scope = optional(string) -})) -default = {} + type = map(object({ + compartment_id = optional(string) + view_compartment_id = optional(string) + view_id = optional(string) + zone_id = string + domain = string + rtype = string + ttl = number + rdata = optional(list(string)) + scope = optional(string) + })) + default = {} } variable "resolvers" { -type = map(object({ -network_compartment_id= string -vcn_name = string -display_name = optional(string) -views = optional(map(object({ - view_id = optional(string) - view_compartment_id = optional(string) -}))) -resolver_rules = optional(map(object({ - client_address_conditions = optional(list(any)) - destination_addresses = optional(list(any)) - qname_cover_conditions = optional(list(any)) - source_endpoint_name = optional(string) -}))) -endpoint_names = optional(map(object({ - is_forwarding = optional(bool) - is_listening = optional(bool) - name = optional(string) - subnet_name = optional(string) - forwarding_address = optional(string) - listening_address = optional(string) - nsg_ids = optional(list(string)) -}))) -freeform_tags = optional(map(any)) -defined_tags = optional(map(any)) -})) -default = {} + type = map(object({ + network_compartment_id = string + vcn_name = string + display_name = optional(string) + views = optional(map(object({ + view_id = optional(string) + view_compartment_id = optional(string) + }))) + resolver_rules = optional(map(object({ + client_address_conditions = optional(list(any)) + destination_addresses = optional(list(any)) + qname_cover_conditions = optional(list(any)) + source_endpoint_name = optional(string) + }))) + endpoint_names = optional(map(object({ + is_forwarding = optional(bool) + is_listening = optional(bool) + name = optional(string) + subnet_name = optional(string) + forwarding_address = optional(string) + listening_address = optional(string) + nsg_ids = optional(list(string)) + }))) + freeform_tags = optional(map(any)) + defined_tags = optional(map(any)) + })) + default = {} } @@ -834,32 +868,32 @@ variable "instances" { policy_compartment_id = optional(string) network_type = optional(string) #extended_metadata = optional(string) - skip_source_dest_check = optional(bool) - baseline_ocpu_utilization = optional(string) + skip_source_dest_check = optional(bool) + baseline_ocpu_utilization = optional(string) #preemptible_instance_config = optional(string) - all_plugins_disabled = optional(bool) - is_management_disabled = optional(bool) - is_monitoring_disabled = optional(bool) - assign_private_dns_record = optional(string) - plugins_details = optional(map(any)) - is_live_migration_preferred = optional(bool) - recovery_action = optional(string) - are_legacy_imds_endpoints_disabled = optional(bool) - boot_volume_type = optional(string) - firmware = optional(string) - is_consistent_volume_naming_enabled = optional(bool) - remote_data_volume_type = optional(string) - platform_config = optional(list(map(any))) - launch_options = optional(list(map(any))) - ipxe_script = optional(string) - preserve_boot_volume = optional(bool) - vlan_id = optional(string) - kms_key_id = optional(string) - vnic_display_name = optional(string) - vnic_defined_tags = optional(map(any)) - vnic_freeform_tags = optional(map(any)) - defined_tags = optional(map(any)) - freeform_tags = optional(map(any)) + all_plugins_disabled = optional(bool) + is_management_disabled = optional(bool) + is_monitoring_disabled = optional(bool) + assign_private_dns_record = optional(string) + plugins_details = optional(map(any)) + is_live_migration_preferred = optional(bool) + recovery_action = optional(string) + are_legacy_imds_endpoints_disabled = optional(bool) + boot_volume_type = optional(string) + firmware = optional(string) + is_consistent_volume_naming_enabled = optional(bool) + remote_data_volume_type = optional(string) + platform_config = optional(list(map(any))) + launch_options = optional(list(map(any))) + ipxe_script = optional(string) + preserve_boot_volume = optional(bool) + vlan_id = optional(string) + kms_key_id = optional(string) + vnic_display_name = optional(string) + vnic_defined_tags = optional(map(any)) + vnic_freeform_tags = optional(map(any)) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) })) default = {} } @@ -934,6 +968,135 @@ variable "adb" { default = {} } +#################################### +####### MySql Database ######## +#################################### +variable "mysql_db_system" { + type = map(object({ + compartment_id = string + network_compartment_id = string + mysql_db_system_display_name = string + configuration_id = string + mysql_shape_name = string + mysql_db_system_admin_username = optional(string) + mysql_db_system_admin_password = optional(string) + mysql_db_system_availability_domain = optional(string) + subnet_id = string + mysql_db_system_data_storage_size_in_gb = number + mysql_db_system_hostname_label = string + vcn_names = string + mysql_db_system_backup_policy_is_enabled = bool + mysql_db_system_backup_policy_pitr_policy_is_enabled = bool + mysql_db_system_backup_policy_retention_in_days = number + mysql_db_system_backup_policy_window_start_time = string + mysql_db_system_crash_recovery = string + mysql_db_system_database_management = string + mysql_db_system_deletion_policy_automatic_backup_retention = string + mysql_db_system_deletion_policy_final_backup = string + mysql_db_system_deletion_policy_is_delete_protected = bool + mysql_db_system_description = string + mysql_db_system_fault_domain = string + mysql_db_system_ip_address = optional(string) + mysql_db_system_is_highly_available = bool + mysql_db_system_maintenance_window_start_time = string + mysql_db_system_port = number + mysql_db_system_port_x = number + mysql_db_system_source_source_type = optional(string) + backup_id = optional(string) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) + + + })) + default = {} +} + + +variable "mysql_configuration" { + type = map(object({ + compartment_id = string + mysql_configuration_shape_name = optional(string) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) + mysql_configuration_description = optional(string) + mysql_configuration_display_name = optional(string) + mysql_configuration_init_variables_lower_case_table_names = optional(string) + mysql_configuration_variables_autocommit = optional(string) + mysql_configuration_variables_big_tables = optional(string) + mysql_configuration_variables_binlog_expire_logs_seconds = optional(string) + mysql_configuration_variables_binlog_row_metadata = optional(string) + mysql_configuration_variables_binlog_row_value_options = optional(string) + mysql_configuration_variables_binlog_transaction_compression = optional(string) + mysql_configuration_variables_connection_memory_chunk_size = optional(string) + mysql_configuration_variables_connect_timeout = optional(string) + mysql_configuration_variables_completion_type = optional(string) + mysql_configuration_variables_connection_memory_limit = optional(string) + mysql_configuration_variables_cte_max_recursion_depth = optional(string) + mysql_configuration_variables_default_authentication_plugin = optional(string) + mysql_configuration_variables_foreign_key_checks = optional(string) + mysql_configuration_variables_global_connection_memory_limit = optional(string) + mysql_configuration_variables_global_connection_memory_tracking = optional(string) + mysql_configuration_variables_group_replication_consistency = optional(string) + mysql_configuration_variables_information_schema_stats_expiry = optional(string) + mysql_configuration_variables_innodb_buffer_pool_dump_pct = optional(string) + mysql_configuration_variables_innodb_buffer_pool_instances = optional(string) + mysql_configuration_variables_innodb_buffer_pool_size = optional(string) + mysql_configuration_variables_innodb_ddl_buffer_size = optional(string) + mysql_configuration_variables_innodb_ddl_threads = optional(string) + mysql_configuration_variables_innodb_ft_enable_stopword = optional(string) + mysql_configuration_variables_innodb_ft_max_token_size = optional(string) + mysql_configuration_variables_innodb_ft_min_token_size = optional(string) + mysql_configuration_variables_innodb_ft_num_word_optimize = optional(string) + mysql_configuration_variables_innodb_ft_result_cache_limit = optional(string) + mysql_configuration_variables_innodb_ft_server_stopword_table = optional(string) + mysql_configuration_variables_innodb_lock_wait_timeout = optional(string) + mysql_configuration_variables_innodb_log_writer_threads = optional(string) + mysql_configuration_variables_innodb_max_purge_lag = optional(string) + mysql_configuration_variables_innodb_max_purge_lag_delay = optional(string) + mysql_configuration_variables_innodb_stats_persistent_sample_pages = optional(string) + mysql_configuration_variables_innodb_stats_transient_sample_pages = optional(string) + mysql_configuration_variables_interactive_timeout = optional(string) + mysql_configuration_variables_local_infile = optional(string) + mysql_configuration_variables_mandatory_roles = optional(string) + mysql_configuration_variables_max_allowed_packet = optional(string) + mysql_configuration_variables_max_binlog_cache_size = optional(string) + mysql_configuration_variables_max_connect_errors = optional(string) + mysql_configuration_variables_max_connections = optional(string) + mysql_configuration_variables_max_execution_time = optional(string) + mysql_configuration_variables_max_heap_table_size = optional(string) + mysql_configuration_variables_max_prepared_stmt_count = optional(string) + mysql_configuration_variables_mysql_firewall_mode = optional(string) + mysql_configuration_variables_mysqlx_connect_timeout = optional(string) + mysql_configuration_variables_mysqlx_deflate_default_compression_level = optional(string) + mysql_configuration_variables_mysqlx_deflate_max_client_compression_level = optional(string) + mysql_configuration_variables_mysqlx_enable_hello_notice = optional(string) + mysql_configuration_variables_mysqlx_interactive_timeout = optional(string) + mysql_configuration_variables_mysqlx_lz4default_compression_level = optional(string) + mysql_configuration_variables_mysqlx_lz4max_client_compression_level = optional(string) + mysql_configuration_variables_mysqlx_max_allowed_packet = optional(string) + mysql_configuration_variables_mysqlx_read_timeout = optional(string) + mysql_configuration_variables_mysqlx_wait_timeout = optional(string) + mysql_configuration_variables_mysqlx_write_timeout = optional(string) + mysql_configuration_variables_mysqlx_zstd_default_compression_level = optional(string) + mysql_configuration_variables_mysqlx_zstd_max_client_compression_level = optional(string) + mysql_configuration_variables_net_read_timeout = optional(string) + mysql_configuration_variables_net_write_timeout = optional(string) + mysql_configuration_variables_parser_max_mem_size = optional(string) + mysql_configuration_variables_regexp_time_limit = optional(string) + mysql_configuration_variables_sort_buffer_size = optional(string) + mysql_configuration_variables_sql_mode = optional(string) + mysql_configuration_variables_sql_require_primary_key = optional(string) + mysql_configuration_variables_sql_warnings = optional(string) + mysql_configuration_variables_thread_pool_dedicated_listeners = optional(string) + mysql_configuration_variables_thread_pool_max_transactions_limit = optional(string) + mysql_configuration_variables_time_zone = optional(string) + mysql_configuration_variables_tmp_table_size = optional(string) + mysql_configuration_variables_transaction_isolation = optional(string) + mysql_configuration_variables_wait_timeout = optional(string) + + })) + default = {} +} ######################### ######### FSS ########### ######################### @@ -959,15 +1122,15 @@ variable "mount_targets" { variable "fss" { description = "To provision File System Services" type = map(object({ - availability_domain = string - compartment_id = string - display_name = optional(string) - source_snapshot = optional(string) - snapshot_policy = optional(string) - policy_compartment_id = optional(string) - kms_key_id = optional(string) - defined_tags = optional(map(any)) - freeform_tags = optional(map(any)) + availability_domain = string + compartment_id = string + display_name = optional(string) + source_snapshot = optional(string) + snapshot_policy = optional(string) + policy_compartment_id = optional(string) + kms_key_id = optional(string) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) })) default = {} } @@ -975,12 +1138,12 @@ variable "fss" { variable "nfs_export_options" { description = "To provision Export Sets" type = map(object({ - export_set_id = string - file_system_id = string - path = string - export_options = optional(list(any)) - defined_tags = optional(map(any)) - freeform_tags = optional(map(any)) + export_set_id = string + file_system_id = string + path = string + export_options = optional(list(any)) + defined_tags = optional(map(any)) + freeform_tags = optional(map(any)) is_idmap_groups_for_sys_auth = optional(bool) })) default = {} @@ -1246,6 +1409,17 @@ variable "lbr_reserved_ips" { default = {} } +variable "lb_routing_policies" { + description = "To provision Load Balancer Routing Policies" + type = map(object({ + name = string + load_balancer_id = string + condition_language_version = optional(string) + rules = optional(list(map(any))) + })) + default = {} +} + ################################### ####### Load Balancer Logs ######## ################################### @@ -1322,11 +1496,11 @@ variable "nlb_backend_sets" { network_load_balancer_id = string policy = string protocol = string - domain_name = optional(string) - query_class = optional(string) - query_type = optional(string) - rcodes = optional(list(string)) - transport_protocol = optional(string) + domain_name = optional(string) + query_class = optional(string) + query_type = optional(string) + rcodes = optional(list(string)) + transport_protocol = optional(string) return_code = optional(number) interval_in_millis = optional(number) port = optional(number) @@ -1591,10 +1765,10 @@ variable "clusters" { cluster_kms_key_id = optional(string) defined_tags = optional(map(any)) freeform_tags = optional(map(any)) - lb_defined_tags = optional(map(any)) - lb_freeform_tags = optional(map(any)) - volume_defined_tags = optional(map(any)) - volume_freeform_tags = optional(map(any)) + lb_defined_tags = optional(map(any)) + lb_freeform_tags = optional(map(any)) + volume_defined_tags = optional(map(any)) + volume_freeform_tags = optional(map(any)) })) default = {} } @@ -1636,25 +1810,25 @@ variable "nodepools" { variable "virtual-nodepools" { type = map(object({ - display_name = string - cluster_name = string - compartment_id = string - network_compartment_id = string - vcn_name = string - node_shape = string - initial_virtual_node_labels = optional(map(any)) - availability_domain = number - fault_domains = list(string) - subnet_id = string - size = number - pod_nsg_ids = optional(list(string)) - pod_subnet_id = string - worker_nsg_ids = optional(list(string)) - taints = optional(list(any)) - node_defined_tags = optional(map(any)) - node_freeform_tags = optional(map(any)) - nodepool_defined_tags = optional(map(any)) - nodepool_freeform_tags = optional(map(any)) + display_name = string + cluster_name = string + compartment_id = string + network_compartment_id = string + vcn_name = string + node_shape = string + initial_virtual_node_labels = optional(map(any)) + availability_domain = number + fault_domains = list(string) + subnet_id = string + size = number + pod_nsg_ids = optional(list(string)) + pod_subnet_id = string + worker_nsg_ids = optional(list(string)) + taints = optional(list(any)) + node_defined_tags = optional(map(any)) + node_freeform_tags = optional(map(any)) + nodepool_defined_tags = optional(map(any)) + nodepool_freeform_tags = optional(map(any)) })) default = {} } @@ -1682,8 +1856,8 @@ variable "sddcs" { vsphere_vlan_id = string capacity_reservation_id = optional(string) defined_tags = optional(map(any)) - display_name = optional(string) - initial_cluster_display_name = optional(string) + display_name = optional(string) + initial_cluster_display_name = optional(string) freeform_tags = optional(map(any)) hcx_action = optional(string) hcx_vlan_id = optional(string) @@ -1726,7 +1900,7 @@ variable "sddc-clusters" { vsphere_vlan_id = string capacity_reservation_id = optional(string) defined_tags = optional(map(any)) - display_name = optional(string) + display_name = optional(string) freeform_tags = optional(map(any)) hcx_action = optional(string) hcx_vlan_id = optional(string) @@ -1743,7 +1917,7 @@ variable "sddc-clusters" { reserving_hcx_on_premise_license_keys = optional(string) workload_network_cidr = optional(string) workload_datastore = optional(list(string)) - sddc_id = optional(string) + sddc_id = optional(string) esxi_software_version = optional(string) })) @@ -1770,16 +1944,16 @@ variable "vaults" { variable "keys" { type = map(object({ - compartment_id = string - display_name = string - vault_name = string - algorithm = optional(string) - length = optional(string) - curve_id = optional(string) - protection_mode = optional(string) - freeform_tags = optional(map(any)) - defined_tags = optional(map(any)) - is_auto_rotation_enabled = optional(bool) + compartment_id = string + display_name = string + vault_name = string + algorithm = optional(string) + length = optional(string) + curve_id = optional(string) + protection_mode = optional(string) + freeform_tags = optional(map(any)) + defined_tags = optional(map(any)) + is_auto_rotation_enabled = optional(bool) rotation_interval_in_days = optional(string) })) @@ -1802,7 +1976,7 @@ variable "budgets" { freeform_tags = optional(map(any)) processing_period_type = optional(string) budget_end_date = optional(string) - budget_start_date = optional(string) + budget_start_date = optional(string) target_type = optional(string) targets = optional(list(any)) })) @@ -2080,3 +2254,4 @@ variable "fw_logs" { # Add new variables here # ########################## ######################### END ######################### + diff --git a/cd3_automation_toolkit/user-scripts/terraform/vlan.tf b/cd3_automation_toolkit/user-scripts/terraform/vlan.tf index ec9f98c7f..3ac859766 100644 --- a/cd3_automation_toolkit/user-scripts/terraform/vlan.tf +++ b/cd3_automation_toolkit/user-scripts/terraform/vlan.tf @@ -1,3 +1,6 @@ +# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. +# ############################################ # Module Network - VLAN # Create VLAN diff --git a/jenkins_install/tf-apply.groovy b/jenkins_install/apply.groovy similarity index 72% rename from jenkins_install/tf-apply.groovy rename to jenkins_install/apply.groovy index e180317bb..ee82496db 100644 --- a/jenkins_install/tf-apply.groovy +++ b/jenkins_install/apply.groovy @@ -1,13 +1,16 @@ def tf_plan = "Changes" + pipeline { agent any options { ansiColor('xterm') } + stages { stage('Set Environment Variables') { steps { script { + def jobName = env.JOB_NAME def fileContent = readFile "${JENKINS_HOME}/jenkins.properties" // Split file content into lines def lines = fileContent.readLines() @@ -19,28 +22,37 @@ pipeline { variables[parts[0].trim()] = parts[1].trim() } } + println "Variables: ${variables}" + + if (variables.containsKey('tf_or_tofu')) { + // Strip quotes from tf_or_tofu value + def tfortofuValue = variables['tf_or_tofu'].replaceAll(/^"|"$/, '') + env.tf_or_tofu = tfortofuValue + } else { + println "tfortofu param not found in the properties file" + } + + def variableOds = variables['outdir_structure'].toString().replaceAll("\\[|\\]", '').replaceAll('"', '') env.out_str = "${variableOds}" - def jobName = env.JOB_NAME def parts = jobName.split('/') if (env.out_str == 'Multiple_Outdir') { // Assuming the job name format is /job//job/job_name - env.Region = parts[1] - env.Service = parts[2] - } - else { + env.Region = parts[2] + env.Service = parts[3] + } else { // Assuming the job name format is /job/job_name - env.Region = parts[1] + env.Region = parts[2] env.Service = '' if (env.Region == 'global') { env.Service = 'rpc' } - } + } } } } - - stage('Terraform Plan') { + // Terraform/Tofu Plan + stage('Plan') { when { expression { return env.GIT_BRANCH == 'origin/develop'; @@ -50,16 +62,17 @@ pipeline { steps { catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { script { - sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform init -upgrade" - // Run Terraform plan and capture the output - terraformPlanOutput = sh(script: "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform plan -out=tfplan.out", returnStdout: true).trim() + def toolCmd = env.tf_or_tofu == 'terraform' ? 'terraform' : 'tofu' + sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} init -upgrade" + // Run Terraform/Tofu plan and capture the output + planOutput = sh(script: "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} plan -out=tfplan.out", returnStdout: true).trim() // Check if the plan contains any changes - if (terraformPlanOutput.contains('No changes.')) { - echo 'No changes in Terraform plan. Skipping further stages.' + if (planOutput.contains('No changes.')) { + echo 'No changes in Plan. Skipping further stages.' tf_plan = "No Changes" } else { // If there are changes, proceed with applying the plan - echo "Changes detected in Terraform plan. Proceeding with apply. \n${terraformPlanOutput}" + echo "Changes detected in Plan. Proceeding with apply. \n${planOutput}" } } } @@ -69,7 +82,7 @@ pipeline { // OPA Stage stage('OPA') { when { - allOf{ + allOf { expression { return env.GIT_BRANCH == 'origin/develop' } expression { return tf_plan == "Changes" } expression { return currentBuild.result != "ABORTED" } @@ -80,8 +93,9 @@ pipeline { steps { catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { script { - // Run Terraform show and capture the output - sh "set +x && cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform show -json tfplan.out > tfplan.json" + def toolCmd = env.tf_or_tofu == 'terraform' ? 'terraform' : 'tofu' + // Run Terraform/Tofu show and capture the output + sh "set +x && cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} show -json tfplan.out > tfplan.json" // Run OPA eval opaOutput = sh(script: "opa eval -f pretty -b /cd3user/oci_tools/cd3_automation_toolkit/user-scripts/OPA/ -i \"${WORKSPACE}/${env.Region}/${env.Service}/tfplan.json\" data.terraform.deny", returnStdout: true).trim() if (opaOutput == '[]') { @@ -98,7 +112,7 @@ pipeline { // Get Approval stage('Get Approval') { when { - allOf{ + allOf { expression { return env.GIT_BRANCH == 'origin/develop' } expression { return tf_plan == "Changes" } expression { return currentBuild.result != "ABORTED" } @@ -118,10 +132,10 @@ pipeline { } } - // Terraform Apply - stage('Terraform Apply') { + // Terraform/Tofu Apply + stage('Apply') { when { - allOf{ + allOf { expression { return env.GIT_BRANCH == 'origin/develop' } expression { return tf_plan == "Changes" } expression { return currentBuild.result != "ABORTED" } @@ -132,8 +146,8 @@ pipeline { steps { catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { script { - sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform apply --auto-approve tfplan.out" - + def toolCmd = env.tf_or_tofu == 'terraform' ? 'terraform' : 'tofu' + sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} apply --auto-approve tfplan.out" } } } @@ -142,7 +156,7 @@ pipeline { // Git Commit to main stage('Git Commit to main') { when { - allOf{ + allOf { expression { return currentBuild.result != "ABORTED" } expression { return currentBuild.result != "FAILURE" } } @@ -161,13 +175,13 @@ pipeline { repo_name=${GIT_URL##*/} cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} git checkout main - reg=`echo ${JOB_NAME}| cut -d "/" -f2` - service=`echo ${JOB_NAME}| cut -d "/" -f3` + reg=`echo ${JOB_NAME}| cut -d "/" -f3` + service=`echo ${JOB_NAME}| cut -d "/" -f4` copy_path=${reg}/${service} cp -r ${WORKSPACE}/${copy_path}/* ${copy_path}/ git add ${copy_path}* ''' - } catch(Exception e1) { + } catch (Exception e1) { println(e1) sh ''' set +x @@ -178,40 +192,40 @@ pipeline { sh ''' set +x repo_name=${GIT_URL##*/} - reg=`echo ${JOB_NAME}| cut -d "/" -f2` - service=`echo ${JOB_NAME}| cut -d "/" -f3` + reg=`echo ${JOB_NAME}| cut -d "/" -f3` + service=`echo ${JOB_NAME}| cut -d "/" -f4` cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} git_status=`git status --porcelain` if [[ $git_status ]]; then - git commit -m "commit for terraform-apply build - ${BUILD_NUMBER} for "${reg}"/"${service} + git commit -m "commit for apply build - ${BUILD_NUMBER} for ${reg}/${service}" else echo "Nothing to commit" fi ''' status = sh(script: ''' - set +x - repo_name=${GIT_URL##*/} - cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} - git pull --no-edit origin main - git push --porcelain origin main - ''', returnStatus: true) + set +x + repo_name=${GIT_URL##*/} + cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} + git pull --no-edit origin main + git push --porcelain origin main + ''', returnStatus: true) - while (status != 0){ - println("Trying again ...") - status = sh(script: ''' - set +x - repo_name=${GIT_URL##*/} - cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} - git config pull.rebase true - git pull --no-edit origin main - set -x - git push --porcelain origin main - ''', returnStatus: true) - } - sh ''' - set +x - rm -rf ${WORKSPACE}/../${BUILD_NUMBER} - ''' + while (status != 0) { + println("Trying again ...") + status = sh(script: ''' + set +x + repo_name=${GIT_URL##*/} + cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} + git config pull.rebase true + git pull --no-edit origin main + set -x + git push --porcelain origin main + ''', returnStatus: true) + } + sh ''' + set +x + rm -rf ${WORKSPACE}/../${BUILD_NUMBER} + ''' } else { try { @@ -223,23 +237,24 @@ pipeline { repo_name=${GIT_URL##*/} cd ${WORKSPACE}/../${BUILD_NUMBER}/${repo_name} git checkout main - reg=`echo ${JOB_NAME}| cut -d "/" -f2` + reg=`echo ${JOB_NAME}| cut -d "/" -f3` copy_path=${reg} cp -r ${WORKSPACE}/${copy_path}/* ${copy_path}/ git add ${copy_path}* git_status=`git status --porcelain` if [[ $git_status ]]; then - git commit -m "commit for terraform-apply build - ${BUILD_NUMBER} for "${reg}"/"${service} + git commit -m "commit for apply build - ${BUILD_NUMBER} for ${reg}" git config pull.rebase true git pull --no-edit origin main git push origin main else echo "Nothing to commit" fi + cd ${WORKSPACE}/.. rm -rf ${WORKSPACE}/../${BUILD_NUMBER} ''' - } catch(Exception e1) { + } catch (Exception e1) { println(e1) sh ''' cd ${WORKSPACE}/.. @@ -247,11 +262,10 @@ pipeline { exit 1 ''' } - } } } } } } -} +} \ No newline at end of file diff --git a/jenkins_install/destroy.groovy b/jenkins_install/destroy.groovy new file mode 100644 index 000000000..ad63c2ad9 --- /dev/null +++ b/jenkins_install/destroy.groovy @@ -0,0 +1,178 @@ +/* Set the various stages of the build */ +def tf_plan = "Changes" + +pipeline { + agent any + options { + ansiColor('xterm') + } + stages { + stage('Set Environment Variables') { + steps { + script { + def fileContent = readFile "${JENKINS_HOME}/jenkins.properties" + // Split file content into lines + def lines = fileContent.readLines() + + // Process each line to extract variable name and value + def variables = [:] + lines.each { line -> + def parts = line.split('=') + if (parts.size() == 2) { + variables[parts[0].trim()] = parts[1].trim() + } + } + println "Variables: ${variables}" + def variableOds = variables['outdir_structure'].toString().replaceAll("\\[|\\]", '').replaceAll('"', '') + env.out_str = "${variableOds}" + + if (variables.containsKey('tf_or_tofu')) { + // Strip quotes from tf_or_tofu value + def tfortofuValue = variables['tf_or_tofu'].replaceAll(/^"|"$/, '').trim() + env.tf_or_tofu = tfortofuValue + } else { + println "tfortofu param not found in the properties file" + } + + def jobName = env.JOB_NAME + def parts = jobName.split('/') + if (env.out_str == 'Multiple_Outdir') { + // Assuming the job name format is /job//job/job_name + env.Region = parts[2] + env.Service = parts[3] + } else { + // Assuming the job name format is /job/job_name + env.Region = parts[2] + env.Service = '' + if (env.Region == 'global') { + env.Service = 'rpc' + } + } + } + } + } + + //Terraform/Tofu Destroy Plan + stage('Destroy Plan') { + when { + expression { return env.GIT_BRANCH == 'origin/develop'; } + } + + steps { + catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { + script { + def toolCmd = env.tf_or_tofu == 'terraform' ? 'terraform' : 'tofu' + sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} init -upgrade" + // Run destroy plan + destroyPlanOutput = sh(script: "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} plan -destroy", returnStdout: true).trim() + + // Check if the plan contains any changes + if (destroyPlanOutput.contains('No changes.')) { + echo 'No changes in destroy plan. Skipping further stages.' + tf_plan = "No Changes" + } else { + echo "Proceeding with destroy. \n${destroyPlanOutput}" + } + } + } + } + } + + /** Approval for Destroy **/ + stage('Get Approval') { + when { + allOf { + expression { return env.GIT_BRANCH == 'origin/develop'; } + expression { return tf_plan == "Changes" } + expression { return currentBuild.result != "FAILURE" } + } + } + input { + message "Do you want to perform destroy?" + } + steps { + echo "Approval for the Destroy Granted!" + } + } + + // Terraforn/Tofu Destroy + stage('Destroy') { + when { + allOf { + expression { return env.GIT_BRANCH == 'origin/develop'; } + expression { return tf_plan == "Changes" } + expression { return currentBuild.result != "FAILURE" } + } + } + + steps { + catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { + script { + def toolCmd = env.tf_or_tofu == 'terraform' ? 'terraform' : 'tofu' + sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && ${toolCmd} destroy --auto-approve" + } + } + } + } + + /** Main branch commit to keep changes in Sync **/ + stage('Commit To Main') { + when { + allOf { + expression { return env.GIT_BRANCH == 'origin/develop'; } + expression { return tf_plan == "Changes" } + expression { return currentBuild.result != "FAILURE" } + } + } + steps { + catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { + script { + def buildDir = "${WORKSPACE}/${BUILD_NUMBER}" + // Create directory with build number + sh "mkdir -p ${buildDir}" + // Commit changes to the main branch + dir(buildDir) { + sh """ + git clone ${GIT_URL} + cd \$(ls -d */|head -n 1) + git checkout main + cd "${env.Region}/${env.Service}" + git pull --no-edit origin main + rm -f *.tfvars + git status + git add --all . + """ + + def git_status = false + while (!git_status) { + // Execute the git commands using shell + def gitResult = sh(script: """ + cd "\$(ls -d */|head -n 1)" + cd "${env.Region}/${env.Service}" + git fetch origin main + git merge origin/main + git commit -m "commit for destroy build - ${BUILD_NUMBER} for ${env.Region}/${env.Service}" + git push --porcelain origin main + """, returnStatus: true) + + if (gitResult == 0) { + git_status = true + } else { + echo "Git operation failed, retrying...." + sleep 3 // 3 seconds before retrying + } + } + } + } + } + } + + post { + always { + // Delete the build directory and the temporary directory + deleteDir() + } + } + } + } +} diff --git a/jenkins_install/example/jenkins.properties b/jenkins_install/example/jenkins.properties index 8bedb634d..e902b1f18 100644 --- a/jenkins_install/example/jenkins.properties +++ b/jenkins_install/example/jenkins.properties @@ -1,5 +1,7 @@ +[PREFIX] git_url="ssh://devops.scmservice..oci.oraclecloud.com/namespaces//projects//repositories/" regions=["ashburn", "phoenix"] services=["identity", "tagging", "network", "vlan", "nsg", "compute", "database", "fss", "oke", "ocvs", "security", "managementservices", "budget", "cis", "oss", "dns"] outdir_structure=["Multiple_Outdir"] #outdir_structure=["Single_Outdir"] +tf_or_tofu="terraform" diff --git a/jenkins_install/init/01_jenkins-config.groovy b/jenkins_install/init/01_jenkins-config.groovy index 540a178e5..bf9cae235 100644 --- a/jenkins_install/init/01_jenkins-config.groovy +++ b/jenkins_install/init/01_jenkins-config.groovy @@ -1,37 +1,37 @@ -import jenkins.model.Jenkins +import jenkins.model.* import com.cloudbees.hudson.plugins.folder.* +import java.io.ByteArrayInputStream +import java.nio.file.Files +import java.nio.file.StandardCopyOption +// Read the Jenkins instance +Jenkins jenkins = Jenkins.getInstance() -Jenkins jenkins = Jenkins.instance +// Read the properties file def JENKINS_HOME = System.getenv("JENKINS_HOME") File file = new File("$JENKINS_HOME/jenkins.properties") -file.withReader { reader -> - while ((line = reader.readLine()) != null) { - if (line.startsWith('git_url')) { - git_url = Eval.me(line.split("=")[1]) - } - if (line.startsWith('regions')) { - regions = Eval.me(line.split("=")[1]) - } - if (line.startsWith('outdir_structure')) { - outdir_structure = Eval.me(line.split("=")[1]) - } - if (line.startsWith('services')) { - services = Eval.me(line.split("=")[1]) - } - } - } -def tfApplyJobName = "terraform-apply" -def tfDestroyJobName = "terraform-destroy" +// Parse the properties file into profiles first. +def profiles = [:] +def currentProfile = "" +file.readLines('UTF-8').each { line -> + if (line.startsWith('[')) { + currentProfile = line.replace('[', '').replace(']', '').trim() + profiles[currentProfile] = [:] + } else if (line.contains('=')) { + def parts = line.split('=') + profiles[currentProfile][parts[0].trim()] = Eval.me(parts[1].trim()) + } +} // Function to create job XML -def createJobXml(scriptPath, gitUrl) { +def createJobXml(scriptPath, gitUrl, tf_or_tofu) { return """ false + ${scriptPath} false @@ -55,37 +55,60 @@ def createJobXml(scriptPath, gitUrl) { """ } -// Function to create Jenkins job -def createJob(parent, jobName, xml) { - def jobXmlStream = new ByteArrayInputStream(xml.getBytes()) - parent.createProjectFromXML(jobName, jobXmlStream) +// Function to create Jenkins job if it does not exist +def createJobIfNotExists(parent, jobName, xml) { + def job = parent.getItem(jobName) + if (job == null) { + def jobXmlStream = new ByteArrayInputStream(xml.getBytes()) + parent.createProjectFromXML(jobName, jobXmlStream) + } else { + println "Job already exists: ${jobName}" + } } -// Create jobs for each configuration -jenkins.with { - Folder ost = getItem("terraform_files") ?: createProject(Folder.class, "terraform_files") +// Create jobs for each profile +profiles.each { profileName, profile -> + // Create profile folder + Folder profileFolder = jenkins.getItem(profileName) ?: jenkins.createProject(Folder.class, profileName) + Folder tfFolder = profileFolder.getItem("terraform_files") ?: profileFolder.createProject(Folder.class, "terraform_files") - for (os in outdir_structure) { - Folder global = ost.getItem("global") ?: ost.createProject(Folder.class, "global") - Folder rpc = global.getItem("rpc") ?: global.createProject(Folder.class, "rpc") + // Create global and rpc folders + Folder globalFolder = tfFolder.getItem("global") ?: tfFolder.createProject(Folder.class, "global") + Folder rpcFolder = globalFolder.getItem("rpc") ?: globalFolder.createProject(Folder.class, "rpc") - createJob(rpc, tfApplyJobName, createJobXml('tf-apply.groovy', git_url)) - createJob(rpc, tfDestroyJobName, createJobXml('tf-destroy.groovy', git_url)) - for (reg in regions) { - Folder folder = ost.getItem(reg) ?: ost.createProject(Folder.class, reg) + // Create jobs in rpc folder + createJobIfNotExists(rpcFolder, "apply", createJobXml('apply.groovy', profile.git_url, profile.tf_or_tofu)) + createJobIfNotExists(rpcFolder, "destroy", createJobXml('destroy.groovy', profile.git_url, profile.tf_or_tofu)) - if (os == "Single_Outdir") { - createJob(folder, tfApplyJobName, createJobXml('tf-apply.groovy', git_url)) - createJob(folder, tfDestroyJobName, createJobXml('tf-destroy.groovy', git_url)) - } + profile.regions.each { region -> + Folder regionFolder = tfFolder.getItem(region) ?: tfFolder.createProject(Folder.class, region) - if (os == "Multiple_Outdir" && services) { - for (svc in services) { - Folder svcFolder = folder.getItem(svc) ?: folder.createProject(Folder.class, svc) - createJob(svcFolder, tfApplyJobName, createJobXml('tf-apply.groovy', git_url)) - createJob(svcFolder, tfDestroyJobName, createJobXml('tf-destroy.groovy', git_url)) + if (profile.outdir_structure.contains("Multiple_Outdir") && profile.services) { + profile.services.each { service -> + Folder serviceFolder = regionFolder.getItem(service) ?: regionFolder.createProject(Folder.class, service) + + createJobIfNotExists(serviceFolder, "apply", createJobXml('apply.groovy', profile.git_url, profile.tf_or_tofu)) + createJobIfNotExists(serviceFolder, "destroy", createJobXml('destroy.groovy', profile.git_url, profile.tf_or_tofu)) } + } else { + createJobIfNotExists(regionFolder, "apply", createJobXml('apply.groovy', profile.git_url, profile.tf_or_tofu)) + createJobIfNotExists(regionFolder, "destroy", createJobXml('destroy.groovy', profile.git_url, profile.tf_or_tofu)) } } + // Move setupoci directory to the correct location. Default is not picked up in UI. + def setupociSrcPath = "$JENKINS_HOME/jobs/${profileName}/setupoci" + def setupociDestPath = "$JENKINS_HOME/jobs/${profileName}/jobs/setupoci" + + def setupociSrcDir = new File(setupociSrcPath) + def setupociDestDir = new File(setupociDestPath) + + if (setupociSrcDir.exists()) { + Files.move(setupociSrcDir.toPath(), setupociDestDir.toPath(), StandardCopyOption.REPLACE_EXISTING) + // println "Moved directory from ${setupociSrcDir} to ${setupociDestDir}" + } } -} + +// Reload Jenkins configuration +Jenkins.instance.reload() +println "Jenkins configuration reloaded." + diff --git a/jenkins_install/init/02_jenkins-view.groovy b/jenkins_install/init/02_jenkins-view.groovy old mode 100755 new mode 100644 index edec49a67..78b10e758 --- a/jenkins_install/init/02_jenkins-view.groovy +++ b/jenkins_install/init/02_jenkins-view.groovy @@ -1,5 +1,9 @@ import jenkins.model.Jenkins +import hudson.model.ListView +import hudson.model.ViewGroup +import com.cloudbees.hudson.plugins.folder.Folder +// Function to create views for each region within profile directories def createRegionViews() { def jenkinsInstance = Jenkins.getInstance() if (jenkinsInstance == null) { @@ -7,48 +11,81 @@ def createRegionViews() { return } - def parentPath = "terraform_files" - def parent = jenkinsInstance.getItemByFullName(parentPath) + // Read the properties file + def JENKINS_HOME = System.getenv("JENKINS_HOME") + File file = new File("$JENKINS_HOME/jenkins.properties") - if (parent != null && parent instanceof hudson.model.ViewGroup) { - parent.items.each { regionFolder -> - def viewName = regionFolder.name - def view = jenkinsInstance.getView(viewName) + // Parse the properties file into profiles + def profiles = [:] + def currentProfile = "" + file.eachLine { line -> + if (line.startsWith('[')) { + currentProfile = line.replace('[', '').replace(']', '').trim() + profiles[currentProfile] = [:] + } else if (line.contains('=')) { + def parts = line.split('=') + profiles[currentProfile][parts[0].trim()] = Eval.me(parts[1].trim()) + } + } - if (view == null) { - view = new hudson.model.ListView(viewName, jenkinsInstance) - jenkinsInstance.addView(view) - } + // Create views for each profile + profiles.each { profileName, profile -> + def profileFolder = jenkinsInstance.getItem(profileName) + if (profileFolder != null && profileFolder instanceof ViewGroup) { + profile.regions.each { region -> + def viewName = region + def view = profileFolder.getView(viewName) - // Clear the view to remove any existing jobs - view.items.clear() + if (view == null) { + println("Creating view: $viewName in profile: $profileName") + def newView = new ListView(viewName) + profileFolder.addView(newView) + newView.save() + println("View '$viewName' created successfully in profile '$profileName'.") + view = newView + } else { + println("View '$viewName' already exists in profile '$profileName'.") + } - // Add jobs to the view - addJobsToView(view, regionFolder) + // Clear the view to remove any existing jobs + view.items.clear() - // Set the "Recurse in folders" option - view.setRecurse(true) + // Navigate through the structure to find jobs + def terraformFilesFolder = profileFolder.getItem('terraform_files') + if (terraformFilesFolder instanceof ViewGroup) { + def regionFolder = terraformFilesFolder.getItem(region) + if (regionFolder instanceof ViewGroup) { + regionFolder.items.each { serviceFolder -> + if (serviceFolder instanceof ViewGroup) { + addJobsToView(view, serviceFolder) + } + } + } + } - // Save the view configuration - view.save() + // Set the "Recurse in folders" option + view.setRecurse(true) - println("View '$viewName' created successfully.") + // Save the view configuration + view.save() + } + } else { + println("Profile folder not found: $profileName") } - } else { - println("Parent folder not found: $parentPath") } } -def addJobsToView(hudson.model.ListView view, hudson.model.ViewGroup folder) { +// Function to add jobs to view +def addJobsToView(ListView view, ViewGroup folder) { folder.items.each { item -> if (item instanceof hudson.model.Job) { view.add(item) - } else if (item instanceof hudson.model.ViewGroup) { + } else if (item instanceof ViewGroup) { // Recursively add jobs from sub-folders addJobsToView(view, item) } } } -// function to create region views +// Function to create region views createRegionViews() \ No newline at end of file diff --git a/jenkins_install/jcasc.yaml b/jenkins_install/jcasc.yaml index a7f8290dc..813e4f224 100644 --- a/jenkins_install/jcasc.yaml +++ b/jenkins_install/jcasc.yaml @@ -47,6 +47,7 @@ security: - "method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object" - "new java.io.File java.lang.String" - "staticMethod org.codehaus.groovy.runtime.ResourceGroovyMethods readLines java.io.File" + - "method java.io.File listFiles" unclassified: buildDiscarders: configuredBuildDiscarders: diff --git a/jenkins_install/jenkins.sh b/jenkins_install/jenkins.sh index 93b4c79fb..ef51505d4 100644 --- a/jenkins_install/jenkins.sh +++ b/jenkins_install/jenkins.sh @@ -11,13 +11,53 @@ if [ ! -d "$JENKINS_HOME" ]; then exit fi -# Copy Required files to JENKINS_HOME +## Copy Required files to JENKINS_HOME +#cp ${JENKINS_INSTALL}/jcasc.yaml "$JENKINS_HOME/" +#if [ ! -d "$JENKINS_HOME/jobs/setUpOCI" ]; then +# mkdir -p "$JENKINS_HOME/jobs/setUpOCI" +#fi +#cp ${JENKINS_INSTALL}/setUpOCI_config.xml "$JENKINS_HOME/jobs/setUpOCI/config.xml" +#cp -r ${JENKINS_INSTALL}/scriptler $JENKINS_HOME + cp ${JENKINS_INSTALL}/jcasc.yaml "$JENKINS_HOME/" -if [ ! -d "$JENKINS_HOME/jobs/setUpOCI" ]; then - mkdir -p "$JENKINS_HOME/jobs/setUpOCI" -fi -cp ${JENKINS_INSTALL}/setUpOCI_config.xml "$JENKINS_HOME/jobs/setUpOCI/config.xml" -cp -r ${JENKINS_INSTALL}/scriptler $JENKINS_HOME + +# Read profiles from jenkins.properties only +declare -A profiles +current_profile="" +while IFS= read -r line; do + if [[ "$line" =~ ^\[.*\]$ ]]; then + current_profile=$(echo "$line" | tr -d '[]' | xargs -0) + profiles["$current_profile"]="" + echo "Processing profile: $current_profile" # Debug line + elif [[ "$line" == *=* ]]; then + key=$(echo "$line" | cut -d'=' -f1 | xargs -0) + value=$(echo "$line" | cut -d'=' -f2- | xargs -0) + profiles["$current_profile"]+="$key='$value' " + fi +done < "$JENKINS_HOME/jenkins.properties" + +# Create setupoci job inside each profile folder +for profile_name in "${!profiles[@]}"; do + # Remove any brackets or whitespace from profile_name + profile_folder_path="$JENKINS_HOME/jobs/${profile_name}" + setupoci_job_dest="$profile_folder_path/setupoci" + + # Create profile and setupoci directories if they don't exist + mkdir -p "$setupoci_job_dest" + echo "Creating directory: $setupoci_job_dest" # Debug line + + # Copy setupoci config + cp "${JENKINS_INSTALL}/setUpOCI_config.xml" "$setupoci_job_dest/config.xml" + echo "Copied setUpOCI_config.xml to $setupoci_job_dest/config.xml" # Debug line +done + +# Copy scriptler directory +cp -r "${JENKINS_INSTALL}/scriptler" "$JENKINS_HOME" +echo "Copied scriptler directory to $JENKINS_HOME" # Debug line + +echo "SetupOCI jobs created for profiles." + + #Generate Self Signed Cert and Copy to JENKINS_HOME keytool -genkey -keystore "$JENKINS_INSTALL/oci_toolkit.jks" -alias "automationtoolkit" -keyalg RSA -validity 60 -keysize 2048 -dname "CN=oci-automation, OU=toolkit, C=IN" -ext SAN=dns:automationtoolkit,ip:127.0.0.1 -storepass automationtoolkit && keytool -importkeystore -srckeystore "$JENKINS_INSTALL/oci_toolkit.jks" -srcstoretype JKS -deststoretype PKCS12 -destkeystore "$JENKINS_HOME/oci_toolkit.p12" -srcstorepass automationtoolkit -deststorepass automationtoolkit -noprompt @@ -58,4 +98,4 @@ if [[ $# -lt 1 ]] || [[ "$1" == "--"* ]]; then fi # As argument is not jenkins, assume user want to run his own process, for example a `bash` shell to explore this image -exec "$@" +exec "$@" \ No newline at end of file diff --git a/jenkins_install/scriptler/scripts/AdditionalFilters.groovy b/jenkins_install/scriptler/scripts/AdditionalFilters.groovy index db01fc1a8..1642d8255 100644 --- a/jenkins_install/scriptler/scripts/AdditionalFilters.groovy +++ b/jenkins_install/scriptler/scripts/AdditionalFilters.groovy @@ -31,7 +31,19 @@ html_to_be_rendered = """ """ } +domain_filter_val = "Unset" for (item in SubOptions.split(",")) { + if ((item in ["Export Groups","Export Users"]) && (domain_filter_val.equals("Unset"))) { + html_to_be_rendered = """ + ${html_to_be_rendered} + + + + (Enter 'all' to export from all domains OR leave it Blank to export from default domain )
+ + """ + domain_filter_val = "Set" + } if (item.equals("Export Instances (excludes instances launched by OKE)")) { html_to_be_rendered = """ ${html_to_be_rendered} @@ -161,41 +173,6 @@ for (item in SubOptions.split(",")) { """ } - if (item.equals('Create Key/Vault')){ - html_to_be_rendered = """ - ${html_to_be_rendered} - - - - - - - - - - - - - """ - } - if (item.equals('Create Default Budget')){ - html_to_be_rendered = """ - ${html_to_be_rendered} - - - -
- - - - - -
- - - """ - } - if (item.equals('Enable Cloud Guard')){ html_to_be_rendered = """ ${html_to_be_rendered} @@ -225,7 +202,53 @@ for (item in SubChildOptions.split(",")) { """ } - break + if (item.equals("Export DR Plan")) { + html_to_be_rendered = """ + ${html_to_be_rendered} + + + + + (Default is 'prefix_oci-fsdr-plan.xlsx at /cd3user/tenancies//othertools_files')
+ + + + + + (Default is 'FSDR-Plan')
+ + + + + + (Mandatory)
+ + + """ + } + + if (item.equals("Update DR Plan")) { + html_to_be_rendered = """ + ${html_to_be_rendered} + + + + (Default is 'prefix_oci-fsdr-plan.xlsx at /cd3user/tenancies//othertools_files)
+ + + + + (Default is 'FSDR-Plan' if left empty)
+ + + + + (Mandatory)
+ + + """ + } + } html_to_be_rendered = "${html_to_be_rendered} " diff --git a/jenkins_install/scriptler/scripts/MainOptions.groovy b/jenkins_install/scriptler/scripts/MainOptions.groovy index 7a31488b8..51dfadbe3 100644 --- a/jenkins_install/scriptler/scripts/MainOptions.groovy +++ b/jenkins_install/scriptler/scripts/MainOptions.groovy @@ -17,7 +17,7 @@ return[ "Logging Services", "Software-Defined Data Centers - OCVS", "CD3 Services", -"3rd Party Services" +"Other OCI Tools" ] } else if(Workflow.toLowerCase().contains("export")) { diff --git a/jenkins_install/scriptler/scripts/SubChildOptions.groovy b/jenkins_install/scriptler/scripts/SubChildOptions.groovy index 8491ef67c..6c7671ea2 100644 --- a/jenkins_install/scriptler/scripts/SubChildOptions.groovy +++ b/jenkins_install/scriptler/scripts/SubChildOptions.groovy @@ -5,6 +5,7 @@ List drg_route_rules = ["DRG ROUTE RULES:disabled","Export DRG Route Rule List nsg = ["NSGs:disabled","Export NSGs (From OCI into NSGs sheet)", "Add/Modify/Delete NSGs (Reads NSGs sheet)"] List cis = ["CIS:disabled","Download latest compliance checking script", "Execute compliance checking script"] List showoci = ["SHOW OCI:disabled","Download Latest ShowOCI Script", "Execute ShowOCI Script"] +List ocifsdr = ["OCI FSDR:disabled","Export DR Plan", "Update DR Plan"] List customer_connectivity = ["Connectivity:disabled","Create Remote Peering Connections"] List final_list = [] @@ -27,10 +28,13 @@ for (item in SubOptions.split(",")) { if (item.equals("ShowOCI Report")){ final_list += showoci } - if (item.equals("Add/Modify/Delete Firewall Policy")){ + if (item.equals("OCI FSDR")){ + final_list += ocifsdr + } + if (item.equals("Add/Modify/Delete Firewall Policy")){ final_list += firewall_policy } - if (item.equals("Customer Connectivity")){ + if (item.equals("Customer Connectivity")){ final_list += customer_connectivity } } diff --git a/jenkins_install/scriptler/scripts/SubOptions.groovy b/jenkins_install/scriptler/scripts/SubOptions.groovy index 60dd92fff..a5a67f9c8 100644 --- a/jenkins_install/scriptler/scripts/SubOptions.groovy +++ b/jenkins_install/scriptler/scripts/SubOptions.groovy @@ -14,7 +14,7 @@ List developer_services = ["DEVELOPER SERVICES:disabled","Add/Modify/Dele List security = ["SECURITY:disabled","Add/Modify/Delete KMS (Keys/Vaults)", "Enable Cloud Guard"] List logging_services = ["LOGGING SERVICES:disabled","Enable VCN Flow Logs", "Enable LBaaS Logs", "Enable Object Storage Buckets Logs", "Enable File Storage Logs", "Enable Network Firewall Logs"] List cd3_services = ["CD3 SERVICES:disabled","Fetch Compartments OCIDs to variables file", "Fetch Protocols to OCI_Protocols"] -List utility_services = ["3rd Party Services:disabled","CIS Compliance Check Script", "ShowOCI Report"] +List utility_services = ["Other OCI Tools:disabled","CIS Compliance Check Script", "ShowOCI Report", "OCI FSDR"] List ex_identity = ["IDENTITY:disabled","Export Compartments", "Export Groups", "Export Policies", "Export Users", "Export Network Sources"] List ex_governance = ["GOVERNANCE:disabled","Export Tags", "Export Quotas"] List ex_cost_management = ["COST MANAGEMENT:disabled","Export Budgets"] @@ -79,7 +79,7 @@ final_list += logging_services if (item.equals("CD3 Services")){ final_list += cd3_services } -if (item.equals("3rd Party Services")){ +if (item.equals("Other OCI Tools")){ final_list += utility_services } if (item.equals("Export Identity")){ diff --git a/jenkins_install/scriptler/scripts/ValidateParams.groovy b/jenkins_install/scriptler/scripts/ValidateParams.groovy index 428e68410..0f23d1c88 100644 --- a/jenkins_install/scriptler/scripts/ValidateParams.groovy +++ b/jenkins_install/scriptler/scripts/ValidateParams.groovy @@ -17,11 +17,11 @@ def validate_params(Workflow,MainOptions,SubOptions,SubChildOptions,AdditionalFi "Security":["Add/Modify/Delete KMS (Keys/Vaults)", "Enable Cloud Guard"], "Logging Services":["Enable VCN Flow Logs", "Enable LBaaS Logs", "Enable Object Storage Buckets Logs", "Enable File Storage Logs", "Enable Network Firewall Logs"], "CD3 Services":["Fetch Compartments OCIDs to variables file", "Fetch Protocols to OCI_Protocols"], - "3rd Party Services":["CIS Compliance Check Script", "ShowOCI Report"] + "Other OCI Tools":["CIS Compliance Check Script", "ShowOCI Report", "OCI FSDR"] ] def non_gf_options_map = [ "Export Identity":["Export Compartments", "Export Groups", "Export Policies", "Export Users", "Export Network Sources"], - "Export Governance":["Expot Tags", "Export Quotas"], + "Export Governance":["Export Tags", "Export Quotas"], "Export Cost Management":["Export Budgets"], "Export Network":["Export all Network Components", "Export Network components for VCNs/DRGs/DRGRouteRulesinOCI Tabs", "Export Network components for DHCP Tab", "Export Network components for SecRulesinOCI Tab", "Export Network components for RouteRulesinOCI Tab", "Export Network components for SubnetsVLANs Tab", "Export Network components for NSGs Tab"], "Export OCI Firewall":["Export Firewall Policy", "Export Firewall"], diff --git a/jenkins_install/setUpOCI_config.xml b/jenkins_install/setUpOCI_config.xml old mode 100755 new mode 100644 index b6435444f..eb3a166a6 --- a/jenkins_install/setUpOCI_config.xml +++ b/jenkins_install/setUpOCI_config.xml @@ -27,7 +27,7 @@ Excel_Template - Upload input Excel file. + Upload input Excel file for the services chosen. Previously uploaded file will be used if left empty. @@ -197,10 +197,10 @@ def generateStage(job) { if (values.size() > 1) { region = values[0] service = values[1] - job_name = "./terraform_files/${region}/${service}/terraform-apply".replace("//","/") + job_name = "./terraform_files/${region}/${service}/apply".replace("//","/") }else { region = values[0] - job_name = "./terraform_files/${region}/terraform-apply".replace("//","/") + job_name = "./terraform_files/${region}/apply".replace("//","/") } build job: "${job_name}" } @@ -285,7 +285,7 @@ pipeline { } environment { prop_file = "/cd3user/tenancies/${customer_prefix}/${customer_prefix}_setUpOCI.properties" - //current_timestamp = sh (script: 'date +%m-%d-%Y-%H-%M-%S', returnStdout: true).trim() + current_timestamp = sh (script: 'date +%s', returnStdout: true).trim() } parameters { stashedFile ( @@ -394,23 +394,50 @@ pipeline { ''' script { - // For latest CD3 XL file. - def latestXL = sh(returnStdout: true, script: ''' - set +x - ls -t /cd3user/tenancies/${customer_prefix}/*.xl* | head -n 1 - ''').trim() - + sh ''' + set +x + # For latest CD3 XL file. + latestXL=`ls -t /cd3user/tenancies/${customer_prefix}/*.xl* | head -n 1` echo "XL is ${latestXL}" - sh "rm -f *.xl*" - sh "cp '${latestXL}' ." + rm -f *.* + cp ${latestXL} . + # Check for cis_reports and show_oci directories + if [ -d "/cd3user/tenancies/${customer_prefix}/othertools_files/${customer_prefix}_cis_report" ]; then + last_modified=`stat -c "%Y" /cd3user/tenancies/${customer_prefix}/othertools_files/${customer_prefix}_cis_report` + if [ $(($last_modified-$current_timestamp)) -gt 0 ]; then + cp -r /cd3user/tenancies/${customer_prefix}/othertools_files/${customer_prefix}_cis_report . + tar -cf ${customer_prefix}_cis_report.zip ${customer_prefix}_cis_report/ + rm -rf ${customer_prefix}_cis_report + fi + fi + if [ -d "/cd3user/tenancies/${customer_prefix}/othertools_files/${customer_prefix}_showoci_report" ]; then + last_modified=`stat -c "%Y" /cd3user/tenancies/${customer_prefix}/othertools_files/${customer_prefix}_showoci_report` + if [ $(($last_modified-$current_timestamp)) -gt 0 ]; then + cp -r /cd3user/tenancies/${customer_prefix}/othertools_files/${customer_prefix}_showoci_report . + tar -cf ${customer_prefix}_showoci_report.zip ${customer_prefix}_showoci_report/ + rm -rf ${customer_prefix}_showoci_report + fi + fi + + # For latest oci_fsdr plan XL file. + count=`ls -1 /cd3user/tenancies/${customer_prefix}/othertools_files/*.xl* 2>/dev/null | wc -l` + if [ $count != 0 ]; then + latest_fsdr_XL=`ls -t /cd3user/tenancies/${customer_prefix}/othertools_files/*.xl* | head -n 1` + last_modified=`stat -c \"%Y\" ${latest_fsdr_XL}` + if [ $(($last_modified-$current_timestamp)) -gt 0 ]; then + cp ${latest_fsdr_XL} . + fi + fi + ''' } } } post { success { - archiveArtifacts '*.xl*' + archiveArtifacts '*.xl*, *.zip' + } } } @@ -470,7 +497,7 @@ pipeline { } } } - stage ('Trigger Terraform Pipelines'){ + stage ('Trigger Pipelines'){ when { allOf{ expression {return "${git_status}" > 0} diff --git a/jenkins_install/tf-destroy.groovy b/jenkins_install/tf-destroy.groovy deleted file mode 100644 index aa0ab8afa..000000000 --- a/jenkins_install/tf-destroy.groovy +++ /dev/null @@ -1,169 +0,0 @@ -/* Set the various stages of the build */ -def tf_plan = "Changes" - -pipeline { - agent any - options { - ansiColor('xterm') - } - stages { - stage('Set Environment Variables') { - steps { - script { - def fileContent = readFile "${JENKINS_HOME}/jenkins.properties" - // Split file content into lines - def lines = fileContent.readLines() - - // Process each line to extract variable name and value - def variables = [:] - lines.each { line -> - def parts = line.split('=') - if (parts.size() == 2) { - variables[parts[0].trim()] = parts[1].trim() - } - } - - def variableOds = variables['outdir_structure'].toString().replaceAll("\\[|\\]", '').replaceAll('"', '') - env.out_str = "${variableOds}" - def jobName = env.JOB_NAME - def parts = jobName.split('/') - if (env.out_str == 'Multiple_Outdir') { - // Assuming the job name format is /job//job/job_name - env.Region = parts[1] - env.Service = parts[2] - } - else { - // Assuming the job name format is /job/job_name - env.Region = parts[1] - env.Service = '' - if (env.Region == 'global') { - env.Service = 'rpc' - } - } - } - } - } - - stage('Terraform Destroy Plan') { - when { - expression { return env.GIT_BRANCH == 'origin/develop';} - } - - steps { - catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { - script { - - sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform init -upgrade" - // Run Terraform plan - terraformPlanOutput = sh(script: "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform plan -destroy", returnStdout: true).trim() - - // Check if the plan contains any changes - if (terraformPlanOutput.contains('No changes.')) { - echo 'No changes in Terraform plan. Skipping further stages.' - tf_plan = "No Changes" - } else { - // If there are changes, proceed with applying the plan - echo "Proceeding with destroy. \n${terraformPlanOutput}" - } - } - } - } - } - - /** Approval for Terraform Apply **/ - stage('Get Approval') { - when { - allOf { - expression {return env.GIT_BRANCH == 'origin/develop'; } - expression {return tf_plan == "Changes" } - expression {return currentBuild.result != "FAILURE" } - } - } - input { - message "Do you want to perform terraform destroy?" - } - steps { - echo "Approval for the Destroy Granted!" - } - } - - stage('Terraform Destroy') { - when { - allOf { - expression {return env.GIT_BRANCH == 'origin/develop'; } - expression {return tf_plan == "Changes" } - expression {return currentBuild.result != "FAILURE" } - } - } - - steps { - catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { - script { - sh "cd \"${WORKSPACE}/${env.Region}/${env.Service}\" && terraform destroy --auto-approve" - } - } - } - } - - /** Main branch commit to keep changes in Sync **/ - stage('Commit To Main') { - when { - allOf { - expression { return env.GIT_BRANCH == 'origin/develop'; } - expression { return tf_plan == "Changes" } - expression { return currentBuild.result != "FAILURE" } - } - } - steps { - catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { - script { - def buildDir = "${WORKSPACE}/${BUILD_NUMBER}" - // Create directory with build number - sh "mkdir -p ${buildDir}" - // Commit changes to the main branch - dir(buildDir) { - sh """ - git clone ${GIT_URL} - cd \$(ls -d */|head -n 1) - git checkout main - cd "${env.Region}/${env.Service}" - git pull --no-edit origin main - rm -f *.tfvars - git status - git add --all . - """ - - def git_status = false - while (!git_status) { - // Execute the git commands using shell - def gitResult = sh(script: """ - cd "\$(ls -d */|head -n 1)" - cd "${env.Region}/${env.Service}" - git fetch origin main - git merge origin/main - git commit -m "commit for terraform-destroy build - ${BUILD_NUMBER} for "${env.Region}"/"${env.Service} - - git push --porcelain origin main - """, returnStatus: true) - - if (gitResult == 0) { - git_status = true - } else { - echo "Git operation failed, retrying...." - sleep 3 // 3 seconds before retrying - } - } - } - } - } - } - - post { - always { - // Delete the build directory and the temporary directory - deleteDir() - } - } - } - } -} diff --git a/cd3_automation_toolkit/cis_reports.py b/othertools/cis_reports.py similarity index 94% rename from cd3_automation_toolkit/cis_reports.py rename to othertools/cis_reports.py index 8b0c1dda1..632c9c0a9 100644 --- a/cd3_automation_toolkit/cis_reports.py +++ b/othertools/cis_reports.py @@ -35,9 +35,9 @@ except Exception: OUTPUT_TO_XLSX = False -RELEASE_VERSION = "2.8.1" -PYTHON_SDK_VERSION = "2.124.1" -UPDATED_DATE = "March 25, 2024" +RELEASE_VERSION = "2.8.4" +PYTHON_SDK_VERSION = "2.129.4" +UPDATED_DATE = "July 26, 2024" ########################################################################## @@ -85,40 +85,11 @@ class CIS_Report: _DAYS_OLD = 90 __KMS_DAYS_OLD = 365 __home_region = [] + __days_to_expiry = 30 # Time Format __iso_time_format = "%Y-%m-%dT%H:%M:%S" - # OCI Link - __oci_cloud_url = "https://cloud.oracle.com" - __oci_users_uri = __oci_cloud_url + "/identity/users/" - __oci_policies_uri = __oci_cloud_url + "/identity/policies/" - __oci_groups_uri = __oci_cloud_url + "/identity/groups/" - __oci_dynamic_groups_uri = __oci_cloud_url + "/identity/dynamicgroups/" - __oci_identity_domains_uri = __oci_cloud_url + '/identity/domains/' - __oci_buckets_uri = __oci_cloud_url + "/object-storage/buckets/" - __oci_boot_volumes_uri = __oci_cloud_url + "/block-storage/boot-volumes/" - __oci_block_volumes_uri = __oci_cloud_url + "/block-storage/volumes/" - __oci_fss_uri = __oci_cloud_url + "/fss/file-systems/" - __oci_networking_uri = __oci_cloud_url + "/networking/vcns/" - __oci_adb_uri = __oci_cloud_url + "/db/adb/" - __oci_oicinstance_uri = __oci_cloud_url + "/oic/integration-instances/" - __oci_oacinstance_uri = __oci_cloud_url + "/analytics/instances/" - __oci_compartment_uri = __oci_cloud_url + "/identity/compartments/" - __oci_drg_uri = __oci_cloud_url + "/networking/drgs/" - __oci_cpe_uri = __oci_cloud_url + "/networking/cpes/" - __oci_ipsec_uri = __oci_cloud_url + "/networking/vpn-connections/" - __oci_events_uri = __oci_cloud_url + "/events/rules/" - __oci_loggroup_uri = __oci_cloud_url + "/logging/log-groups/" - __oci_vault_uri = __oci_cloud_url + "/security/kms/vaults/" - __oci_budget_uri = __oci_cloud_url + "/usage/budgets/" - __oci_cgtarget_uri = __oci_cloud_url + "/cloud-guard/targets/" - __oci_onssub_uri = __oci_cloud_url + "/notification/subscriptions/" - __oci_serviceconnector_uri = __oci_cloud_url + "/connector-hub/service-connectors/" - __oci_fastconnect_uri = __oci_cloud_url + "/networking/fast-connect/virtual-circuit/" - __oci_instances_uri = __oci_cloud_url + "/compute/instances/" - - __oci_ocid_pattern = r'ocid1\.[a-z,0-9]*\.[a-z,0-9]*\.[a-z,0-9,-]*\.[a-z,0-9,\.]{20,}' # Start print time info @@ -137,8 +108,14 @@ class CIS_Report: datetime.timedelta(days=__KMS_DAYS_OLD) str_kms_key_time_max_datetime = kms_key_time_max_datetime.strftime(__iso_time_format) kms_key_time_max_datetime = datetime.datetime.strptime(str_kms_key_time_max_datetime, __iso_time_format) + # For Certificates Check + cert_key_time_max_datetime = start_datetime + \ + datetime.timedelta(days=__days_to_expiry) + str_cert_key_time_max_datetime = cert_key_time_max_datetime.strftime(__iso_time_format) + cert_key_time_max_datetime = datetime.datetime.strptime(str_cert_key_time_max_datetime, __iso_time_format) + - def __init__(self, config, signer, proxy, output_bucket, report_directory, report_prefix, report_summary_json, print_to_screen, regions_to_run_in, raw_data, obp, redact_output, debug=False, all_resources=True): + def __init__(self, config, signer, proxy, output_bucket, report_directory, report_prefix, report_summary_json, print_to_screen, regions_to_run_in, raw_data, obp, redact_output, oci_url=None, debug=False, all_resources=True): # CIS Foundation benchmark 2.0.0 self.cis_foundations_benchmark_2_0 = { @@ -185,7 +162,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor '4.12': {'section': 'Logging and Monitoring', 'recommendation_#': '4.12', 'Title': 'Ensure a notification is configured for changes to network gateways.', 'Status': False, 'Level': 1, 'Total': [], 'Findings': [], 'CISv8': ['4.2'], 'CCCS Guard Rail': '11', 'Remediation': []}, '4.13': {'section': 'Logging and Monitoring', 'recommendation_#': '4.13', 'Title': 'Ensure VCN flow logging is enabled for all subnets.', 'Status': True, 'Level': 2, 'Total': [], 'Findings': [], 'CISv8': ['8.2', '8.5', '13.6'], 'CCCS Guard Rail': '', 'Remediation': []}, '4.14': {'section': 'Logging and Monitoring', 'recommendation_#': '4.14', 'Title': 'Ensure Cloud Guard is enabled in the root compartment of the tenancy.', 'Status': True, 'Level': 1, 'Total': [], 'Findings': [], 'CISv8': ['8.2', '8.5', '8.11'], 'CCCS Guard Rail': '1,2,3', 'Remediation': []}, - '4.15': {'section': 'Logging and Monitoring', 'recommendation_#': '4.15', 'Title': 'Ensure a notification is configured for Oracle Cloud Guard problems detected.', 'Status': True, 'Level': 2, 'Total': [], 'Findings': [], 'CISv8': ['8.2', '8.11'], 'CCCS Guard Rail': '', 'Remediation': []}, + '4.15': {'section': 'Logging and Monitoring', 'recommendation_#': '4.15', 'Title': 'Ensure a notification is configured for Oracle Cloud Guard problems detected.', 'Status': False, 'Level': 2, 'Total': [], 'Findings': [], 'CISv8': ['8.2', '8.11'], 'CCCS Guard Rail': '', 'Remediation': []}, '4.16': {'section': 'Logging and Monitoring', 'recommendation_#': '4.16', 'Title': 'Ensure customer created Customer Managed Key (CMK) is rotated at least annually.', 'Status': True, 'Level': 1, 'Total': [], 'Findings': [], 'CISv8': [], 'CCCS Guard Rail': '6,7', 'Remediation': []}, '4.17': {'section': 'Logging and Monitoring', 'recommendation_#': '4.17', 'Title': 'Ensure write level Object Storage logging is enabled for all buckets.', 'Status': True, 'Level': 2, 'Total': [], 'Findings': [], 'CISv8': ['8.2'], 'CCCS Guard Rail': '', 'Remediation': []}, @@ -431,7 +408,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Create a Rule Condition in the Events services by selecting Identity in the Service Name Drop-down and selecting Identity Provider – Create, Identity Provider - Delete and Identity Provider – Update. In the Actions section select Notifications as Action Type and selct the compartment and topic to be used.", "Recommendation": "", - "Observation": "notification has been configured for Identity Provider changes." + "Observation": "notifications have been configured for Identity Provider changes." }, "4.4": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when Identity Provider Group Mappings are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments. It is recommended to create the Event rule at the root compartment level", @@ -439,7 +416,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Find and click the Rule that handles Idp Group Mapping Changes. Click the Edit Rule button and verify that the RuleConditions section contains a condition for the Service Identity and Event Types: Idp Group Mapping – Create, Idp Group Mapping – Delete, and Idp Group Mapping – Update and confirm Action Type contains: Notifications and that a valid Topic is referenced.", "Recommendation": "", - "Observation": "notification has been configured for Identity Provider Group Mapping changes." + "Observation": "notifications have been configured for Identity Provider Group Mapping changes." }, "4.5": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when IAM Groups are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -447,7 +424,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Create a Rule Condition by selecting Identity in the Service Name Drop-down and selecting Group – Create, Group – Delete and Group – Update. In the Actions section select Notifications as Action Type and selct the compartment and topic to be used.", "Recommendation": "", - "Observation": "notification has been configured for Identity Provider changes." + "Observation": "notifications have been configured for IAM Group changes." }, "4.6": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when IAM Policies are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -455,7 +432,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Create a Rule Condition by selecting Identity in the Service Name Drop-down and selecting Policy – Change Compartment, Policy – Create, Policy - Delete and Policy – Update. In the Actions section select Notifications as Action Type and selct the compartment and topic to be used.", "Recommendation": "", - "Observation": "notification has been configured for IAM Policy changes." + "Observation": "notifications have been configured for IAM Policy changes." }, "4.7": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when IAM Users are created, updated, deleted, capabilities updated, or state updated. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -463,7 +440,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Edit Rule that handles IAM User Changes and verify that the Rule Conditions section contains a condition for the Service Identity and Event Types: User – Create, User – Delete, User – Update, User Capabilities – Update, User State – Update.", "Recommendation": "", - "Observation": "notification has been configured for user changes." + "Observation": "notifications have been configured for user changes." }, "4.8": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when Virtual Cloud Networks are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -471,7 +448,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Edit Rule that handles VCN Changes and verify that the RuleConditions section contains a condition for the Service Networking and Event Types: VCN – Create, VCN - Delete, and VCN – Update.", "Recommendation": "", - "Observation": "notification has been configured for VCN changes." + "Observation": "notifications have been configured for VCN changes." }, "4.9": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when route tables are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -479,7 +456,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Edit Rule that handles Route Table Changes and verify that the RuleConditions section contains a condition for the Service Networking and Event Types: Route Table – Change Compartment, Route Table – Create, Route Table - Delete, and Route Table – Update.", "Recommendation": "", - "Observation": "notification has been configured for changes to route tables." + "Observation": "notifications have been configured for changes to route tables." }, "4.10": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when security lists are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -487,7 +464,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Edit Rule that handles Security List Changes and verify that the RuleConditions section contains a condition for the Service Networking and Event Types: Security List – Change Compartment, Security List – Create, Security List - Delete, and Security List – Update.", "Recommendation": "", - "Observation": "notification has been configured for security list changes." + "Observation": "notifications have been configured for security list changes." }, "4.11": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when network security groups are created, updated or deleted. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -495,7 +472,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Edit Rule that handles Network Security Group changes and verify that the RuleConditions section contains a condition for the Service Networking and Event Types: Network Security Group – Change Compartment, Network Security Group – Create, Network Security Group - Delete, and Network Security Group – Update.", "Recommendation": "", - "Observation": "notification has been configured for changes on Network Service Groups." + "Observation": "notifications have been configured for changes on Network Service Groups." }, "4.12": { "Description": "It is recommended to setup an Event Rule and Notification that gets triggered when Network Gateways are created, updated, deleted, attached, detached, or moved. This recommendation includes Internet Gateways, Dynamic Routing Gateways, Service Gateways, Local Peering Gateways, and NAT Gateways. Event Rules are compartment scoped and will detect events in child compartments, it is recommended to create the Event rule at the root compartment level.", @@ -503,7 +480,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Edit Rule that handles Network Gateways Changes and verify that the RuleConditions section contains a condition for the Service Networking and Event Types: DRG – Create, DRG - Delete, DRG - Update, DRG Attachment – Create, DRG Attachment – Delete, DRG Attachment - Update, Internet Gateway – Create, Internet Gateway – Delete, Internet Gateway - Update, Internet Gateway – Change Compartment, Local Peering Gateway – Create, Local Peering Gateway – Delete End, Local Peering Gateway - Update, Local Peering Gateway – Change Compartment, NAT Gateway – Create, NAT Gateway – Delete, NAT Gateway - Update, NAT Gateway – Change Compartment,Compartment, Service Gateway – Create, Service Gateway – Delete Begin, Service Gateway – Delete End, Service Gateway – Update, Service Gateway – Attach Service, Service Gateway – Detach Service, Service Gateway – Change Compartment.", "Recommendation": "", - "Observation": "notification has been configured for changes on network gateways." + "Observation": "notifications have been configured for changes on network gateways." }, "4.13": { "Description": "VCN flow logs record details about traffic that has been accepted or rejected based on the security list rule.", @@ -527,7 +504,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor "Impact": "There is no performance impact when enabling the above described features but depending on the amount of notifications sent per month there may be a cost associated.", "Remediation": "Create a Rule Condition by selecting Cloud Guard in the Service Name Drop-down and selecting Detected – Problem, Remediated – Problem and Dismissed - Problem. In the Actions section select Notifications as Action Type and selct the compartment and topic to be used.", "Recommendation": "", - "Observation": "notification has been configured for Cloud Guard Problems" + "Observation": "notifications have been configured for Cloud Guard Problems." }, "4.16": { "Description": "Oracle Cloud Infrastructure Vault securely stores master encryption keys that protect your encrypted data. You can use the Vault service to rotate keys to generate new cryptographic material. Periodically rotating keys limits the amount of data encrypted by one key version.", @@ -611,7 +588,7 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor } } - # MAP Checks + # OBP Checks self.obp_foundations_checks = { 'Cost_Tracking_Budgets': {'Status': False, 'Findings': [], 'OBP': [], "Documentation": "https://docs.oracle.com/en-us/iaas/Content/Billing/Concepts/budgetsoverview.htm#Budgets_Overview"}, 'SIEM_Audit_Log_All_Comps': {'Status': True, 'Findings': [], 'OBP': [], "Documentation": "https://docs.oracle.com/en/solutions/oci-aggregate-logs-siem/index.html"}, # Assuming True @@ -621,63 +598,66 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor 'SIEM_Read_Bucket_Logs': {'Status': None, 'Findings': [], 'OBP': [], "Documentation": "https://docs.oracle.com/en/solutions/oci-aggregate-logs-siem/index.html"}, 'Networking_Connectivity': {'Status': True, 'Findings': [], 'OBP': [], "Documentation": "https://docs.oracle.com/en-us/iaas/Content/Network/Troubleshoot/drgredundancy.htm"}, 'Cloud_Guard_Config': {'Status': None, 'Findings': [], 'OBP': [], "Documentation": "https://www.ateam-oracle.com/post/tuning-oracle-cloud-guard"}, + 'Certificates_Near_Expiry': {'Status': None, 'Findings': [], 'OBP': [], "Documentation": "TBD"}, } - # MAP Regional Data + # CIS and OBP Regional Data + # 4.6 is not regional because OCI IAM Policies only exist in the home region + self.__cis_regional_checks = {"4.3","4.4","4.5","4.7", "4.8", "4.9", "4.10", "4.11", "4.12"} self.__obp_regional_checks = {} # CIS monitoring notifications check self.cis_monitoring_checks = { - "4.4": [ + "4.3": [ 'com.oraclecloud.identitycontrolplane.createidentityprovider', 'com.oraclecloud.identitycontrolplane.deleteidentityprovider', 'com.oraclecloud.identitycontrolplane.updateidentityprovider' ], - "4.5": [ + "4.4": [ 'com.oraclecloud.identitycontrolplane.createidpgroupmapping', 'com.oraclecloud.identitycontrolplane.deleteidpgroupmapping', 'com.oraclecloud.identitycontrolplane.updateidpgroupmapping' ], - "4.6": [ + "4.5": [ 'com.oraclecloud.identitycontrolplane.creategroup', 'com.oraclecloud.identitycontrolplane.deletegroup', 'com.oraclecloud.identitycontrolplane.updategroup' ], - "4.7": [ + "4.6": [ 'com.oraclecloud.identitycontrolplane.createpolicy', 'com.oraclecloud.identitycontrolplane.deletepolicy', 'com.oraclecloud.identitycontrolplane.updatepolicy' ], - "4.8": [ + "4.7": [ 'com.oraclecloud.identitycontrolplane.createuser', 'com.oraclecloud.identitycontrolplane.deleteuser', 'com.oraclecloud.identitycontrolplane.updateuser', 'com.oraclecloud.identitycontrolplane.updateusercapabilities', 'com.oraclecloud.identitycontrolplane.updateuserstate' ], - "4.9": [ + "4.8": [ 'com.oraclecloud.virtualnetwork.createvcn', 'com.oraclecloud.virtualnetwork.deletevcn', 'com.oraclecloud.virtualnetwork.updatevcn' ], - "4.10": [ + "4.9": [ 'com.oraclecloud.virtualnetwork.changeroutetablecompartment', 'com.oraclecloud.virtualnetwork.createroutetable', 'com.oraclecloud.virtualnetwork.deleteroutetable', 'com.oraclecloud.virtualnetwork.updateroutetable' ], - "4.11": [ + "4.10": [ 'com.oraclecloud.virtualnetwork.changesecuritylistcompartment', 'com.oraclecloud.virtualnetwork.createsecuritylist', 'com.oraclecloud.virtualnetwork.deletesecuritylist', 'com.oraclecloud.virtualnetwork.updatesecuritylist' ], - "4.12": [ + "4.11": [ 'com.oraclecloud.virtualnetwork.changenetworksecuritygroupcompartment', 'com.oraclecloud.virtualnetwork.createnetworksecuritygroup', 'com.oraclecloud.virtualnetwork.deletenetworksecuritygroup', 'com.oraclecloud.virtualnetwork.updatenetworksecuritygroup' ], - "4.13": [ + "4.12": [ 'com.oraclecloud.virtualnetwork.createdrg', 'com.oraclecloud.virtualnetwork.deletedrg', 'com.oraclecloud.virtualnetwork.updatedrg', @@ -844,6 +824,8 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor # Compute Resources - Thinking about self.__Instance = [] + # Certificates raw resources + self.__raw_oci_certificates = [] # Setting list of regions to run in # Start print time info @@ -991,6 +973,40 @@ def __init__(self, config, signer, proxy, output_bucket, report_directory, repor self.__obp_checks = True self.__output_raw_data = True + # Determine if __oci_cloud_url will be override with a different realm ex. OC2 or sovreign region + self.__oci_cloud_url = "https://cloud.oracle.com" + if oci_url: + self.__oci_cloud_url = oci_url + + # OCI Link + self.__oci_users_uri = self.__oci_cloud_url + "/identity/users/" + self.__oci_policies_uri = self.__oci_cloud_url + "/identity/policies/" + self.__oci_groups_uri = self.__oci_cloud_url + "/identity/groups/" + self.__oci_dynamic_groups_uri = self.__oci_cloud_url + "/identity/dynamicgroups/" + self.__oci_identity_domains_uri = self.__oci_cloud_url + '/identity/domains/' + self.__oci_buckets_uri = self.__oci_cloud_url + "/object-storage/buckets/" + self.__oci_boot_volumes_uri = self.__oci_cloud_url + "/block-storage/boot-volumes/" + self.__oci_block_volumes_uri = self.__oci_cloud_url + "/block-storage/volumes/" + self.__oci_fss_uri = self.__oci_cloud_url + "/fss/file-systems/" + self.__oci_networking_uri = self.__oci_cloud_url + "/networking/vcns/" + self.__oci_adb_uri = self.__oci_cloud_url + "/db/adb/" + self.__oci_oicinstance_uri = self.__oci_cloud_url + "/oic/integration-instances/" + self.__oci_oacinstance_uri = self.__oci_cloud_url + "/analytics/instances/" + self.__oci_compartment_uri = self.__oci_cloud_url + "/identity/compartments/" + self.__oci_drg_uri = self.__oci_cloud_url + "/networking/drgs/" + self.__oci_cpe_uri = self.__oci_cloud_url + "/networking/cpes/" + self.__oci_ipsec_uri = self.__oci_cloud_url + "/networking/vpn-connections/" + self.__oci_events_uri = self.__oci_cloud_url + "/events/rules/" + self.__oci_loggroup_uri = self.__oci_cloud_url + "/logging/log-groups/" + self.__oci_vault_uri = self.__oci_cloud_url + "/security/kms/vaults/" + self.__oci_budget_uri = self.__oci_cloud_url + "/usage/budgets/" + self.__oci_cgtarget_uri = self.__oci_cloud_url + "/cloud-guard/targets/" + self.__oci_onssub_uri = self.__oci_cloud_url + "/notification/subscriptions/" + self.__oci_serviceconnector_uri = self.__oci_cloud_url + "/connector-hub/service-connectors/" + self.__oci_fastconnect_uri = self.__oci_cloud_url + "/networking/fast-connect/virtual-circuit/" + self.__oci_instances_uri = self.__oci_cloud_url + "/compute/instances/" + self.__oci_cert_uri = self.__oci_cloud_url + "security/certificates/certificate/" + ########################################################################## # Create regional config, signers adds appends them to self.__regions object ########################################################################## @@ -1097,6 +1113,11 @@ def __create_regional_signers(self, proxy): instance.base_client.session.proxies = {'https': proxy} region_values['instance'] = instance + certificate_client = oci.certificates_management.CertificatesManagementClient(region_config, signer=region_signer) + if proxy: + search.base_client.session.proxies = {'https': proxy} + region_values['certificate_client'] = certificate_client + except Exception as e: debug("__create_regional_signers: error reading" + str(self.__config)) self.__errors.append({"id" : "__create_regional_signers", "error" : str(e)}) @@ -1362,13 +1383,13 @@ def __identity_read_groups_and_membership(self): ########################################################################## def __identity_domains_get_all_results(self, func, args): - if not 'start_index' in args: + if "start_index" not in args: args['start_index'] = 1 - if not "count" in args: + if "count" not in args: args["count"] = 1000 - if not "filter" in args: + if "filter" not in args: args["filter"] = '' - if not "attribute_sets" in args: + if "attribute_sets" not in args: args["attribute_sets"] = ['all'] debug("__identity_domains_get_all_results: " + str(func.__name__) + " arguments are: " + str(args)) @@ -2645,7 +2666,7 @@ def __network_read_ip_sec_connections(self): self.__network_ipsec_connections[ip_sec.additional_details['drgId']] = [] self.__network_ipsec_connections[ip_sec.additional_details['drgId']].append(record) - print("\tProcessed " + str(len((list(itertools.chain.from_iterable(self.__network_ipsec_connections.values()))))) + " IP SEC Conenctions") + print("\tProcessed " + str(len((list(itertools.chain.from_iterable(self.__network_ipsec_connections.values()))))) + " IP SEC Connections") return self.__network_ipsec_connections except Exception as e: raise RuntimeError( @@ -2656,7 +2677,7 @@ def __network_read_ip_sec_connections(self): ############################################ def __network_topology_dump(self): debug("__network_topology_dump: Starting") - if type(self.__signer) == oci.auth.signers.InstancePrincipalsDelegationTokenSigner: + if type(self.__signer) is not oci.auth.signers.InstancePrincipalsDelegationTokenSigner: self.__errors.append({"id": "__network_topology_dump", "error": "Delegated Tokens via Cloud Shell not supported." }) return def api_function(region_key, region_values, tenancy_id): @@ -2695,6 +2716,7 @@ def __adb_read_adbs(self): try: for region_key, region_values in self.__regions.items(): # UPDATED JB + #adb_query_resources = self.__search_query_resource_type("AutonomousDatabase", region_values['search_client']) adb_query_resources = oci.pagination.list_call_get_all_results( region_values['search_client'].search_resources, search_details=oci.resource_search.models.StructuredSearchDetails( @@ -2702,7 +2724,6 @@ def __adb_read_adbs(self): ).data compartments = set() - for adb in adb_query_resources: compartments.add(adb.compartment_id) @@ -2711,268 +2732,33 @@ def __adb_read_adbs(self): region_values['adb_client'].list_autonomous_databases, compartment_id=compartment ).data + # autonomous_databases = region_values['adb_client'].list_autonomous_databases( + # compartment_id=compartment + # ).data for adb in autonomous_databases: try: deep_link = self.__oci_adb_uri + adb.id + '?region=' + region_key # Issue 295 fixed if adb.lifecycle_state not in [ oci.database.models.AutonomousDatabaseSummary.LIFECYCLE_STATE_TERMINATED, oci.database.models.AutonomousDatabaseSummary.LIFECYCLE_STATE_TERMINATING, oci.database.models.AutonomousDatabaseSummary.LIFECYCLE_STATE_UNAVAILABLE ]: - record = { - "id": adb.id, - "display_name": adb.display_name, - "deep_link": self.__generate_csv_hyperlink(deep_link, adb.display_name), - "apex_details": adb.apex_details, - "are_primary_whitelisted_ips_used": adb.are_primary_whitelisted_ips_used, - "autonomous_container_database_id": adb.autonomous_container_database_id, - "autonomous_maintenance_schedule_type": adb.autonomous_maintenance_schedule_type, - "available_upgrade_versions": adb.available_upgrade_versions, - "backup_config": adb.backup_config, - "compartment_id": adb.compartment_id, - "connection_strings": adb.connection_strings, - "connection_urls": adb.connection_urls, - "cpu_core_count": adb.cpu_core_count, - "customer_contacts": adb.cpu_core_count, - "data_safe_status": adb.data_safe_status, - "data_storage_size_in_gbs": adb.data_storage_size_in_gbs, - "data_storage_size_in_tbs": adb.data_storage_size_in_tbs, - "database_management_status": adb.database_management_status, - "dataguard_region_type": adb.dataguard_region_type, - "db_name": adb.db_name, - "db_version": adb.db_version, - "db_workload": adb.db_workload, - "defined_tags": adb.defined_tags, - "failed_data_recovery_in_seconds": adb.failed_data_recovery_in_seconds, - "freeform_tags": adb.freeform_tags, - "infrastructure_type": adb.infrastructure_type, - "is_access_control_enabled": adb.is_access_control_enabled, - "is_auto_scaling_enabled": adb.is_auto_scaling_enabled, - "is_data_guard_enabled": adb.is_data_guard_enabled, - "is_dedicated": adb.is_dedicated, - "is_free_tier": adb.is_free_tier, - "is_mtls_connection_required": adb.is_mtls_connection_required, - "is_preview": adb.is_preview, - "is_reconnect_clone_enabled": adb.is_reconnect_clone_enabled, - "is_refreshable_clone": adb.is_refreshable_clone, - "key_history_entry": adb.key_history_entry, - "key_store_id": adb.key_store_id, - "key_store_wallet_name": adb.key_store_wallet_name, - "kms_key_id": adb.kms_key_id, - "kms_key_lifecycle_details": adb.kms_key_lifecycle_details, - "kms_key_version_id": adb.kms_key_version_id, - "license_model": adb.license_model, - "lifecycle_details": adb.lifecycle_details, - "lifecycle_state": adb.lifecycle_state, - "nsg_ids": adb.nsg_ids, - "ocpu_count": adb.ocpu_count, - "open_mode": adb.open_mode, - "operations_insights_status": adb.operations_insights_status, - "peer_db_ids": adb.peer_db_ids, - "permission_level": adb.permission_level, - "private_endpoint": adb.private_endpoint, - "private_endpoint_ip": adb.private_endpoint_ip, - "private_endpoint_label": adb.private_endpoint_label, - "refreshable_mode": adb.refreshable_mode, - "refreshable_status": adb.refreshable_status, - "role": adb.role, - "scheduled_operations": adb.scheduled_operations, - "service_console_url": adb.service_console_url, - "source_id": adb.source_id, - "standby_whitelisted_ips": adb.standby_whitelisted_ips, - "subnet_id": adb.subnet_id, - "supported_regions_to_clone_to": adb.supported_regions_to_clone_to, - "system_tags": adb.system_tags, - "time_created": adb.time_created.strftime(self.__iso_time_format), - "time_data_guard_role_changed": str(adb.time_data_guard_role_changed), - "time_deletion_of_free_autonomous_database": str(adb.time_deletion_of_free_autonomous_database), - "time_local_data_guard_enabled": str(adb.time_local_data_guard_enabled), - "time_maintenance_begin": str(adb.time_maintenance_begin), - "time_maintenance_end": str(adb.time_maintenance_end), - "time_of_last_failover": str(adb.time_of_last_failover), - "time_of_last_refresh": str(adb.time_of_last_refresh), - "time_of_last_refresh_point": str(adb.time_of_last_refresh_point), - "time_of_last_switchover": str(adb.time_of_last_switchover), - "time_of_next_refresh": str(adb.time_of_next_refresh), - "time_reclamation_of_free_autonomous_database": str(adb.time_reclamation_of_free_autonomous_database), - "time_until_reconnect_clone_enabled": str(adb.time_until_reconnect_clone_enabled), - "used_data_storage_size_in_tbs": str(adb.used_data_storage_size_in_tbs), - "vault_id": adb.vault_id, - "whitelisted_ips": adb.whitelisted_ips, - "region": region_key, - "notes": "" - } + record = oci.util.to_dict(adb) + record['deep_link'] = self.__generate_csv_hyperlink(deep_link, adb.display_name) + record['error'] = "" + self.__autonomous_databases.append(record) else: - record = { - "id": adb.id, - "display_name": adb.display_name, - "deep_link": self.__generate_csv_hyperlink(deep_link, adb.display_name), - "apex_details": "", - "are_primary_whitelisted_ips_used": "", - "autonomous_container_database_id": "", - "autonomous_maintenance_schedule_type": "", - "available_upgrade_versions": "", - "backup_config": "", - "compartment_id": adb.compartment_id, - "connection_strings": "", - "connection_urls": "", - "cpu_core_count": "", - "customer_contacts": "", - "data_safe_status": "", - "data_storage_size_in_gbs": "", - "data_storage_size_in_tbs": "", - "database_management_status": "", - "dataguard_region_type": "", - "db_name": "", - "db_version": "", - "db_workload": "", - "defined_tags": "", - "failed_data_recovery_in_seconds": "", - "freeform_tags": "", - "infrastructure_type": "", - "is_access_control_enabled": "", - "is_auto_scaling_enabled": "", - "is_data_guard_enabled": "", - "is_dedicated": "", - "is_free_tier": "", - "is_mtls_connection_required": "", - "is_preview": "", - "is_reconnect_clone_enabled": "", - "is_refreshable_clone": "", - "key_history_entry": "", - "key_store_id": "", - "key_store_wallet_name": "", - "kms_key_id": "", - "kms_key_lifecycle_details": "", - "kms_key_version_id": "", - "license_model": "", - "lifecycle_details": "", - "lifecycle_state": adb.lifecycle_state, - "nsg_ids": "", - "ocpu_count": "", - "open_mode": "", - "operations_insights_status": "", - "peer_db_ids": "", - "permission_level": "", - "private_endpoint": "", - "private_endpoint_ip": "", - "private_endpoint_label": "", - "refreshable_mode": "", - "refreshable_status": "", - "role": "", - "scheduled_operations": "", - "service_console_url": "", - "source_id": "", - "standby_whitelisted_ips": "", - "subnet_id": "", - "supported_regions_to_clone_to": "", - "system_tags": "", - "time_created": "", - "time_data_guard_role_changed": "", - "time_deletion_of_free_autonomous_database": "", - "time_local_data_guard_enabled": "", - "time_maintenance_begin": "", - "time_maintenance_end": "", - "time_of_last_failover": "", - "time_of_last_refresh": "", - "time_of_last_refresh_point": "", - "time_of_last_switchover": "", - "time_of_next_refresh": "", - "time_reclamation_of_free_autonomous_database": "", - "time_until_reconnect_clone_enabled": "", - "used_data_storage_size_in_tbs": "", - "vault_id": "", - "whitelisted_ips": "", - "region": region_key, - "notes": "" - } + record = record = oci.util.to_dict(adb) + record['deep_link'] = self.__generate_csv_hyperlink(deep_link, adb.display_name) + record['error'] = "" + self.__autonomous_databases.append(record) except Exception as e: - record = { - "id": "", - "display_name": "", - "deep_link": "", - "apex_details": "", - "are_primary_whitelisted_ips_used": "", - "autonomous_container_database_id": "", - "autonomous_maintenance_schedule_type": "", - "available_upgrade_versions": "", - "backup_config": "", - "compartment_id": "", - "connection_strings": "", - "connection_urls": "", - "cpu_core_count": "", - "customer_contacts": "", - "data_safe_status": "", - "data_storage_size_in_gbs": "", - "data_storage_size_in_tbs": "", - "database_management_status": "", - "dataguard_region_type": "", - "db_name": "", - "db_version": "", - "db_workload": "", - "defined_tags": "", - "failed_data_recovery_in_seconds": "", - "freeform_tags": "", - "infrastructure_type": "", - "is_access_control_enabled": "", - "is_auto_scaling_enabled": "", - "is_data_guard_enabled": "", - "is_dedicated": "", - "is_free_tier": "", - "is_mtls_connection_required": "", - "is_preview": "", - "is_reconnect_clone_enabled": "", - "is_refreshable_clone": "", - "key_history_entry": "", - "key_store_id": "", - "key_store_wallet_name": "", - "kms_key_id": "", - "kms_key_lifecycle_details": "", - "kms_key_version_id": "", - "license_model": "", - "lifecycle_details": "", - "lifecycle_state": "", - "nsg_ids": "", - "ocpu_count": "", - "open_mode": "", - "operations_insights_status": "", - "peer_db_ids": "", - "permission_level": "", - "private_endpoint": "", - "private_endpoint_ip": "", - "private_endpoint_label": "", - "refreshable_mode": "", - "refreshable_status": "", - "role": "", - "scheduled_operations": "", - "service_console_url": "", - "source_id": "", - "standby_whitelisted_ips": "", - "subnet_id": "", - "supported_regions_to_clone_to": "", - "system_tags": "", - "time_created": "", - "time_data_guard_role_changed": "", - "time_deletion_of_free_autonomous_database": "", - "time_local_data_guard_enabled": "", - "time_maintenance_begin": "", - "time_maintenance_end": "", - "time_of_last_failover": "", - "time_of_last_refresh": "", - "time_of_last_refresh_point": "", - "time_of_last_switchover": "", - "time_of_next_refresh": "", - "time_reclamation_of_free_autonomous_database": "", - "time_until_reconnect_clone_enabled": "", - "used_data_storage_size_in_tbs": "", - "vault_id": "", - "whitelisted_ips": "", - "region": region_key, - "notes": str(e) - } - self.__autonomous_databases.append(record) + record = record['deep_link'] = self.__generate_csv_hyperlink(deep_link, adb.display_name) + record['error'] = str(e) + self.__autonomous_databases.append(record) print("\tProcessed " + str(len(self.__autonomous_databases)) + " Autonomous Databases") return self.__autonomous_databases except Exception as e: - raise RuntimeError("Error in __adb_read_adbs " + str(e.args)) + print("Error in __adb_read_adbs " + str(e.args)) + self.__errors.append({'id' : '__adb_read_adbs', 'error' : str(e)}) ############################################ # Load Oracle Integration Cloud @@ -3138,6 +2924,7 @@ def __events_read_event_rules(self): record = { "compartment_id": event_rule.compartment_id, "condition": event_rule.additional_details['condition'], + "actions": event_rule.additional_details['actionsDetails'], "description": event_rule.additional_details['description'], "display_name": event_rule.display_name, "deep_link": self.__generate_csv_hyperlink(deep_link, event_rule.display_name), @@ -3306,7 +3093,7 @@ def __kms_read_keys(self): wrapping_key_id = self.__vaults[vault]['kms_client'].get_wrapping_key().data.id debug("\t__kms_read_keys: Succeeded Adding Wrapping Key Id: " + str(wrapping_key_id)) self.__vaults[vault]['wrapping_key_id'] = wrapping_key_id - except Exception as e: + except Exception: debug("\t__kms_read_keys: Failed Adding Wrapping Key Id for vault: " + str(vault)) self.__vaults[vault]['wrapping_key_id'] = None @@ -3506,6 +3293,7 @@ def __identity_read_tenancy_password_policy(self): # Oracle Notifications Services for Subscriptions ########################################################################## def __ons_read_subscriptions(self): + debug("__ons_read_subscriptions: Starting: ") try: for region_key, region_values in self.__regions.items(): # Iterate through compartments to get all subscriptions @@ -3514,7 +3302,7 @@ def __ons_read_subscriptions(self): search_details=oci.resource_search.models.StructuredSearchDetails( query="query OnsSubscription resources return allAdditionalFields where compartmentId != '" + self.__managed_paas_compartment_id + "'") ).data - + debug("\t__ons_read_subscriptions: Recieved " + str(len(subs_data)) + " subscriptions in region " + str(region_key)) for sub in subs_data: deep_link = self.__oci_onssub_uri + sub.identifier + '?region=' + region_key record = { @@ -3570,9 +3358,8 @@ def __identity_read_tag_defaults(self): return self.__tag_defaults except Exception as e: - raise RuntimeError( - "Error in __identity_read_tag_defaults " + str(e.args)) - + print("Error in __identity_read_tag_defaults " + str(e.args)) + self.__errors.append({'id' : '__identity_read_tag_defaults', 'error' : str(e)}) ########################################################################## # Get Service Connectors ########################################################################## @@ -3690,7 +3477,7 @@ def __search_resources_in_root_compartment(self): "region": region_key } self.cis_foundations_benchmark_2_0['6.2']['Total'].append(record) - except: + except Exception: self.__errors.append({"id": "search_resources_in_root_compartment Invalid OCID", "error" : str(item)}) debug(f'__search_resources_in_root_compartment: Invalid OCID: {str(item)}') @@ -3715,7 +3502,8 @@ def __search_query_resource_type(self, resource_type, search_client): ).data return oci.util.to_dict(results) - except Exception as e: + except Exception: + debug("__search_query_resource_type: failed to get type: " + str(resource_type)) return [] ########################################################################## @@ -3782,11 +3570,71 @@ def __core_instance_read_compute(self): raise RuntimeError("Error in __core_instance_read_compute " + str(e.args)) + ########################################################################## + # Returns a region name for a region key + # Takes: region key + ########################################################################## + def __get_region_name_from_key(self,region_key): + debug("__get_region_name_from_key") + for key, region_values in self.__regions.items(): + if region_values['region_key'].upper() == region_key.upper() or region_values['region_name'].upper() == region_key.upper(): + return region_values['region_name'] + + ########################################################################## + # Query All certificates in the tenancy + ########################################################################## + def __certificates_read_certificates(self): + debug("__certificates_read_certificates") + try: + for region_key, region_values in self.__regions.items(): + certificates_data = oci.pagination.list_call_get_all_results( + region_values['search_client'].search_resources, + search_details=oci.resource_search.models.StructuredSearchDetails( + query="query certificate resources return allAdditionalFields") + ).data + cert_compartments = {} + debug("\t__certificates_read_certificates: Got Ceritificates from ") + + for certificate in certificates_data: + cert_compartments[certificate.compartment_id] = certificate.compartment_id + + for compartment in cert_compartments: + certs = oci.pagination.list_call_get_all_results( + region_values['certificate_client'].list_certificates, + compartment_id=compartment).data + for cert in certs: + record = oci.util.to_dict(cert) + debug("\t__certificates_read_certificates: Coverted Certificate Object to Dict") + + region_id = record['id'].split(".")[3] + debug("\t__certificates_read_certificates: Got region id") + + region_name = self.__get_region_name_from_key(region_id) + deep_link = self.__oci_cert_uri + record['id'] + "?region=" + region_name + record['deep_link'] = self.__generate_csv_hyperlink(deep_link, record['name']), + record['region'] = region_name + debug("\t__certificates_read_certificates: Added region name and deeplink to certificate record.") + self.__raw_oci_certificates.append(record) + except Exception as e: + debug("__certificates_read_certificates failed to process: " + str(e)) + print("\tProcessed " + str(len(self.__raw_oci_certificates)) + " Certificates") + + + ########################################################################## # Analyzes Tenancy Data for CIS Report ########################################################################## def __report_cis_analyze_tenancy_data(self): + self.__cis_regional_findings_data = {} + + for check in self.__cis_regional_checks: + self.__cis_regional_findings_data[check] = {} + for region_key, region_values in self.__regions.items(): + self.__cis_regional_findings_data[check][region_key] = None + + + # 1.1 Check - Checking for policy statements that are not restricted to a service for policy in self.__policies: @@ -4212,22 +4060,40 @@ def __report_cis_analyze_tenancy_data(self): # Iterate through all event rules for event in self.__event_rules: # Convert Event Condition to dict - jsonable_str = event['condition'].lower().replace("'", "\"") + eventtype_jsonable_str = event['condition'].lower().replace("'", "\"") try: - event_dict = json.loads(jsonable_str) + eventtype_dict = json.loads(eventtype_jsonable_str) except Exception: print("*** Invalid Event Condition for event (not in JSON format): " + event['display_name'] + " ***") - event_dict = {} - # Issue 256: 'eventtype' not in event_dict (i.e. missing in event condition) - if event_dict and 'eventtype' in event_dict: + eventtype_dict = {} + # Issue 256: 'eventtype' not in eventtype_dict (i.e. missing in event condition) + if eventtype_dict and 'eventtype' in eventtype_dict: for key, changes in self.cis_monitoring_checks.items(): # Checking if all cis change list is a subset of event condition try: - if (all(x in event_dict['eventtype'] for x in changes)): + # Checking if each region has the required events + if (all(x in eventtype_dict['eventtype'] for x in changes)) and key in self.__cis_regional_checks: + self.__cis_regional_findings_data[key][event['region']] = True + + # Cloud Guard Check is only required in the Cloud Guard Reporting Region + elif key == "4.15" and event['region'] == self.__cloud_guard_config.reporting_region and \ + (all(x in eventtype_dict['eventtype'] for x in changes)): self.cis_foundations_benchmark_2_0[key]['Status'] = True + + # For Checks that are home region based checking those + elif (all(x in eventtype_dict['eventtype'] for x in changes)) and \ + key not in self.__cis_regional_checks and event['region'] == self.__home_region: + self.cis_foundations_benchmark_2_0[key]['Status'] = True + except Exception: print("*** Invalid Event Data for event: " + event['display_name'] + " ***") + + # ******* Iterating through Regional Checks adding findings + for key, findings in self.__cis_regional_findings_data.items(): + if all(findings.values()): + self.cis_foundations_benchmark_2_0[key]['Status'] = True + # CIS Check 4.13 - VCN FlowLog enable # Generate list of subnets IDs for subnet in self.__network_subnets: @@ -4259,7 +4125,7 @@ def __report_cis_analyze_tenancy_data(self): self.cis_foundations_benchmark_2_0['4.16']['Status'] = False self.cis_foundations_benchmark_2_0['4.16']['Findings'].append( key) - except: + except Exception: self.cis_foundations_benchmark_2_0['4.16']['Status'] = False self.cis_foundations_benchmark_2_0['4.16']['Findings'].append( key) @@ -4299,7 +4165,7 @@ def __report_cis_analyze_tenancy_data(self): bucket) self.cis_foundations_benchmark_2_0['5.1.3']['Status'] = False - # CIS Check 4.1.1,4.1.2,4.1.3 Total - Adding All Buckets to total + # CIS Check 5.1.1,5.1.2,5.1.3 Total - Adding All Buckets to total self.cis_foundations_benchmark_2_0['5.1.1']['Total'] = self.__buckets self.cis_foundations_benchmark_2_0['5.1.2']['Total'] = self.__buckets self.cis_foundations_benchmark_2_0['5.1.3']['Total'] = self.__buckets @@ -4859,6 +4725,28 @@ def __obp_analyze_tenancy_data(self): else: self.obp_foundations_checks['Cloud_Guard_Config']['Findings'].append(cloud_guard_record) + ####################################### + # Certificate Expiry Check + ####################################### + + for cert in self.__raw_oci_certificates: + debug("\t__obp_analyze_tenancy_data: Iterating through certificates") + + try: + if cert['current_version_summary']['validity'] and \ + datetime.datetime.strptime(self.get_date_iso_format(cert['current_version_summary']['validity']['time_of_validity_not_after']), self.__iso_time_format) >= self.cert_key_time_max_datetime: + self.obp_foundations_checks['Certificates_Near_Expiry']['OBP'].append(cert) + else: + self.obp_foundations_checks['Certificates_Near_Expiry']['Findings'].append(cert) + except Exception: + debug("\t__obp_analyze_tenancy_data: Certificate is missing time of validity not after" + cert['name']) + self.obp_foundations_checks['Certificates_Near_Expiry']['Findings'].append(cert) + + if self.obp_foundations_checks['Certificates_Near_Expiry']['Findings']: + self.obp_foundations_checks['Certificates_Near_Expiry']['Status'] = False + else: + self.obp_foundations_checks['Certificates_Near_Expiry']['Status'] = True + ########################################################################## # Orchestrates data collection and CIS report generation ########################################################################## @@ -5182,7 +5070,7 @@ def __report_generate_html_summary_report(self, header, file_subject, data): if item_value != "": html_file.write(f"
{item_key.title()}
") if item_key == 'Observation': - if fing['Status'] == None: + if fing['Status'] is None: pfx = 'Manually check for' else: num_findings = len(fing['Findings']) @@ -5342,7 +5230,8 @@ def __collect_tenancy_data(self): self.__block_volume_read_block_volumes, self.__boot_volume_read_boot_volumes, self.__fss_read_fsss, - self.__core_instance_read_compute + self.__core_instance_read_compute, + self.__certificates_read_certificates ] # Oracle Best practice functions @@ -5418,7 +5307,8 @@ def __report_generate_raw_data_output(self): "cloud_guard_target": list(self.__cloud_guard_targets.values()), "regions": self.__raw_regions, "network_drg_attachments": list(itertools.chain.from_iterable(self.__network_drg_attachments.values())), - "instances": self.__Instance + "instances": self.__Instance, + "certificates" : self.__raw_oci_certificates } for key in raw_csv_files: rfn = self.__print_to_csv_file('raw_data', key, raw_csv_files[key]) @@ -5851,6 +5741,8 @@ def execute_report(): help='Uses Advanced Search Service to query all resources in the tenancy and outputs to a JSON. This also enables OCI Best Practice Checks (--obp) and All resource to csv (--raw) flags.') parser.add_argument('--redact_output', action='store_true', default=False, help='Redacts OCIDs in output CSV and JSON files.') + parser.add_argument('--deeplink-url-override', default=None, dest='oci_url', + help='Replaces the base OCI URL (https://cloud.oracle.com) for deeplinks (i.e. https://oc10.cloud.oracle.com).') parser.add_argument('-ip', action='store_true', default=False, dest='is_instance_principals', help='Use Instance Principals for Authentication.') parser.add_argument('-dt', action='store_true', default=False, @@ -5870,7 +5762,7 @@ def execute_report(): config, signer = create_signer(cmd.file_location, cmd.config_profile, cmd.is_instance_principals, cmd.is_delegation_token, cmd.is_security_token) config['retry_strategy'] = oci.retry.DEFAULT_RETRY_STRATEGY report = CIS_Report(config, signer, cmd.proxy, cmd.output_bucket, cmd.report_directory, cmd.report_prefix, cmd.report_summary_json, cmd.print_to_screen, \ - cmd.regions, cmd.raw, cmd.obp, cmd.redact_output, debug=cmd.debug, all_resources=cmd.all_resources) + cmd.regions, cmd.raw, cmd.obp, cmd.redact_output, oci_url=cmd.oci_url, debug=cmd.debug, all_resources=cmd.all_resources) csv_report_directory = report.generate_reports(int(cmd.level)) try: diff --git a/othertools/oci-fsdr/commonLib.py b/othertools/oci-fsdr/commonLib.py new file mode 100644 index 000000000..beeecf9c1 --- /dev/null +++ b/othertools/oci-fsdr/commonLib.py @@ -0,0 +1,14 @@ +import re +import json + +def get_region_from_ocid(ocid, region_map): + match = re.search(r'oc1\.(.*?)\.', ocid) + if match: + region_code = match.group(1) + return region_map.get(region_code, 'unknown-region') + return 'unknown-region' + +def load_region_map(region_file): + with open(region_file, 'r') as f: + region_map = json.load(f) + return region_map \ No newline at end of file diff --git a/othertools/oci-fsdr/export_drplan.py b/othertools/oci-fsdr/export_drplan.py new file mode 100644 index 000000000..c11b19e0e --- /dev/null +++ b/othertools/oci-fsdr/export_drplan.py @@ -0,0 +1,284 @@ +import oci +import pandas as pd +import os +from openpyxl import load_workbook +from openpyxl.utils import column_index_from_string +from openpyxl.styles import Alignment, PatternFill, Font +import argparse +from commonLib import * + +parser = argparse.ArgumentParser() +parser.add_argument("-o", "--ocid", help="Provide the DR Plan OCID") +parser.add_argument("-s", "--sheet", help="Provide the sheet name under which the value is stored") +parser.add_argument("-f", "--file", help="Provide name of the file to be created/updated") +parser.add_argument("-c", "--config", help="API_KEY") +parser.add_argument("-i", "--instance_principal", help="INSTANCE_PRINCIPAL", nargs='?', const=1, type=int) +parser.add_argument("-t", "--session_token", help="SESSION_TOKEN", nargs='?', const=1, type=int) +args = parser.parse_args() + +try: + region_file = os.path.dirname(os.path.abspath(__file__))+"/region_file.json" + region_map = load_region_map(region_file) + region = get_region_from_ocid(args.ocid, region_map) +except Exception as e: + print(f"Error loading region map: {str(e)}") + exit(1) + +try: + config = oci.config.from_file(file_location=args.config) +except Exception as e: + print(f"Error loading OCI config: {str(e)}") + print(".....Exiting!!!") + exit(1) + +if args.ocid: + config['region'] = region + +try: + if args.instance_principal == 1: + signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() + elif args.session_token: + token_file = config['security_token_file'] + token = None + with open(token_file, 'r') as f: + token = f.read() + + private_key = oci.signer.load_private_key_from_file(config['key_file']) + signer = oci.auth.signers.SecurityTokenSigner(token, private_key) + elif args.config != '': + signer = oci.signer.Signer(config['tenancy'], config['user'], config['fingerprint'], config['key_file']) +except Exception as e: + print(f"Error creating signer: {str(e)}") + exit(1) + +try: + # Get DR Plan + disaster_recovery_client = oci.disaster_recovery.DisasterRecoveryClient( + config=config, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY, signer=signer) + get_dr_plan_response = disaster_recovery_client.get_dr_plan(dr_plan_id=args.ocid) + plan_groups = get_dr_plan_response.data.plan_groups + # Extract the order of plan groups + original_order = [pg.id for pg in plan_groups] + + # Manually convert DrPlanGroup objects to dictionaries + plan_dicts = [] + for pg in plan_groups: + steps = [] + for step in pg.steps: + step_dict = { + 'display_name': step.display_name, + 'error_mode': step.error_mode, + 'id': step.id, + 'is_enabled': step.is_enabled, + 'timeout': step.timeout, + 'type': step.type, + } + if hasattr(step, 'user_defined_step') and step.user_defined_step: + user_defined_step = { + 'step_type': step.user_defined_step.step_type, + 'run_as_user': getattr(step.user_defined_step, 'run_as_user', None), + 'run_on_instance_id': getattr(step.user_defined_step, 'run_on_instance_id', None), + 'function_id': getattr(step.user_defined_step, 'function_id', None), + 'function_region': getattr(step.user_defined_step, 'function_region', None), + 'request_body': getattr(step.user_defined_step, 'request_body', None), + 'object_storage_script_location': { + 'bucket': getattr(step.user_defined_step.object_storage_script_location, 'bucket', None), + 'namespace': getattr(step.user_defined_step.object_storage_script_location, 'namespace', None), + 'object': getattr(step.user_defined_step.object_storage_script_location, 'object', None) + } if getattr(step.user_defined_step, 'object_storage_script_location', None) else None, + 'run_on_instance_region': getattr(step.user_defined_step, 'run_on_instance_region', None), + 'script_command': getattr(step.user_defined_step, 'script_command', None) + } + step_dict['user_defined_step'] = user_defined_step + steps.append(step_dict) + plan_dicts.append({ + 'display_name': pg.display_name, + 'id': pg.id, + 'type': pg.type, + 'steps': steps + }) + + # Convert the parsed plan data to a DataFrame + df = pd.json_normalize(plan_dicts) + + # Split the data into two parts based on the "type" value + built_in_df = df[df['type'] == 'BUILT_IN'] + other_df = df[df['type'] != 'BUILT_IN'] + + # Function to normalize and reformat data + def normalize_and_reformat(df): + dict_list_orient = df.to_dict('records') + normalized_data = pd.json_normalize(dict_list_orient, "steps", ['display_name', 'id', 'type'], record_prefix='steps.') + columns_order = [ + 'display_name', 'id', 'steps.display_name', 'steps.error_mode', 'steps.id', 'steps.is_enabled', + 'steps.timeout', 'steps.type', 'type' + ] + normalized_data = normalized_data.reindex(columns=columns_order, fill_value=None) + return normalized_data + + def normalize_other_data(df): + dict_list_orient = df.to_dict('records') + normalized_data = pd.json_normalize(dict_list_orient, "steps", ['display_name', 'id', 'type'], record_prefix='steps.') + columns_order = [ + 'display_name', 'id', 'steps.display_name', 'steps.error_mode', 'steps.id', 'steps.is_enabled', + 'steps.timeout', 'steps.type', 'steps.user_defined_step.step_type', + 'steps.user_defined_step.run_as_user', 'steps.user_defined_step.run_on_instance_id', + 'steps.user_defined_step.function_id', 'steps.user_defined_step.function_region', 'steps.user_defined_step.request_body', + 'steps.user_defined_step.object_storage_script_location.bucket', 'steps.user_defined_step.object_storage_script_location.namespace', 'steps.user_defined_step.object_storage_script_location.object', + 'steps.user_defined_step.run_on_instance_region', 'steps.user_defined_step.script_command', 'type' + ] + normalized_data = normalized_data.reindex(columns=columns_order, fill_value=None) + return normalized_data + + # Normalize and reformat both subsets of data + built_in_data = normalize_and_reformat(built_in_df) + other_data = normalize_other_data(other_df) + + # Append both subsets of data into one DataFrame + combined_data = pd.concat([other_data, built_in_data], ignore_index=True) + + # Sort the combined data based on the original order + combined_data['sort_order'] = pd.Categorical(combined_data['id'], categories=original_order, ordered=True) + combined_data.sort_values('sort_order', inplace=True) + combined_data.drop(columns=['sort_order'], inplace=True) + + # Write the combined data to an Excel file + excel_file = args.file + sheet = args.sheet + if sheet.startswith('"') and sheet.endswith('"'): + sheet = sheet[1:-1] + + # Check if the file exists and the sheet exists + if os.path.exists(excel_file): + wb = load_workbook(excel_file) + if sheet in wb.sheetnames: + with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer: + print(f"Writing to sheet: {sheet}") + combined_data.to_excel(writer, sheet_name=sheet, index=False) + worksheet = writer.sheets[sheet] + else: + with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a') as writer: + print(f"Writing to sheet: {sheet}") + combined_data.to_excel(writer, sheet_name=sheet, index=False) + worksheet = writer.sheets[sheet] + else: + with pd.ExcelWriter(excel_file, engine='openpyxl', mode='w') as writer: + print(f"Writing to Excel file: {excel_file} and sheet: {sheet}") + combined_data.to_excel(writer, sheet_name=sheet, index=False) + worksheet = writer.sheets[sheet] + + wb = load_workbook(excel_file) + ws = wb[sheet] + + + def merge_and_center(ws, col): + max_row = ws.max_row + for row in range(2, max_row + 1): + cell_value = ws.cell(row=row, column=col).value + start_row = row + while row <= max_row and ws.cell(row=row, column=col).value == cell_value: + row += 1 + end_row = row - 1 + if start_row != end_row: + ws.merge_cells(start_row=start_row, start_column=col, end_row=end_row, end_column=col) + merged_cell = ws.cell(row=start_row, column=col) + merged_cell.alignment = Alignment(horizontal='center', vertical='center') + + + columns_to_merge = ['A', 'B'] + + for col in columns_to_merge: + col_index = column_index_from_string(col) + merge_and_center(ws, col_index) + + # Define fill colors + fill_blue = PatternFill(start_color="346EC9", end_color="346EC9", fill_type="solid") + fill_purple = PatternFill(start_color="858491", end_color="858491", fill_type="solid") + font_white = Font(color="FFFFFF", bold=True) + + header_cells = ws[1] + for cell in header_cells: + if cell.column_letter in ['A', 'B', 'T']: + cell.fill = fill_blue + cell.font = font_white + else: + cell.fill = fill_purple + cell.font = font_white + + # Auto-adjust column widths + for col in ws.columns: + max_length = 0 + column = col[0].column_letter + for cell in col: + try: + if len(str(cell.value)) > max_length: + max_length = len(cell.value) + except: + pass + adjusted_width = (max_length + 2) + ws.column_dimensions[column].width = adjusted_width + + # Save the modified workbook + wb.save(excel_file) + print("Excel file updated successfully.") + + if "Readme" not in wb.sheetnames: + readme_sheet = wb.create_sheet(title="Readme") + readme_content = """ + Instructions to update columns in Excel sheet + + For New Plan step update the row values as below: + - id, steps.id - leave these row values empty column empty + - Display_name : Display name for Plan Group name (mandatory) + steps.display_name : Display name for the step (mandatory) + steps.error_mode : STOP_ON_ERROR/CONTINUE_ON_ERROR (mandatory) + steps.is_enabled : TRUE/FALSE (mandatory) + steps.timeout : timeout value in seconds (mandatory) + type: USER_DEFINED (mandatory) + steps.user_defined_step.step_type : RUN_LOCAL_SCRIPT/RUN_OBJECTSTORE_SCRIPT/INVOKE_FUNCTION + + Based on the step type from above fill in the row values as mentioned : + RUN_LOCAL_SCRIPT: + - steps.user_defined_step.run_as_user, (description: user as which the script needs to run) + - steps.user_defined_step.run_on_instance_id, (description: Instance OCID where the script is located) + - steps.user_defined_step.script_command (description: script command which needs to run) + RUN_OBJECTSTORE_SCRIPT: + - steps.user_defined_step.run_on_instance_id, (description: Instance OCID where the script is located) + - steps.user_defined_step.object_storage_script_location.bucket, (description: OCI bucket name) + - steps.user_defined_step.object_storage_script_location.namespace, (description: OCI bucket namespace name) + - steps.user_defined_step.object_storage_script_location.object, (description: script name) + - steps.user_defined_step.run_on_instance_region, (description: Instance region name) + - steps.user_defined_step.script_command (description: script command which needs to run) + INVOKE_FUNCTION: + - steps.user_defined_step.function_id (description: OCI Function OCID which needs to be invoked) + - steps.user_defined_step.function_region (description: OCI Function region) + - steps.user_defined_step.request_body (description: OCI Function request body) + """ + + # Insert the content into a single cell (A1) + readme_sheet["A1"] = readme_content.strip() + + # Expand the row height to accommodate the text + readme_sheet.row_dimensions[1].height = 750 # You can adjust this value + + # Auto-adjust column width to fit the content + readme_sheet.column_dimensions['A'].width = 150 # You can adjust this value + + # Set text wrapping for the cell + readme_sheet["A1"].alignment = Alignment(wrap_text=True, vertical='top') + readme_sheet["A1"].font = Font(size=14, color="FFFFFF", bold=True) # Set font size to 14 and color to white + readme_sheet["A1"].fill = PatternFill(start_color="346EC9", end_color="346EC9", + fill_type="solid") # Set background to blue + readme_index = wb.sheetnames.index("Readme") + wb._sheets.insert(0, wb._sheets.pop(readme_index)) + + # Save the workbook with the new Readme sheet + wb.save(excel_file) + + + + wb.save(excel_file) + wb.close() + +except Exception as e: + print(f"Error: {str(e)}") diff --git a/othertools/oci-fsdr/oci-fsdr-plan-template.xlsx b/othertools/oci-fsdr/oci-fsdr-plan-template.xlsx new file mode 100644 index 000000000..be22a2d89 Binary files /dev/null and b/othertools/oci-fsdr/oci-fsdr-plan-template.xlsx differ diff --git a/othertools/oci-fsdr/region_file.json b/othertools/oci-fsdr/region_file.json new file mode 100644 index 000000000..2d970e31d --- /dev/null +++ b/othertools/oci-fsdr/region_file.json @@ -0,0 +1,41 @@ +{ + "phx": "us-phoenix-1", + "syd": "ap-sydney-1", + "mel": "ap-melbourne-1", + "gru": "sa-saopaulo-1", + "vcp": "sa-vinhedo-1", + "yul": "ca-montreal-1", + "yyz": "ca-toronto-1", + "scl": "sa-santiago-1", + "vap": "sa-valparaiso-1", + "bog": "sa-bogota-1", + "cdg": "eu-paris-1", + "mrs": "eu-marseille-1", + "fra": "eu-frankfurt-1", + "hyd": "ap-hyderabad-1", + "bom": "ap-mumbai-1", + "mtz": "il-jerusalem-1", + "lin": "eu-milan-1", + "kix": "ap-osaka-1", + "nrt": "ap-tokyo-1", + "qro": "mx-queretaro-1", + "mty": "mx-monterrey-1", + "ams": "eu-amsterdam-1", + "jed": "me-jeddah-1", + "beg": "eu-jovanovac-1", + "sin": "ap-singapore-1", + "xsp": "ap-singapore-2", + "jnb": "af-johannesburg-1", + "icn": "ap-seoul-1", + "yny": "ap-chuncheon-1", + "mad": "eu-madrid-1", + "arn": "eu-stockholm-1", + "zrh": "eu-zurich-1", + "auh": "me-abudhabi-1", + "dxb": "me-dubai-1", + "lhr": "uk-london-1", + "cwl": "uk-cardiff-1", + "iad": "us-ashburn-1", + "ord": "us-chicago-1", + "sjc": "us-sanjose-1" +} diff --git a/othertools/oci-fsdr/update_drplan.py b/othertools/oci-fsdr/update_drplan.py new file mode 100644 index 000000000..ea21c8fd4 --- /dev/null +++ b/othertools/oci-fsdr/update_drplan.py @@ -0,0 +1,368 @@ +import oci +import openpyxl +import argparse +import os +from commonLib import * + +parser = argparse.ArgumentParser() +parser.add_argument("-o", "--ocid", help="Provide the DR Plan OCID") +parser.add_argument("-s", "--sheet", help="Provide the sheet name under which the value is stored") +parser.add_argument("-f", "--file", help="Provide name of the file to be created/updated") +parser.add_argument("-c", "--config", help="API_KEY") +parser.add_argument("-i", "--instance_principal", help="INSTANCE_PRINCIPAL", nargs='?', const=1, type=int) +parser.add_argument("-t", "--session_token", help="SESSION_TOKEN", nargs='?', const=1, type=int) + +args = parser.parse_args() + +try: + region_file = os.path.dirname(os.path.abspath(__file__)) + "/region_file.json" + region_map = load_region_map(region_file) + region = get_region_from_ocid(args.ocid, region_map) +except Exception as e: + print(f"Error loading region map or determining region from OCID: {str(e)}") + print(".....Exiting!!!") + exit(0) + +try: + config = oci.config.from_file(file_location=args.config) + if args.ocid: + config['region'] = region +except Exception as e: + print(f"Error loading OCI config: {str(e)}") + print(".....Exiting!!!") + exit(0) + +try: + if args.instance_principal == 1: + signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() + elif args.session_token: + token_file = config['security_token_file'] + token = None + with open(token_file, 'r') as f: + token = f.read() + + private_key = oci.signer.load_private_key_from_file(config['key_file']) + elif args.config != '': + signer = oci.signer.Signer(config['tenancy'], config['user'], config['fingerprint'], config['key_file']) +except Exception as e: + print(f"Error initializing signer: {str(e)}") + print(".....Exiting!!!") + exit(0) + +# Initialize Disaster Recovery client +try: + disaster_recovery_client = oci.disaster_recovery.DisasterRecoveryClient(config) +except Exception as e: + print(f"Error initializing Disaster Recovery client: {str(e)}") + print(".....Exiting!!!") + exit(0) + +# Function to get the actual value of a cell, considering merged cells +def get_merged_cell_value(sheet, row, col): + cell = sheet.cell(row=row, column=col) + for merged_cell_range in sheet.merged_cells.ranges: + if cell.coordinate in merged_cell_range: + merged_cell = sheet.cell(row=merged_cell_range.min_row, column=merged_cell_range.min_col) + return merged_cell.value + return cell.value + +# Define functions for plan management with appropriate error handling +def new_plan(row, plan_groups_dict): + try: + plan_group_display_name = str(row[0]) + id = None + step_display_name = str(row[2]) + step_error_mode = row[3] + s_id = None + step_is_enabled = row[5] + timeout = row[6] + step_type = row[8] + run_as_user = row[9] + run_on_instance_id = row[10] + function_id = row[11] + function_region = row[12] + request_body = row[13] + bucket = row[14] + namespace = row[15] + bucket_object = row[16] + instance_region = row[17] + script_command = row[18] + + if step_type in ["RUN_LOCAL_SCRIPT", "RUN_OBJECTSTORE_SCRIPT", "INVOKE_FUNCTION"]: + type = 'USER_DEFINED' + else: + raise ValueError(f"Invalid step_type: {step_type}. Must be one of RUN_LOCAL_SCRIPT, RUN_OBJECTSTORE_SCRIPT, INVOKE_FUNCTION") + + valid_step_types = [ + 'RUN_OBJECTSTORE_SCRIPT_PRECHECK', + 'RUN_LOCAL_SCRIPT_PRECHECK', + 'INVOKE_FUNCTION_PRECHECK', + 'RUN_OBJECTSTORE_SCRIPT', + 'RUN_LOCAL_SCRIPT', + 'INVOKE_FUNCTION' + ] + + if step_type not in valid_step_types: + raise ValueError(f"Invalid step_type: {step_type}. Must be one of {valid_step_types}") + + if plan_group_display_name in plan_groups_dict: + plan_group_details = plan_groups_dict[plan_group_display_name] + else: + plan_group_details = oci.disaster_recovery.models.UpdateDrPlanGroupDetails( + display_name=plan_group_display_name, + id=id, + type=type, + steps=[] + ) + plan_groups_dict[plan_group_display_name] = plan_group_details + + if step_type == "RUN_LOCAL_SCRIPT": + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled, + user_defined_step=oci.disaster_recovery.models.UpdateRunLocalScriptUserDefinedStepDetails( + step_type=step_type, + run_on_instance_id=run_on_instance_id, + run_as_user=run_as_user, + script_command=script_command + ) + ) + elif step_type == "RUN_OBJECTSTORE_SCRIPT": + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled, + user_defined_step=oci.disaster_recovery.models.UpdateRunObjectStoreScriptUserDefinedStepDetails( + step_type=step_type, + run_on_instance_id=run_on_instance_id, + object_storage_script_location=oci.disaster_recovery.models.UpdateObjectStorageScriptLocationDetails( + bucket=bucket, + namespace=namespace, + object=bucket_object + ) + ) + ) + elif step_type == "INVOKE_FUNCTION": + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled, + user_defined_step=oci.disaster_recovery.models.UpdateInvokeFunctionUserDefinedStepDetails( + step_type=step_type, + function_id=function_id, + request_body=request_body + ) + ) + else: + raise ValueError(f"Invalid step_type: {step_type}. Must be one of RUN_LOCAL_SCRIPT, RUN_OBJECTSTORE_SCRIPT, INVOKE_FUNCTION") + + if step_details not in plan_group_details.steps: + plan_group_details.steps.append(step_details) + + return plan_groups_dict, plan_group_details + except Exception as e: + print(f"Error in new_plan function: {str(e)}") + exit(0) + +def existing_plan(row, plan_groups_dict): + try: + plan_group_display_name = str(row[0]) + id = str(row[1]) + step_display_name = str(row[2]) + step_error_mode = row[3] + s_id = str(row[4]) + step_is_enabled = row[5] + timeout = row[6] + step_type = row[8] + run_as_user = row[9] + run_on_instance_id = row[10] + function_id = row[11] + function_region = row[12] + request_body = row[13] + bucket = row[14] + namespace = row[15] + bucket_object = row[16] + instance_region = row[17] + script_command = row[18] + + if step_type in ["RUN_LOCAL_SCRIPT", "RUN_OBJECTSTORE_SCRIPT", "INVOKE_FUNCTION"]: + type = 'USER_DEFINED' + else: + raise ValueError(f"Invalid step_type: {step_type}. Must be one of RUN_LOCAL_SCRIPT, RUN_OBJECTSTORE_SCRIPT, INVOKE_FUNCTION") + + valid_step_types = [ + 'RUN_OBJECTSTORE_SCRIPT_PRECHECK', + 'RUN_LOCAL_SCRIPT_PRECHECK', + 'INVOKE_FUNCTION_PRECHECK', + 'RUN_OBJECTSTORE_SCRIPT', + 'RUN_LOCAL_SCRIPT', + 'INVOKE_FUNCTION' + ] + + if step_type not in valid_step_types: + raise ValueError(f"Invalid step_type: {step_type}. Must be one of {valid_step_types}") + + if id in plan_groups_dict: + plan_group_details = plan_groups_dict[id] + else: + plan_group_details = oci.disaster_recovery.models.UpdateDrPlanGroupDetails( + display_name=plan_group_display_name, + id=id, + type=type, + steps=[] + ) + plan_groups_dict[id] = plan_group_details + + if step_type == "RUN_LOCAL_SCRIPT": + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled, + user_defined_step=oci.disaster_recovery.models.UpdateRunLocalScriptUserDefinedStepDetails( + step_type=step_type, + run_on_instance_id=run_on_instance_id, + run_as_user=run_as_user, + script_command=script_command + ) + ) + elif step_type == "RUN_OBJECTSTORE_SCRIPT": + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled, + user_defined_step=oci.disaster_recovery.models.UpdateRunObjectStoreScriptUserDefinedStepDetails( + step_type=step_type, + run_on_instance_id=run_on_instance_id, + object_storage_script_location=oci.disaster_recovery.models.UpdateObjectStorageScriptLocationDetails( + bucket=bucket, + namespace=namespace, + object=bucket_object + ) + ) + ) + elif step_type == "INVOKE_FUNCTION": + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled, + user_defined_step=oci.disaster_recovery.models.UpdateInvokeFunctionUserDefinedStepDetails( + step_type=step_type, + function_id=function_id, + request_body=request_body + ) + ) + else: + raise ValueError(f"Invalid step_type: {step_type}. Must be one of RUN_LOCAL_SCRIPT, RUN_OBJECTSTORE_SCRIPT, INVOKE_FUNCTION") + + if step_details not in plan_group_details.steps: + plan_group_details.steps.append(step_details) + + return plan_groups_dict, plan_group_details + except Exception as e: + print(f"Error in existing_plan function: {str(e)}") + exit(0) + +def builtin_function(row, plan_groups_dict): + try: + plan_group_display_name = str(row[0]) + id = str(row[1]) + step_display_name = str(row[2]) + step_error_mode = row[3] + s_id = row[4] + step_is_enabled = row[5] + timeout = row[6] + type = row[19] + + valid_builtin_types = ['BUILT_IN', 'BUILT_IN_PRECHECK', 'USER_DEFINED'] + if type not in valid_builtin_types: + raise ValueError(f"Invalid value for `type`: {type}. Must be one of {valid_builtin_types}") + + if id in plan_groups_dict: + plan_group_details = plan_groups_dict[id] + else: + plan_group_details = oci.disaster_recovery.models.UpdateDrPlanGroupDetails( + display_name=plan_group_display_name, + id=id, + type=type, + steps=[] + ) + plan_groups_dict[id] = plan_group_details + + step_details = oci.disaster_recovery.models.UpdateDrPlanStepDetails( + display_name=step_display_name, + error_mode=step_error_mode, + id=s_id, + timeout=timeout, + is_enabled=step_is_enabled + ) + + if step_details not in plan_group_details.steps: + plan_group_details.steps.append(step_details) + + return plan_groups_dict, plan_group_details + except Exception as e: + print(f"Error in builtin_function function: {str(e)}") + exit(0) + +try: + workbook = openpyxl.load_workbook(args.file) + sheet = args.sheet + if sheet.startswith('"') and sheet.endswith('"'): + sheet = sheet[1:-1] + sheet = workbook[sheet] +except Exception as e: + print(f"Error loading Excel file or sheet: {str(e)}") + print(".....Exiting!!!") + exit(0) + +plan_groups_dict = {} +ordered_plan_groups = [] + +try: + for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row): + row_values = [get_merged_cell_value(sheet, row[0].row, col) for col in range(1, sheet.max_column + 1)] + id_value = str(row_values[1]) + type_value = str(row_values[19]) + + row_values = [None if val in ["None", None] else val for val in row_values] + + if type_value == "USER_DEFINED": + if id_value == "None": + plan_groups_dict, plan_group_details = new_plan(row_values, plan_groups_dict) + else: + plan_groups_dict, plan_group_details = existing_plan(row_values, plan_groups_dict) + else: + plan_groups_dict, plan_group_details = builtin_function(row_values, plan_groups_dict) + + ordered_plan_groups.append(plan_group_details) +except Exception as e: + print(f"Error processing rows in Excel sheet: {str(e)}") + print(".....Exiting!!!") + exit(0) + +final_plan_groups = list(plan_groups_dict.values()) + +try: + update_dr_plan_details = oci.disaster_recovery.models.UpdateDrPlanDetails(plan_groups=final_plan_groups) + update_dr_plan_response = disaster_recovery_client.update_dr_plan( + update_dr_plan_details=update_dr_plan_details, + dr_plan_id=args.ocid + ) + print("Update to DR Plan " + args.ocid + "is successful") +except Exception as e: + print(f"Error updating DR plan: {str(e)}") + print(".....Exiting!!!") + exit(0)