Forum Discussion
Hello,
we have a prototype of a script to create services using an existing template and to modify the name of the service and the device search filter based on supplied data. I will post the script below. This script is provided as a working sample to demonstrate what is possible, please do not raise a Support case for it! The script only works with Device Service templates.
#!/usr/bin/env python3
import requests
import argparse
import getpass
def run_gql(url, payload, auth):
request = requests.post(url, json=payload, verify=False, auth=auth)
if request.status_code == 200:
return request.json()
else:
raise Exception(f"GraphQL query failed to run by returning code of {request.status_code}. \n\nOriginal Query: {query}")
def query_template_by_name(template_name):
query = """
query harTemplateNameToId($templateName: String!) {
harTemplates(search: {name: {eq: $templateName}}) {
edges {
node {
id
definition
}
}
pageInfo {
matchCount
}
}
}
"""
variables = {
"templateName": template_name
}
payload = {
'query': query,
'variables': variables
}
auth = (username, password)
try:
result = run_gql(GQL_URL, payload, auth)
if result['data']['harTemplates']['pageInfo']['matchCount'] > 1:
print(f"Multiple templates with name {template_name}")
exit(1)
return result['data']['harTemplates']['edges'][0]['node']
except Exception as e:
print(f"Error caught: {e}")
exit(1)
def query_organization_id_by_name(organization_name):
query = """
query orgNameToOrgId($companyName:String!) {
organizations(search: { company: { eq: $companyName } } ) {
edges {
node {
id
}
}
}
}
"""
variables = {
"companyName": organization_name
}
payload = {
'query': query,
'variables': variables
}
auth = (username, password)
try:
result = run_gql(GQL_URL, payload, auth)
return result['data']['organizations']['edges'][0]['node']['id']
except Exception as e:
print(f"Error caught: {e}")
exit(1)
def create_from_har_template(template_id, definition):
query = """
mutation createFromHarTemplate($templateId:ID!, $definition:JSON!) {
createFromHarTemplate(id: $templateId, definition:$definition) {
harProviders {
id
name
type
organization {
company
}
}
}
}
"""
variables = {
"templateId": template_id,
"definition": definition,
}
payload = {
'query': query,
'variables': variables
}
auth = (username, password)
try:
result = run_gql(GQL_URL, payload, auth)
return result
except Exception as e:
print(f"Error caught: {e}")
exit(1)
####### main ######
parser = argparse.ArgumentParser(description='Install services from a template')
parser.add_argument('--url', help='Required argument -- URL of the SL1 GraphQL API endpoint. Example: https://sl1platform.company.com/gql OR http://sl1platform.company.com/gql', required=True)
parser.add_argument('--user', help='Required argument -- user name for the GraphQL request. Users will be prompted for a password at run time.', required=True)
parser.add_argument('--template', help='Required argument -- Service / HarProvider template name', required=True)
parser.add_argument('--org', help='Required argument -- SL1 Organization (Company name)', required=True)
parser.add_argument('--nameKey', help='Optional argument -- Unique name to append to services and to require in devices')
args = vars(parser.parse_args())
GQL_URL = args['url']
username = args['user']
template = args['template']
name_key = args['nameKey']
organization = args['org']
print(f"template: {template}")
print(f"nameKey: {name_key}")
print(f"org = {organization}")
password = getpass.getpass(prompt='Password: ')
organization_id = query_organization_id_by_name(organization)
har_template = query_template_by_name(template)
template_definition = har_template['definition']
template_id = har_template['id']
har_providers = template_definition['harProviders']
# loop through har providers and update organizations and filters
for har_provider in har_providers:
har_provider['organization']['id'] = organization_id
har_provider['contactOrganization']['id'] = organization_id
name = har_providers[0]['name']
new_name = name
if name_key:
new_name += f" - {name_key}"
har_provider['name'] = new_name
filterText = har_provider['filter']['filter']
filterJson = har_provider['filter']['search']
newFilterText = f'({filterText}) and (name contains {name_key})'
newFilterJson = {
"and": [
filterJson,
{
"name": {
"contains": name_key
}
}
]
}
har_provider['filter']['filter'] = newFilterText
har_provider['filter']['search'] = newFilterJson
# call createFromHarTemplate
result = create_from_har_template(template_id, template_definition)
print('')
print('The following services were created:')
for har_provider in result['data']['createFromHarTemplate']['harProviders']:
print(f' ServiceId: {har_provider["id"]}')
print(f' Name: {har_provider["name"]}')
print(f' Type: {har_provider["type"]}')
print(f' Organization: {har_provider["organization"]["company"]}')