This is the fifth part of a five-part series on automating common DevOps tasks in New Relic.
- Part 1 shows you how to audit your services with Python and the NerdGraph API and includes the sample API code that this post uses.
- Part 2: Automate your tags with Python and the NerdGraph API
- Part 3: Export telemetry data with Python and the NerdGraph API
- Part 4: Export dashboards with Python and the NerdGraph API
All of the code from this five-part series can be found in this repository.
For security reasons, it's important that you regularly rotate your license keys. License key rotation is even required in some industries, such as those using the Payment Card Industry Data Security Standard (PCI DSS). This post shows you how to create, read, update, and delete license keys using New Relic Query Language (NRQL) and Python.
Creating a license key
Here's how you can create a license key using the NerdGraph API. The following code defines and calls a Python method called nerdgraph_createkey
. Note that each XXX
in {accountId: XXX, userId: XXX, name: "XXX", notes: "XXX" }
needs to be replaced. accountId
and userId
are integers while name
and notes
are strings.
If the response is successful, you can optionally serialize the object as a JSON-formatted stream or print it as a Python dictionary.
import requests
import json
from license import user_key
def nerdgraph_createkey(key):
# GraphQL query to NerdGraph
query = """
mutation {
apiAccessCreateKeys(keys: {user: {accountId: XXX, userId: XXX, name: "XXX", notes: "XXX" } }) {
createdKeys {
id
key
name
notes
type
}
errors {
message
type
... on ApiAccessIngestKeyError {
accountId
errorType
ingestType
}
}
}
}"""
# 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
json_dictionary = json.loads(response.content)
print(json_dictionary['data']['apiAccessCreateKeys']['createdKeys'])
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json()["data"]["dashboardCreateSnapshotUrl"], indent=2)
# print(json_response)
else:
# raise an error with a HTTP response code
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_createkey(user_key)
Reading a license key
This query will return the license keys for an account (including the name associated with the key and any notes). Note that the code follows the same structure as the previous example. The query is different and the response is also parsed differently.
import requests
import json
from license import user_key
def nerdgraph_readkey(key):
# GraphQL query to NerdGraph
query = """
{
actor {
apiAccess {
keySearch(query: {types: USER, scope: {ingestTypes: LICENSE}}) {
keys {
name
key
type
notes
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
json_dictionary = json.loads(response.content)
print(json_dictionary['data']['actor']['apiAccess']['keySearch'])
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json()['data']['actor']['apiAccess']['keySearch'], indent=2)
# print(json_response)
else:
# raise an error with a HTTP response code
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_readkey(user_key)
Updating a license key
Next, let's take a look at how you can update a license key. Once again, you need to replace each XXX
in {keyId: "XXX", name: "XXX", notes: "XXX" }
.
import requests
import json
from license import user_key
def nerdgraph_updatekey(key):
# GraphQL query to NerdGraph
query = """
mutation {
apiAccessUpdateKeys(keys: {user: {keyId: "XXX", name: "XXX", notes: "XXX" } }) {
updatedKeys {
id
key
type
name
notes
}
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
json_dictionary = json.loads(response.content)
print(json_dictionary)
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json()["data"]["dashboardCreateSnapshotUrl"], indent=2)
# print(json_response)
else:
# raise an error with a HTTP response code
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_updatekey(user_key)
Deleting license keys
Finally, you can delete license keys with the following code.
import requests
import json
from license import user_key
def nerdgraph_deletekey(key):
# GraphQL query to NerdGraph
query = """
mutation {
apiAccessDeleteKeys(keys: {userKeyIds: "XXX"}) {
deletedKeys {
id
}
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
json_dictionary = json.loads(response.content)
print(json_dictionary)
# optional - serialize object as a JSON formatted stream
# json_response = json.dumps(response.json()["data"]["dashboardCreateSnapshotUrl"], indent=2)
# print(json_response)
else:
# raise an error with a HTTP response code
raise Exception(f'Nerdgraph query failed with a {response.status_code}.')
nerdgraph_deletekey(user_key)
To learn more, see the NerdGraph tutorial on managing license keys. Along with learning about license keys with python, take a read at our best tools for cloud automation.
핵심 요약
Learn what else you can do with the Nerdgraph API, API-enabled architectures, 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. To see more about what New Relic offers, try our Infrastructure monitoring integration
Interested in more? Get started with New Relic Infrastructure monitoring today.
이 블로그에 표현된 견해는 저자의 견해이며 반드시 New Relic의 견해를 반영하는 것은 아닙니다. 저자가 제공하는 모든 솔루션은 환경에 따라 다르며 New Relic에서 제공하는 상용 솔루션이나 지원의 일부가 아닙니다. 이 블로그 게시물과 관련된 질문 및 지원이 필요한 경우 Explorers Hub(discuss.newrelic.com)에서만 참여하십시오. 이 블로그에는 타사 사이트의 콘텐츠에 대한 링크가 포함될 수 있습니다. 이러한 링크를 제공함으로써 New Relic은 해당 사이트에서 사용할 수 있는 정보, 보기 또는 제품을 채택, 보증, 승인 또는 보증하지 않습니다.