This is the second part in a five-part series on automating common DevOps tasks in New Relic.
The first part shows you how to audit your services with Python and the NerdGraph API, and also includes the sample API code that this post uses.
All of the code from this five-part series can be found in this repository.
When you're working with large amounts of data or data from many different sources, it's a good idea to use tags to help with organization. While you can tag data manually in New Relic, you can make your workflow more efficient and tag New Relic entities via API calls instead. Need a better way to segment your apps based on environments? You can do it automatically via the API! The Python code snippets in this post show examples of creating, reading, updating, and deleting tags using GraphQL.
Prerequisites
If you plan to follow along with this tutorial and use Python to make your API calls, you need:
- Python 3 installed on your machine. To download and install, visit python.org. Note that you can also make API calls to the specified endpoints using languages other than Python as well.
- With Python, you’ll be using the requests and json modules.
- A New Relic account. Sign up for free.
- An application instrumented with New Relic APM and Infrastructure. Follow along with this guide to instrument an application.
- A New Relic API key. Follow these steps to get an API key, or, if you’re already signed in, generate an API key on the API keys page. To learn more, see Keys for querying and configuration.
- The Python starter code, which is in part one of this blog series.
The next video shows you how to manage your tags using the NerdGraph API.
Creating tags
Here's an example query for creating a tag using the NerdGraph API. If you need more context on the starter code, see Using Python to make an API call in part one of this series.
import requests
import json
from license import user_key
def nerdgraph_createtags(key):
# GraphQL query to NerdGraph
query = """
mutation {
taggingAddTagsToEntity(
guid: "XXX",
tags: [
{ key: "env", values: ["prod"]},
{ key: "cloud", values: ["AWS", "ap-southeast"]},
{ key: "team", values: ["web", "content", "frontend"]}
]) {
errors {
message
}
}
}"""
# NerdGraph endpoint
endpoint = "https://api.newrelic.com/graphql"
headers = {'API-Key': f'{key}'}
response = requests.post(endpoint, headers=headers, json={"query": query})
if response.status_code == 200:
# convert a JSON into an equivalent python dictionary
dict_response = json.loads(response.content)
print(dict_response)
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json(), indent=2)
# print(json_response)
else:
# raise an exepction with a HTTP response code, if there is an error
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_createtags(user_key)
Reading tags
Here's how you can read tags using the NerdGraph API.
import requests
import json
from license import user_key
def nerdgraph_readtags(key):
# GraphQL query to NerdGraph
query = """
{
actor {
entitySearch(query: "name = 'XXX'") {
results {
entities {
tags {
key
values
}
guid
name
account {
name
id
}
}
}
}
}
}"""
# NerdGraph endpoint
endpoint = "https://api.newrelic.com/graphql"
headers = {'API-Key': f'{key}'}
response = requests.post(endpoint, headers=headers, json={"query": query})
if response.status_code == 200:
# convert a JSON into an equivalent python dictionary
dict_response = json.loads(response.content)
print(dict_response["data"]["actor"]["entitySearch"]["results"]["entities"])
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json(), indent=2)
# print(json_response)
else:
# raise an exepction with a HTTP response code, if there is an error
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_readtags(user_key)
Updating tags
Here's how you can update dates with the NerdGraph API.
import requests
import json
from license import user_key
def nerdgraph_updatetags(key):
# GraphQL query to NerdGraph
query = """
mutation {
taggingReplaceTagsOnEntity(
guid: "XXX",
tags: [
{ key: "env", values: ["staging"]},
{ key: "cloud", values: ["AWS", "ap-southeast"]},
{ key: "team", values: ["web", "content", "frontend"]}
]) {
errors {
message
}
}
}"""
# NerdGraph endpoint
endpoint = "https://api.newrelic.com/graphql"
headers = {'API-Key': f'{key}'}
response = requests.post(endpoint, headers=headers, json={"query": query})
if response.status_code == 200:
# convert a JSON into an equivalent python dictionary
dict_response = json.loads(response.content)
print(dict_response)
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json(), indent=2)
# print(json_response)
else:
# raise an exepction with a HTTP response code, if there is an error
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_updatetags(user_key)
Deleting tags
Here's how to delete tags using the NerdGraph API.
import requests
import json
from license import user_key
def nerdgraph_deletetags(key):
# GraphQL query to NerdGraph
query = """
mutation {
taggingDeleteTagFromEntity(
guid: "XXX",
tagKeys: ["env", "team"]) {
errors {
message
}
}
}"""
# NerdGraph endpoint
endpoint = "https://api.newrelic.com/graphql"
headers = {'API-Key': f'{key}'}
response = requests.post(endpoint, headers=headers, json={"query": query})
if response.status_code == 200:
# convert a JSON into an equivalent python dictionary
dict_response = json.loads(response.content)
print(dict_response)
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json(), indent=2)
# print(json_response)
else:
# raise an exepction with a HTTP response code, if there is an error
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_deletetags(user_key)
To learn more, see the NerdGraph tutorial on tags.
Stay tuned for part three in the series, where you'll learn how to export your telemetry data with Python and the NerdGraph API.
Interested in what else New Relic has to offer? Check out our Infrastructure monitoring platform.
Étapes suivantes
Learn what else you can do with the Nerdgraph API and continue to build DevOps into your observability practice. If you don't have a New Relic account yet, sign up today. Your free account includes 100 GB/month of free data ingest, one free full-access user, and unlimited free basic users.
Read the next part in this 5-part series: Export your telemetry data with Python and the NerdGraph API.
Les opinions exprimées sur ce blog sont celles de l'auteur et ne reflètent pas nécessairement celles de New Relic. Toutes les solutions proposées par l'auteur sont spécifiques à l'environnement et ne font pas partie des solutions commerciales ou du support proposés par New Relic. Veuillez nous rejoindre exclusivement sur l'Explorers Hub (discuss.newrelic.com) pour toute question et assistance concernant cet article de blog. Ce blog peut contenir des liens vers du contenu de sites tiers. En fournissant de tels liens, New Relic n'adopte, ne garantit, n'approuve ou n'approuve pas les informations, vues ou produits disponibles sur ces sites.