New Relic CLI is a command-line interface tool designed to interact with New Relic APIs, enabling users to manage and monitor applications, alert policies, dashboards, and more through terminal commands.
Key Features:
APM Applications Management: List applications, view details, and retrieve metrics for monitoring application performance.
Alert Policies Configuration: List and inspect alert policy configurations to ensure proactive monitoring of system health.
NRQL Execution: Run New Relic Query Language (NRQL) queries directly from the command line for real-time data analysis.
Deployment Tracking: Add deployment markers to applications, facilitating easier correlation between code changes and performance metrics.
Entity Search: Quickly search across all New Relic entity types, such as applications, services, and infrastructure components.
Output Formats: Support for table, JSON, and plain text output, enabling seamless integration into scripts and workflows.
Audience & Benefit:
Ideal for DevOps engineers, Site Reliability Engineers (SREs), developers, and IT operations teams who need to manage New Relic configurations programmatically. The tool provides a flexible alternative to graphical interfaces, allowing users to automate monitoring tasks and integrate New Relic data into existing CI/CD pipelines or monitoring workflows.
Available for installation via winget on Windows, ensuring easy setup across environments.
README
newrelic-cli
A command-line interface for interacting with New Relic APIs.
Features
APM Applications: List applications, view details, and retrieve available metrics
Alert Policies: List and inspect alert policy configurations
Dashboards: List and view dashboard details
Deployments: Track deployment markers for applications
Entities: Search across all New Relic entity types
Log Parsing Rules: Create, list, and delete log parsing rules
NerdGraph: Execute arbitrary GraphQL queries
NRQL: Run NRQL queries directly from the command line
Synthetic Monitors: List and inspect synthetic monitoring configurations
Users: List and view user details
Agent-First Output: Table and plain (scriptable) output on resource reads; JSON reserved for control-plane envelopes (set-credential, config show, config test with --json) and NerdGraph/NRQL passthrough (see cli-common docs/output-and-rendering.md §2)
Secure Credential Storage: API key stored in the OS keyring (macOS Keychain / Windows Credential Manager / Linux Secret Service), or an encrypted file with the explicit file-backend opt-in — never in plaintext and never in config.yml
go install github.com/open-cli-collective/newrelic-cli/cmd/nrq@latest
Quick Start
# 1. First-time setup (API key stored in the OS keyring — never in plaintext, never in config.yml)
nrq init
# 2. Verify configuration
nrq config show
# 3. Start using the CLI
nrq apps list
Configuration
Environment Variables
Variable
Description
Notes
NEWRELIC_API_KEY
New Relic User API key (NRAK-)
Setup ingress only — accepted by nrq init --api-key-from-env / nrq set-credential --from-env; not read at runtime
NEWRELIC_ACCOUNT_ID
New Relic account ID (non-secret)
Runtime override; precedence env > config.yml
NEWRELIC_REGION
API region: US (default) or EU (non-secret)
Runtime override; precedence env > config.yml
CLI Configuration Commands
# First-time setup (interactive no-echo API key prompt, or scripted ingress)
nrq init
op read "op://Vault/New Relic/api key" | nrq init --api-key-stdin --account-id 12345 --region US
# Fully non-interactive (central installer: op resolves refs into env vars)
nrq init --region US \
--api-key-from-env NEWRELIC_API_KEY \
--account-id-from-env NEWRELIC_ACCOUNT_ID \
--non-interactive
# Verify the resolved credential / account (exits non-zero if broken)
nrq me
# Low-level scripted secret ingress (single key, stdin or env — never a flag value)
nrq set-credential --key api_key --stdin
nrq set-credential --key api_key --from-env NEWRELIC_API_KEY
# Set non-secret config (written to config.yml)
nrq config set --account-id 12345678 --region EU
# View current configuration (never prints the key value)
nrq config show
# Remove credentials (idempotent, non-interactive)
nrq config clear # removes the keyring api_key
nrq config clear --all # also removes config.yml
> nrq config set-api-key is removed — the API key is no longer stored on
> disk or accepted as a positional/flag value (§1.5). Use nrq init or
> nrq set-credential. config set-account-id / config set-region are
> deprecated thin aliases of config set (one cycle).
> Installer / non-interactive init:--api-key-from-env ingests
> the secret into the keyring; --account-id-from-env ingests the
> non-secret account ID into config.yml (same op→env→--*-from-env
> channel, never the keyring). --non-interactive makes init fail loudly
> instead of prompting for any missing value — including the file-backend
> passphrase. nrq me resolves the credential and prints the authenticated
> user/account, exiting non-zero if the key is invalid or the configured
> account is inaccessible (scripted health check / installer verify).
Credential Storage
The API key lives only in the OS keyring via the shared
cli-common/credstore:
Platform
Backend
macOS
Keychain
Windows
Credential Manager
Linux
Secret Service (encrypted-file fallback when no keyring is available)
Backend selection has three user-configurable knobs that fall back to
auto-detect, in precedence order: --backend flag >
NEWRELIC_CLI_KEYRING_BACKEND env var > keyring.backend in
config.yml > auto-detect. Supported names: keychain, wincred,
secret-service, file, memory. The file backend additionally
requires NEWRELIC_CLI_KEYRING_PASSPHRASE.
Non-secret config (credential_ref, account_id, region) lives in
~/.config/newrelic-cli/config.yml (0600). A pre-existing macOS Keychain
entry or legacy ~/.config/newrelic-cli/credentials file is auto-migrated on
first run (one-time; the API key moves to the keyring, account_id/region into
config.yml, the legacy original is removed). Divergent legacy secret values
fail loudly rather than silently picking a winner.
Configuration Precedence
API key: OS keyring only at runtime (env is setup-ingress only).
Run nrq completion --help for detailed setup instructions.
Command Reference
Global Flags
Flag
Short
Default
Description
--output
-o
table
Output format: table, json, or plain
--no-color
false
Disable colored output
--help
-h
Show help for any command
--version
Show version information
Command Aliases
Most commands have shorter aliases for convenience:
Command
Aliases
applications
apps, app
alerts
alert
dashboards
dashboard, dash
deployments
deployment, deploy
entities
entity, ent
logs
log
synthetics
synthetic, syn
nerdgraph
ng, graphql
users
user
apps
Manage APM applications.
apps list
List all APM applications in your account.
nrq apps list
nrq apps list -o plain
Table Output:
ID NAME LANGUAGE STATUS
12345678 production-api ruby green
23456789 staging-api ruby gray
34567890 frontend-service nodejs green
apps get
Get details for a specific application.
nrq apps get
nrq apps get 12345678
Table Output:
ID: 12345678
Name: production-api
Language: ruby
Health Status: green
Reporting: true
Last Reported: 2024-01-15T10:30:00Z
apps metrics
List available metrics for an application.
nrq apps metrics
nrq apps metrics 12345678
alerts policies
Manage alert policies.
alerts policies list
List all alert policies.
nrq alerts policies list
Table Output:
ID NAME INCIDENT PREFERENCE
12345 Production Alerts PER_POLICY
23456 Staging Alerts PER_CONDITION
alerts policies get
Get details for a specific alert policy.
nrq alerts policies get
nrq alerts policies get 12345
dashboards
Manage dashboards.
dashboards list
List all dashboards.
nrq dashboards list
Table Output:
GUID NAME PAGES
ABC123... Production Overview 3
DEF456... API Performance 2
dashboards get
Get details for a specific dashboard.
nrq dashboards get
nrq dashboards get "ABC123..."
deployments
Manage deployment markers.
Aliases:deployment, deploy
deployments list
List deployments for an application with optional time filtering.
# By app ID
nrq deployments list 12345678
# By application name
nrq deployments list --name "My Application"
# By entity GUID
nrq deployments list --guid "MjcxMjY0MHxBUE18..."
# With time filtering
nrq deployments list 12345678 --since "7 days ago" --until "yesterday"
# Limit results
nrq deployments list 12345678 --limit 10
Flag
Short
Description
--name
-n
Application name to look up
--guid
-g
Entity GUID to look up
--since
Show deployments after this time
--until
Show deployments before this time
--limit
-l
Limit number of results
Time formats: Supports relative times (7 days ago, 2 hours ago), keywords (now, yesterday), and standard formats (2025-01-14, RFC3339).
Table Output:
ID REVISION DESCRIPTION USER TIMESTAMP
9876 v1.2.3 Bug fixes alice 2024-01-15T10:30:00Z
9875 v1.2.2 Feature release bob 2024-01-14T15:00:00Z
deployments create
Create a deployment marker for an application.
# By app ID
nrq deployments create 12345678 --revision v1.2.3
# By application name
nrq deployments create --name "My Application" --revision v1.2.3
# By entity GUID
nrq deployments create --guid "MjcxMjY0MHxBUE18..." --revision v1.2.3
# Full example
nrq deployments create 12345678 \
--revision v1.2.3 \
--description "Bug fixes and performance improvements" \
--user "alice" \
--changelog "Fixed memory leak, improved cache hit rate"
Flag
Short
Required
Description
--name
-n
No*
Application name to look up
--guid
-g
No*
Entity GUID to look up
--revision
-r
Yes
Deployment revision/version
--description
-d
No
Deployment description
--user
-u
No
User who deployed
--changelog
-c
No
Changelog information
*One of app ID (positional), --name, or --guid is required.
deployments search
Search deployments across all applications using NRQL WHERE clause syntax.
# Search by user
nrq deployments search "user = 'jane.doe@example.com'"
# Search by revision pattern
nrq deployments search "revision LIKE 'v2%'"
# Search with time range
nrq deployments search "description LIKE '%hotfix%'" --since "30 days ago"
# Limit results
nrq deployments search "changelog IS NOT NULL" --limit 50
Flag
Short
Description
--since
Search from this time
--until
Search until this time
--limit
-l
Maximum results (default: 100)
Table Output:
TIMESTAMP APP NAME REVISION DESCRIPTION USER
2024-01-15T10:30:00Z production-api v2.1.0 Hotfix jane.doe
2024-01-14T15:00:00Z staging-api v2.0.9 Bug fixes bob
entities
Search and manage New Relic entities.
Aliases:entity, ent
entities search
Search for entities using NRQL-style queries.
nrq entities search
Flag
Description
--link
Include New Relic deep link URLs in output
--since
Time range start for deep links (e.g., 1 hour ago, 2025-01-01)
--until
Time range end for deep links (e.g., now, 2025-01-15)
Examples:
# Find all applications
nrq entities search "type = 'APPLICATION'"
# Find by name pattern
nrq entities search "name LIKE 'production%'"
# Find by domain
nrq entities search "domain = 'APM'"
# Combined conditions
nrq entities search "type = 'APPLICATION' AND name LIKE 'prod%'"
# Include deep links with a time range
nrq entities search "domain = 'APM'" --link --since "1 hour ago"
Table Output:
GUID NAME TYPE DOMAIN ACCOUNT ID
ABC123... production-api APPLICATION APM 12345678
DEF456... production-web APPLICATION APM 12345678
logs link
Generate a New Relic deep link that opens the log viewer with a Lucene filter query pre-populated.
nrq logs link
Flag
Description
--since
Time range start (e.g., 30 minutes ago, 2025-01-01)
--until
Time range end (e.g., now, 2025-01-15)
When --since is provided without --until, the end defaults to now.
Examples:
# Link to error logs for a service
nrq logs link 'entity.name:"my-service" level:"ERROR"'
# With time range
nrq logs link 'level:"ERROR"' --since "30 minutes ago"
# Multiple entities
nrq logs link '(entity.name:"svc-a" OR entity.name:"svc-b") level:"ERROR"' --since "1 hour ago"
logs rules
Manage log parsing rules.
logs rules list
List all log parsing rules.
nrq logs rules list
Table Output:
ID DESCRIPTION ENABLED UPDATED
abc-123... Parse user login events true 2024-01-15T10:00:00Z
def-456... Extract error codes false 2024-01-10T08:00:00Z
logs rules create
Create a log parsing rule.
nrq logs rules create [flags]
Flag
Short
Required
Description
--description
-d
Yes
Rule description
--grok
-g
Yes
GROK pattern for parsing
--nrql
-n
Yes
NRQL matching condition
--enabled
-e
No
Enable the rule (default: true)
--lucene
-l
No
Lucene filter expression
Example:
nrq logs rules create \
--description "Parse user login events" \
--grok "User %{UUID:user_id} logged in from %{IP:ip_address}" \
--nrql "SELECT * FROM Log WHERE message LIKE 'User % logged in%'" \
--enabled true
logs rules update
Update an existing log parsing rule. Only specified fields are modified.
Execute a GraphQL query against the NerdGraph API.
nrq nerdgraph query
Examples:
# Get current user info
nrq nerdgraph query '{ actor { user { email name } } }'
# List accounts
nrq nerdgraph query '{ actor { accounts { id name } } }'
# Complex query
nrq nerdgraph query '{
actor {
account(id: 12345678) {
name
nrql(query: "SELECT count(*) FROM Transaction") {
results
}
}
}
}'
nrql
Execute NRQL queries.
nrq nrql
nrq nrql query
Flag
Description
--link
Output a New Relic deep link URL instead of executing the query
--since
Time range start, appended as SINCE clause (e.g., 7 days ago, 2025-01-01)
--until
Time range end, appended as UNTIL clause (e.g., now, 2025-01-15)
Examples:
# Transaction count
nrq nrql "SELECT count(*) FROM Transaction SINCE 1 hour ago"
# Average response time by app
nrq nrql "SELECT average(duration) FROM Transaction FACET appName SINCE 1 day ago"
# Error rate
nrq nrql "SELECT percentage(count(*), WHERE error IS true) FROM Transaction SINCE 1 hour ago"
# Top slow transactions
nrq nrql "SELECT average(duration), count(*) FROM Transaction FACET name SINCE 1 hour ago LIMIT 10"
# Generate a deep link to open the query in New Relic
nrq nrql --link "SELECT count(*) FROM Transaction SINCE 1 hour ago"
# Using --since flag (appends to query)
nrq nrql "SELECT count(*) FROM Transaction" --since "7 days ago"
synthetics
Manage synthetic monitors.
synthetics list
List all synthetic monitors.
nrq synthetics list
Table Output:
ID NAME TYPE STATUS FREQUENCY
abc-123... Production Health SIMPLE ENABLED 5
def-456... API Endpoint Check API ENABLED 1
synthetics get
Get details for a specific synthetic monitor.
nrq synthetics get
nrq synthetics get abc-123-def-456
users
Manage users.
users list
List all users in your account.
nrq users list
Table Output:
ID NAME EMAIL ROLE
12345 Alice Smith alice@example.com admin
23456 Bob Jones bob@example.com user
users get
Get details for a specific user.
nrq users get
nrq users get 12345
config
Configure nrq credentials.
Setting the API key
The API key is stored in the OS keyring and is never taken as a
flag/positional literal (§1.5). Use nrq init (the standard setup
path) or nrq set-credential for non-interactive ingress:
Resource reads emit text only (table by default, plain for scripts). JSON is
reserved per cli-common docs/output-and-rendering.md §2 for:
Control-plane envelopes: set-credential --json, config show --json,
config test --json — --json is a subcommand-local flag, not part of the
global -o selector.
Passthrough surfaces: nerdgraph query and nrql always emit JSON
regardless of -o (their data is GraphQL/NRQL result shape).
nrq -o json … on any resource command is rejected at the root. The
previously-deprecated root --json boolean alias is also removed — it
was a translation layer over -o json and has no closed-set value to
forward to.
Table (default)
Human-readable tabular format with headers and aligned columns.
nrq apps list
nrq apps list -o table
Plain
Tab-separated values without headers, ideal for shell scripting.
nrq apps list -o plain
Scripting Examples
Extract Application IDs
# Get all app IDs
nrq apps list -o plain | cut -f1
# Get app ID by name (plain output: ID is column 1, NAME is column 2)
nrq apps list -o plain | awk -F'\t' '$2 == "production-api" {print $1}'
# Check for unhealthy apps using the passthrough JSON surface
nrq nerdgraph query '{ actor { entitySearch(query: "domain = '\''APM'\''") { results { entities { name ... on AlertableEntityOutline { alertSeverity } } } } } }' \
| jq -r '.actor.entitySearch.results.entities[] | select(.alertSeverity != "NOT_ALERTING") | .name'
NRQL in Scripts
# Get error count as a number (nrql is a passthrough JSON surface)
ERROR_COUNT=$(nrq nrql query "SELECT count(*) FROM TransactionError SINCE 1 hour ago" | jq '.results[0].count')
echo "Errors in last hour: $ERROR_COUNT"
Exit Codes
Code
Description
0
Success
1
General error (API error, invalid arguments, etc.)
Go Library Usage
The api package can be imported and used as a Go library:
package main
import (
"fmt"
"log"
"github.com/open-cli-collective/newrelic-cli/api"
)
func main() {
// Create client from environment variables
client, err := api.New()
if err != nil {
log.Fatal(err)
}
// Or with explicit configuration
client = api.NewWithConfig(api.ClientConfig{
APIKey: "NRAK-xxxxxxxxxxxxxxxxxxxx",
AccountID: "12345678",
Region: "US",
})
// List applications
apps, err := client.ListApplications()
if err != nil {
log.Fatal(err)
}
for _, app := range apps {
fmt.Printf("%d: %s (%s)\n", app.ID, app.Name, app.HealthStatus)
}
// Execute NRQL query
result, err := client.QueryNRQL("SELECT count(*) FROM Transaction SINCE 1 hour ago")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Results: %+v\n", result)
// Execute GraphQL query
response, err := client.NerdGraphQuery(`{ actor { user { email } } }`, nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Response: %+v\n", response)
}
Available API Methods
Method
Description
ListApplications()
List all APM applications
GetApplication(id)
Get application details
ListApplicationMetrics(id)
List available metrics
ListAlertPolicies()
List alert policies
GetAlertPolicy(id)
Get policy details
ListDashboards()
List dashboards
GetDashboard(guid)
Get dashboard details
ListDeployments(appID)
List deployments
CreateDeployment(...)
Create deployment marker
SearchEntities(query)
Search entities
ListLogParsingRules()
List log parsing rules
CreateLogParsingRule(...)
Create parsing rule
DeleteLogParsingRule(id)
Delete parsing rule
GetLogParsingRule(id)
Get parsing rule by ID
UpdateLogParsingRule(id, update)
Update parsing rule
QueryNRQL(query)
Execute NRQL query
NerdGraphQuery(query, vars)
Execute GraphQL query
ListSyntheticMonitors()
List synthetic monitors
GetSyntheticMonitor(id)
Get monitor details
ListUsers()
List users
GetUser(id)
Get user details
Entity GUIDs
Important: New Relic Entity GUIDs are NOT standard UUIDs. They are base64-encoded, pipe-delimited strings with a specific structure:
base64(version|domain|type|id)
Encoded GUID
Decoded
MXxBUE18QVBQTElDQVRJT058MTIzNDU2Nzg=
1|APM|APPLICATION|12345678
MXxWSVp8REFTSEJPQVJEfDEyMzQ1
1|VIZ|DASHBOARD|12345
The EntityGUID type provides methods for working with these identifiers:
guid := api.EntityGUID("MXxBUE18QVBQTElDQVRJT058MTIzNDU2Nzg=")
// Parse components
version, domain, entityType, entityID, err := guid.Parse()
// Get specific components
domain, err := guid.Domain() // "APM"
entityType, err := guid.EntityType() // "APPLICATION"
entityID, err := guid.EntityID() // "12345678"
// For APM applications, extract the app ID
appID, err := guid.AppID() // "12345678"
// Validate format
if err := guid.Validate(); err != nil {
log.Printf("Invalid GUID: %v", err)
}
// Check if a string looks like a GUID
if api.IsValidEntityGUID(identifier) {
// Likely a GUID, not a name or numeric ID
}
Methods using Entity GUIDs:
GetDashboard(guid) - Takes an EntityGUID
SearchEntities(query) - Returns entities with GUIDs
Methods using numeric IDs:
GetApplication(id) - Takes an integer ID
GetAlertPolicy(id) - Takes an integer ID
GetUser(id) - Takes a string ID
APIKey Type
The APIKey type provides type-safe handling of New Relic User API keys:
// Create and validate an API key
key, warning, err := api.NewAPIKey("NRAK-ABCDEFGHIJ1234567890")
if err != nil {
log.Fatal(err)
}
if warning != "" {
log.Printf("Warning: %s", warning) // Non-NRAK prefix warning
}
// Validate an existing key
warning, err = key.Validate()
// Check prefix
if key.HasNRAKPrefix() {
// Standard User API key
}
Valid User API keys start with NRAK- and are typically 40+ characters. Keys without the NRAK- prefix will validate successfully but return a warning.
AccountID Type
The AccountID type provides type-safe handling of New Relic account identifiers:
// Create and validate an account ID
accountID, err := api.NewAccountID("12345678")
if err != nil {
log.Fatal(err) // Empty, non-numeric, or non-positive
}
// Get as integer (no error check needed - already validated)
id := accountID.Int()
// Check if empty
if accountID.IsEmpty() {
log.Fatal("Account ID required")
}
// Validate an existing AccountID
if err := accountID.Validate(); err != nil {
log.Fatal(err)
}
Account IDs must be positive integers. The Int() method provides pre-validated integer conversion without requiring error handling.
Error Handling
The API package provides structured error types and helper functions:
Error Types:
// APIError - HTTP API errors
var apiErr *api.APIError
if errors.As(err, &apiErr) {
fmt.Printf("HTTP %d: %s\n", apiErr.StatusCode, apiErr.Message)
}
// GraphQLError - NerdGraph query errors
var gqlErr *api.GraphQLError
if errors.As(err, &gqlErr) {
fmt.Printf("GraphQL error: %s\n", gqlErr.Message)
}
// ResponseError - Response parsing errors
var respErr *api.ResponseError
if errors.As(err, &respErr) {
fmt.Printf("Parse error: %s\n", respErr.Message)
}
Sentinel Errors:
api.ErrNotFound // Resource not found (404)
api.ErrUnauthorized // Invalid or missing API key (401)
api.ErrAPIKeyRequired // API key not configured
api.ErrAccountIDRequired // Account ID not configured
Helper Functions:
// Check for specific error conditions
if api.IsNotFound(err) {
fmt.Println("Resource does not exist")
}
if api.IsUnauthorized(err) {
fmt.Println("Check your API key")
}
Example:
app, err := client.GetApplication(12345678)
if err != nil {
if api.IsNotFound(err) {
log.Println("Application not found")
return
}
if api.IsUnauthorized(err) {
log.Fatal("Invalid API key - run 'nrq config set-api-key'")
}
log.Fatalf("API error: %v", err)
}
Utility Functions
App ID Resolution
Resolve application identifiers from multiple formats (numeric ID, Entity GUID, or application name):
// Accepts: numeric ID, Entity GUID, or application name
appID, err := client.ResolveAppID("my-application")
if err != nil {
log.Fatal(err)
}
// Now use appID with deployment or metrics APIs
deployments, err := client.ListDeployments(appID)
Flexible Time Parsing
Parse time strings in various formats for filtering: