Skip to content

Instantly share code, notes, and snippets.

@NWMichl
Last active June 29, 2021 18:58
Show Gist options
  • Save NWMichl/984a39652c2f92fb4afb5fb3b6891b9e to your computer and use it in GitHub Desktop.
Save NWMichl/984a39652c2f92fb4afb5fb3b6891b9e to your computer and use it in GitHub Desktop.
Chatbot demo to return the Cisco ACI Health Score to a Slack workspace using FastAPI
from fastapi import FastAPI, Form
import requests, json
SLACK_VERIFICATION_TOKEN = "OnLmGpOwclDyXMNuNSRI5HAQ"
APIC_URL = 'sandboxapicdc.cisco.com'
APIC_USERNAME = 'admin'
APIC_PASSWORD = 'ciscopsdt'
def apic_login(apic: str, username: str, password: str) -> dict:
""" APIC login and return session cookie """
apic_cookie = {}
credentials = {'aaaUser': {'attributes': {'name': APIC_USERNAME, 'pwd': APIC_PASSWORD }}}
json_credentials = json.dumps(credentials)
base_url = 'https://' + apic + '/api/aaaLogin.json'
login_response = requests.post(base_url, data=json_credentials)
login_response_json = json.loads(login_response.text)
token = login_response_json['imdata'][0]['aaaLogin']['attributes']['token']
apic_cookie['APIC-Cookie'] = token
return apic_cookie
def apic_query(apic: str, path: str, cookie: dict) -> dict:
""" APIC 'GET' query and return response """
base_url = 'https://' + apic + path
get_response = requests.get(base_url, cookies=cookie)
return get_response
def apic_logout(apic: str, cookie:dict) -> dict:
""" APIC logout and return response """
base_url = 'https://' + apic + '/api/aaaLogout.json'
post_response = requests.post(base_url, cookies=cookie)
return post_response
app = FastAPI()
@app.get("/")
def root():
return {"message": "API Server seems to be up"}
@app.post("/acibot")
def slack_slash(text: str = Form("missing argument", max_length=20), token: str = Form(...)):
"""
Slack ACIBOT queries an ACI Fabric for some interesting metrics.
Visit /aci help for supported commands.
"""
if not token == SLACK_VERIFICATION_TOKEN:
result = {
"text": "ERROR: Wrong SLACK_VERIFICATION_TOKEN in request!"
}
return result
if text == "help":
result = {
"response_type": "in_channel",
"text": """Hi there! I accept the following commands:
`/aci health` - show total system health
"""
}
elif text == "health":
apic_cookie = apic_login(apic=APIC_URL, username=APIC_USERNAME, password=APIC_PASSWORD)
response = apic_query(apic=APIC_URL, path='/api/class/fabricHealthTotal.json', cookie=apic_cookie)
logout_response = apic_logout(apic=APIC_URL, cookie=apic_cookie)
response_json = json.loads(response.text)
fab_health_total = response_json['imdata'][0]['fabricHealthTotal']['attributes']['cur']
result = {
"response_type": "in_channel",
"text": "Total System Health: " + fab_health_total
}
else:
result = {
"text": "_" + text + "_? I don't know what you're talking about. Please visit `/aci help`"
}
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment