Skip to content

Commit

Permalink
chore(docs): Add python script to generate .tfvars file from CSV in…
Browse files Browse the repository at this point in the history
…put and add usage to `README.md`
  • Loading branch information
spbsoluble committed Jul 10, 2024
1 parent d3acc20 commit ace82bf
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 0 deletions.
45 changes: 45 additions & 0 deletions examples/terraform/multiple_unique_creds/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,51 @@ terraform plan
terraform apply
```

### Generate tfvars file from CSV
Alternatively, you can generate the `.tfvars` file from a CSV file using the template `example.csv` and running the
python script `csv2tfvars.py`. This script will generate a `.tfvars` based on the inputs of the CSV file.

#### Usage
```text
python csv2tfvars.py -h
usage: csv2tfvars.py [-h] -csv CSV_FILE -orch ORCHESTRATOR_NAME [-i] [output_tfvars_file]
Convert CSV to TFVARS. This script parses a given CSV file containing camera information and generates a Terraform variables file (.tfvars) with the data structured for Terraform usage.
Usage:
csv2tfvars.py -csv <input_csv_file> -orch <orchestrator_name> [output_tfvars_file] [-i]
csv2tfvars.py --help
The -i flag enables interactive mode, prompting for any missing required inputs.
positional arguments:
output_tfvars_file Output TFVARS file path. Optional, defaults to BoschIPCameraStores.tfvars.
optional arguments:
-h, --help show this help message and exit
-csv CSV_FILE, --csv_file CSV_FILE
Path to the input CSV file. Required unless in interactive mode.
-orch ORCHESTRATOR_NAME, --orchestrator_name ORCHESTRATOR_NAME
Orchestrator name. Required unless in interactive mode.
-i, --interactive Run in interactive mode. Prompts for missing inputs.
```

#### Interactive Example
```bash
python csv2tfvars.py -i
```
```text
Enter the input CSV file path: example.csv
Enter the orchestrator_name: my-uo-client-name
Enter the output TFVARS file path (default is 'BoschIPCameraStores.tfvars'):
TFVARS file generated: BoschIPCameraStores.tfvars
```

#### Non-Interactive Example
```bash
python csv2tfvars.py -csv example.csv -orch my-uo-client-name
```

<!-- BEGIN_TF_DOCS -->
## Requirements

Expand Down
72 changes: 72 additions & 0 deletions examples/terraform/multiple_unique_creds/csv2tfvars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import argparse
import csv
import os
import sys

DEFAULT_OUTPUT_TFVARS_FILE = 'BoschIPCameraStores.tfvars'

def validate_file_exists(file_path):
if not os.path.exists(file_path):
print(f"Error: The file '{file_path}' does not exist.")
sys.exit(1)

def get_args(interactive):
parser = argparse.ArgumentParser(description="""
Convert CSV to TFVARS. This script parses a given CSV file containing camera information and generates a Terraform variables file (.tfvars) with the data structured for Terraform usage.
Usage:
csv2tfvars.py -csv <input_csv_file> -orch <orchestrator_name> [output_tfvars_file] [-i]
csv2tfvars.py --help
The -i flag enables interactive mode, prompting for any missing required inputs.""",
formatter_class=argparse.RawTextHelpFormatter)

parser.add_argument('-csv', '--csv_file', type=str, required=False, help='Path to the input CSV file. Required unless in interactive mode.')
parser.add_argument('-orch', '--orchestrator_name', type=str, required=False, help='Orchestrator name. Required unless in interactive mode.')
parser.add_argument('output_tfvars_file', nargs='?', default=DEFAULT_OUTPUT_TFVARS_FILE, help='Output TFVARS file path. Optional, defaults to BoschIPCameraStores.tfvars.')
parser.add_argument('-i', '--interactive', action='store_true', help='Run in interactive mode. Prompts for missing inputs.')

args = parser.parse_args()

if interactive:
if not args.csv_file:
args.csv_file = input("Enter the input CSV file path: ")
if not args.orchestrator_name:
args.orchestrator_name = input("Enter the orchestrator_name: ")
if args.output_tfvars_file == DEFAULT_OUTPUT_TFVARS_FILE: # Default value
args.output_tfvars_file = input("Enter the output TFVARS file path (default is 'BoschIPCameraStores.tfvars'): ") or DEFAULT_OUTPUT_TFVARS_FILE
else:
if not args.csv_file or not args.orchestrator_name:
parser.print_help()
sys.exit(1)

validate_file_exists(args.csv_file)
return args

def main():
args = get_args('-i' in sys.argv)

camera_map = {}
with open(args.csv_file, mode='r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
camera_map[row['serial_number']] = {
'ip': row['ip'],
'username': row['username'],
'password': row['password']
}

with open(args.output_tfvars_file, mode='w', encoding='utf-8') as tfvarsfile:
tfvarsfile.write(f'orchestrator_name="{args.orchestrator_name}"\n')
tfvarsfile.write('camera_map = {\n')
for serial, details in camera_map.items():
tfvarsfile.write(f' "{serial}" = {{\n')
tfvarsfile.write(f' ip = "{details["ip"]}"\n')
tfvarsfile.write(f' username = "{details["username"]}"\n')
tfvarsfile.write(f' password = "{details["password"]}"\n')
tfvarsfile.write(' }\n')
tfvarsfile.write('}\n')
print(f"TFVARS file generated: {args.output_tfvars_file}")

if __name__ == "__main__":
main()
11 changes: 11 additions & 0 deletions examples/terraform/multiple_unique_creds/example.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
serial_number,ip,username,password
068745431065110091,192.168.0.1:4444,camera1_admin,camera1_password
068745431065110092,192.168.0.2:4444,camera2_admin,camera2_password
068745431065110093,192.168.0.3:4444,camera3_admin,camera3_password
068745431065110094,192.168.0.4:4444,camera4_admin,camera4_password
068745431065110095,192.168.0.5:4444,camera5_admin,camera5_password
068745431065110096,192.168.0.6:4444,camera6_admin,camera6_password
068745431065110097,192.168.0.7:4444,camera7_admin,camera7_password
068745431065110098,192.168.0.8:4444,camera8_admin,camera8_password
068745431065110099,192.168.0.8:4444,camera9_admin,camera9_password
068745431065110100,192.168.0.9:4444,camera10_admin,camera10_password

0 comments on commit ace82bf

Please sign in to comment.