Skip to content

Instantly share code, notes, and snippets.

@PiotrCzapla
Last active June 24, 2022 17:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PiotrCzapla/3175b6225acdfde731671c5f54177e87 to your computer and use it in GitHub Desktop.
Save PiotrCzapla/3175b6225acdfde731671c5f54177e87 to your computer and use it in GitHub Desktop.
Python script to log a new relic deployment information with minimal python dependency
"""
Python script to log a new relic deployment information with minimsl dependencies
# Usage:
The scripts accepts either `list` or `new` commands
$ API_KEY="..." APP_ID="..."" python nr_deployment.py new 'rev id' "my title"\
--description="some desc" --timestamp='2022-01-02' --user='test'
# Credentials configuration
Configure your api key and app id as env variables as follows:
Using bash
API_KEY="..." APP_ID="..."" REGION="eu" python nr_deployment.py list
or using 1password and .env file
op run --env-file=.env python nr_deployment.py list
.env then should look like this:
entry = "Personal/New Relic"
APP_ID = op://$entry/app_id
API_KEY = op://$entry/api_key
DEFAULT_USER = op://$entry/username
REGION = eu
# Dependencies
pip install fire requests
"""
import os
from datetime import datetime, timezone
import json
import requests
import fire
REGION=os.environ.get("REGION","eu")
API_KEY=os.environ["API_KEY"]
APP_ID=os.environ["APP_ID"]
DEFAULT_USER=os.environ.get("DEFAULT_USER")
URLS={
"eu":"https://api.eu.newrelic.com/v2/",
"us":"https://api.newrelic.com/v2/"
}
URL=URLS[REGION]
def print_response(r):
print(json.dumps(r.json(), indent=2))
def api_request(method, endpoint, headers=None, **kwargs):
if headers is None: headers = {}
headers.update({"X-Api-Key": API_KEY, "Content-Type": "application/json"})
if not endpoint.endswith(".json"):
endpoint = endpoint+".json"
return requests.request(method, f"{URL}{endpoint}", headers=headers, **kwargs)
def list_deployments():
print_response(api_request("GET", "applications.json"))
def new_deployment(revision, title, description="", timestamp:datetime=None, user=DEFAULT_USER):
timestamp = datetime.now() if timestamp is None else timestamp
if isinstance(timestamp, str):
timestamp = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
timestamp = timestamp.astimezone().astimezone(timezone.utc)
timestamp = timestamp.strftime("%Y-%m-%dT%H:%M:%S") # no time zone info but in utc
json={"deployment": {
"revision": revision,
"changelog": title,
"description": description,
"user": user,
"timestamp": timestamp
}}
print("request: ", json)
print_response(api_request("POST", f"applications/{APP_ID}/deployments.json", json=json))
if __name__ == "__main__":
fire.Fire({'new': new_deployment, 'list': list_deployments})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment