Files
IOT_Stack/Portainer_Script/yml_to_json.py
T
2022-11-12 12:52:31 +05:30

92 lines
2.8 KiB
Python

import os
from dotenv import load_dotenv
load_dotenv()
file_name=list()
#listing all yml file in the path
for x in os.listdir(os.getenv('FILE_PATH')):
if x.endswith(".yml"):
print(x)
file_name.append(x)
portainer_json_format='''
{
"version": "2",
"templates": [
{
'''
temp_expect_handle=0
port=1024
for i in file_name:
temp_replace_title=''
temp=''
with open(os.getenv('FILE_PATH')+i,'r') as f:
givenWord = 'image:'
for textline in f:
wordsList = textline.split()
if givenWord in wordsList:
temp_replace_title=temp
temp=textline
title=temp_replace_title.replace(" ", "").replace('\n','').replace(':','')
with open(os.getenv('FILE_PATH')+i,'r') as ff:
kk=ff.read()
portainer_json_format +=' "type": 1,'
portainer_json_format +=f'"title" : "{title}",\n'
portainer_json_format +=f'"name": "{title}.bit.lan",\n'
portainer_json_format +='"platform": "linux",\n'
portainer_json_format+= '"administrator_only": false,\n'
#finding image name
start_value=kk.rfind("image:")
end_value=kk.find('\n',start_value+6)
image=kk[start_value+6:end_value].replace(" ", "").replace('\n','')
portainer_json_format +=f'"image" : "{image}",\n'
portainer_json_format +=f'"hostname": "{title}",\n"restart_policy": "always",\n'
portainer_json_format +=f'"ports": ["{port}/tcp"],\n'
port+=1
#volumes allocating
try:
start_value=kk.index("volumes:")
start_value=kk.find("-",start_value)
end_Value=kk.find(":",start_value+3)
# print("image :",kk[start_value+3:end_Value].replace(" ", "").replace('\n',''))
ports=kk[start_value+3:end_Value].replace(" ", "").replace('\n','')
portainer_json_format +='''
"volumes": [
{
"container": "/%s/data",
"bind": "/srv/%s.bit.lan/docker/data",
"readonly": false
},
{
"container": "/%s/config",
"bind": "/srv/%s.bit.lan/docker/config",
"readonly": false
}
,
{
"container": "/%s/log",
"bind": "/srv/%s.bit.lan/docker/log",
"readonly": false
}
],\n'''%(title,title,title,title,title,title)
except:
temp_expect_handle=1
portainer_json_format+= ''' "labels": [
{ "name": "com.centurylinklabs.watchtower.enable", "value": "true" }
]'''
portainer_json_format+= '''
},
{
'''
portainer_json_format+= '''
]
}
'''
portainer_json_format = f"{portainer_json_format}"
with open("portainer_json_format.json",'w') as f:
f.write(portainer_json_format)