-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.py
58 lines (41 loc) · 1.49 KB
/
import.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import sys, hcl, ovh, os, stat
# Define constants.
OVH_TF_RESOURCE = "ovh_domain_zone_record"
# Parse args.
creds_tf = sys.argv[1]
zone = sys.argv[2]
main_tf = 'main.tf'
import_sh = 'import.sh'
try:
main_tf = sys.argv[3]
import_sh = sys.argv[4]
except IndexError:
pass
main_tf_contents = ''
import_sh_contents = '#!/bin/sh\n'
# Create TF-friendly zone prefix.
zone_res_name = zone.replace(".", "_dot_")
# Load OVH credentials.
with open(creds_tf, 'r') as f:
creds_hcl = hcl.load(f)
ovh_client = ovh.Client(**creds_hcl['provider']['ovh'])
record_ids = ovh_client.get(f'/domain/zone/{zone}/record')
for r_id in record_ids:
record = ovh_client.get(f'/domain/zone/{zone}/record/{r_id}')
terraform_resource_name = f"{zone_res_name}_{r_id}"
main_tf_contents += (f'resource "{OVH_TF_RESOURCE}" "{terraform_resource_name}" ' + '{\n')
for k,v in record.items():
# Resource ID is not part of the configuration.
if k == 'id':
import_sh_contents += f'terraform import {OVH_TF_RESOURCE}.{terraform_resource_name} {v}.{zone}\n'
continue
# Record values might contain double quotes.
v_escaped = str(v).replace('"', r'\"')
main_tf_contents += f' {k.lower()} = "{v_escaped}"\n'
main_tf_contents += '}\n\n'
with open(main_tf, 'w') as f:
f.write(main_tf_contents)
with open(import_sh, 'w') as f:
f.write(import_sh_contents)
import_sh_stat = os.stat(import_sh)
os.chmod(import_sh, import_sh_stat.st_mode | stat.S_IEXEC)