Skip to content

Instantly share code, notes, and snippets.

@noahp
Created December 22, 2022 14:52
Show Gist options
  • Save noahp/afe781f2368d0e3fb2e30af909e1fcbb to your computer and use it in GitHub Desktop.
Save noahp/afe781f2368d0e3fb2e30af909e1fcbb to your computer and use it in GitHub Desktop.
Example using the Memfault Device API to update the Cohort for a Device ID
#!/usr/bin/env python3
"""
Example script to update the cohort for a device via the Memfault API.
Run with --help for usage information.
"""
import requests
import argparse
def auth_info(token_arg):
user, password = token_arg.split(":", 1)
return (user, password)
def update_cohort_for_device(org, project, device, cohort_name, token):
url = f"https://app.memfault.com/api/v0/organizations/{org}/projects/{project}/devices/{device}"
response = requests.patch(url, auth=auth_info(token), json={"cohort": cohort_name})
if response.status_code != 200:
raise Exception(f"Failed to update device {device}: {response.text}")
print(f"Updated device {device} to cohort {cohort_name}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cohort", help="The cohort name to update the device to", required=True)
parser.add_argument("--org", help="Memfault organization slug", required=True)
parser.add_argument("--project", help="Memfault project slug", required=True)
parser.add_argument(
"--token",
help=(
"The API token to use for authentication. Should be of the form"
" '[email protected]:password'. If Organization Access Token is used, the user field"
" will be blank: ':token'"
),
required=True,
)
parser.add_argument("device", help="The device IDs to update the cohort for", nargs="+")
args = parser.parse_args()
print(f"Updating devices {args.device} to cohort '{args.cohort}' ({args.cohort})")
for device in args.device:
update_cohort_for_device(args.org, args.project, device, args.cohort, args.token)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment