• Stars
    star
    620
  • Rank 70,173 (Top 2 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Quick and reliable way to convert NGINX configurations into JSON and back.

Crossplane Logo

crossplane

Reliable and fast NGINX configuration file parser and builder

Install

You can install both the Command Line Interface and Python Module via:

pip install crossplane

Command Line Interface

usage: crossplane <command> [options]

various operations for nginx config files

optional arguments:
  -h, --help            show this help message and exit
  -V, --version         show program's version number and exit

commands:
  parse                 parses a json payload for an nginx config
  build                 builds an nginx config from a json payload
  lex                   lexes tokens from an nginx config file
  minify                removes all whitespace from an nginx config
  format                formats an nginx config file
  help                  show help for commands

crossplane parse

This command will take a path to a main NGINX config file as input, then parse the entire config into the schema defined below, and dumps the entire thing as a JSON payload.

usage: crossplane parse [-h] [-o OUT] [-i NUM] [--ignore DIRECTIVES]
                        [--no-catch] [--tb-onerror] [--single-file]
                        [--include-comments] [--strict]
                        filename

parses a json payload for an nginx config

positional arguments:
  filename              the nginx config file

optional arguments:
  -h, --help            show this help message and exit
  -o OUT, --out OUT     write output to a file
  -i NUM, --indent NUM  number of spaces to indent output
  --ignore DIRECTIVES   ignore directives (comma-separated)
  --no-catch            only collect first error in file
  --tb-onerror          include tracebacks in config errors
  --combine             use includes to create one single file
  --single-file         do not include other config files
  --include-comments    include comments in json
  --strict              raise errors for unknown directives

Privacy and Security

Since crossplane is usually used to create payloads that are sent to different servers, it's important to keep security in mind. For that reason, the --ignore option was added. It can be used to keep certain sensitive directives out of the payload output entirely.

For example, we always use the equivalent of this flag in the NGINX Amplify Agent out of respect for our users' privacy:

--ignore=auth_basic_user_file,secure_link_secret,ssl_certificate_key,ssl_client_certificate,ssl_password_file,ssl_stapling_file,ssl_trusted_certificate

Schema

Response Object

{
    "status": String, // "ok" or "failed" if "errors" is not empty
    "errors": Array,  // aggregation of "errors" from Config objects
    "config": Array   // Array of Config objects
}

Config Object

{
    "file": String,   // the full path of the config file
    "status": String, // "ok" or "failed" if errors is not empty array
    "errors": Array,  // Array of Error objects
    "parsed": Array   // Array of Directive objects
}

Directive Object

{
    "directive": String, // the name of the directive
    "line": Number,      // integer line number the directive started on
    "args": Array,       // Array of String arguments
    "includes": Array,   // Array of integers (included iff this is an include directive)
    "block": Array       // Array of Directive Objects (included iff this is a block)
}

Note

If this is an include directive and the --single-file flag was not used, an "includes" value will be used that holds an Array of indices of the configs that are included by this directive.

If this is a block directive, a "block" value will be used that holds an Array of more Directive Objects that define the block context.

Error Object

{
    "file": String,     // the full path of the config file
    "line": Number,     // integer line number the directive that caused the error
    "error": String,    // the error message
    "callback": Object  // only included iff an "onerror" function was passed to parse()
}

Note

If the --tb-onerror flag was used by crossplane parse, "callback" will contain a string that represents the traceback that the error caused.

Example

The main NGINX config file is at /etc/nginx/nginx.conf:

events {
    worker_connections 1024;
}

http {
    include conf.d/*.conf;
}

And this config file is at /etc/nginx/conf.d/servers.conf:

server {
    listen 8080;
    location / {
        try_files 'foo bar' baz;
    }
}

server {
    listen 8081;
    location / {
        return 200 'success!';
    }
}

So then if you run this:

crossplane parse --indent=4 /etc/nginx/nginx.conf

The prettified JSON output would look like this:

{
    "status": "ok",
    "errors": [],
    "config": [
        {
            "file": "/etc/nginx/nginx.conf",
            "status": "ok",
            "errors": [],
            "parsed": [
                {
                    "directive": "events",
                    "line": 1,
                    "args": [],
                    "block": [
                        {
                            "directive": "worker_connections",
                            "line": 2,
                            "args": [
                                "1024"
                            ]
                        }
                    ]
                },
                {
                    "directive": "http",
                    "line": 5,
                    "args": [],
                    "block": [
                        {
                            "directive": "include",
                            "line": 6,
                            "args": [
                                "conf.d/*.conf"
                            ],
                            "includes": [
                                1
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "file": "/etc/nginx/conf.d/servers.conf",
            "status": "ok",
            "errors": [],
            "parsed": [
                {
                    "directive": "server",
                    "line": 1,
                    "args": [],
                    "block": [
                        {
                            "directive": "listen",
                            "line": 2,
                            "args": [
                                "8080"
                            ]
                        },
                        {
                            "directive": "location",
                            "line": 3,
                            "args": [
                                "/"
                            ],
                            "block": [
                                {
                                    "directive": "try_files",
                                    "line": 4,
                                    "args": [
                                        "foo bar",
                                        "baz"
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    "directive": "server",
                    "line": 8,
                    "args": [],
                    "block": [
                        {
                            "directive": "listen",
                            "line": 9,
                            "args": [
                                "8081"
                            ]
                        },
                        {
                            "directive": "location",
                            "line": 10,
                            "args": [
                                "/"
                            ],
                            "block": [
                                {
                                    "directive": "return",
                                    "line": 11,
                                    "args": [
                                        "200",
                                        "success!"
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

crossplane parse (advanced)

This tool uses two flags that can change how crossplane handles errors.

The first, --no-catch, can be used if you'd prefer that crossplane quit parsing after the first error it finds.

The second, --tb-onerror, will add a "callback" key to all error objects in the JSON output, each containing a string representation of the traceback that would have been raised by the parser if the exception had not been caught. This can be useful for logging purposes.

crossplane build

This command will take a path to a file as input. The file should contain a JSON representation of an NGINX config that has the structure defined above. Saving and using the output from crossplane parse to rebuild your config files should not cause any differences in content except for the formatting.

usage: crossplane build [-h] [-d PATH] [-f] [-i NUM | -t] [--no-headers]
                        [--stdout] [-v]
                        filename

builds an nginx config from a json payload

positional arguments:
  filename              the file with the config payload

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         verbose output
  -d PATH, --dir PATH   the base directory to build in
  -f, --force           overwrite existing files
  -i NUM, --indent NUM  number of spaces to indent output
  -t, --tabs            indent with tabs instead of spaces
  --no-headers          do not write header to configs
  --stdout              write configs to stdout instead

crossplane lex

This command takes an NGINX config file, splits it into tokens by removing whitespace and comments, and dumps the list of tokens as a JSON array.

usage: crossplane lex [-h] [-o OUT] [-i NUM] [-n] filename

lexes tokens from an nginx config file

positional arguments:
  filename              the nginx config file

optional arguments:
  -h, --help            show this help message and exit
  -o OUT, --out OUT     write output to a file
  -i NUM, --indent NUM  number of spaces to indent output
  -n, --line-numbers    include line numbers in json payload

Example

Passing in this NGINX config file at /etc/nginx/nginx.conf:

events {
    worker_connections 1024;
}

http {
    include conf.d/*.conf;
}

By running:

crossplane lex /etc/nginx/nginx.conf

Will result in this JSON output:

["events","{","worker_connections","1024",";","}","http","{","include","conf.d/*.conf",";","}"]

However, if you decide to use the --line-numbers flag, your output will look like:

[["events",1],["{",1],["worker_connections",2],["1024",2],[";",2],["}",3],["http",5],["{",5],["include",6],["conf.d/*.conf",6],[";",6],["}",7]]

crossplane format

This is a quick and dirty tool that uses crossplane parse internally to format an NGINX config file. It serves the purpose of demonstrating what you can do with crossplane's parsing abilities. It is not meant to be a fully fleshed out, feature-rich formatting tool. If that is what you are looking for, then you may want to look writing your own using crossplane's Python API.

usage: crossplane format [-h] [-o OUT] [-i NUM | -t] filename

formats an nginx config file

positional arguments:
  filename              the nginx config file

optional arguments:
  -h, --help            show this help message and exit
  -o OUT, --out OUT     write output to a file
  -i NUM, --indent NUM  number of spaces to indent output
  -t, --tabs            indent with tabs instead of spaces

crossplane minify

This is a simple and fun little tool that uses crossplane lex internally to remove as much whitespace from an NGINX config file as possible without affecting what it does. It can't imagine it will have much of a use to most people, but it demonstrates the kinds of things you can do with crossplane's lexing abilities.

usage: crossplane minify [-h] [-o OUT] filename

removes all whitespace from an nginx config

positional arguments:
  filename           the nginx config file

optional arguments:
  -h, --help         show this help message and exit
  -o OUT, --out OUT  write output to a file

Python Module

In addition to the command line tool, you can import crossplane as a python module. There are two basic functions that the module will provide you: parse and lex.

crossplane.parse()

import crossplane
payload = crossplane.parse('/etc/nginx/nginx.conf')

This will return the same payload as described in the crossplane parse section, except it will be Python dicts and not one giant JSON string.

crossplane.build()

import crossplane
config = crossplane.build(
    [{
        "directive": "events",
        "args": [],
        "block": [{
            "directive": "worker_connections",
            "args": ["1024"]
        }]
    }]
)

This will return a single string that contains an entire NGINX config file.

crossplane.lex()

import crossplane
tokens = crossplane.lex('/etc/nginx/nginx.conf')

crossplane.lex generates 2-tuples. Inserting these pairs into a list will result in a long list similar to what you can see in the crossplane lex section when the --line-numbers flag is used, except it will obviously be a Python list of tuples and not one giant JSON string.

Other Languages

More Repositories

1

kubernetes-ingress

NGINX and NGINX Plus Ingress Controllers for Kubernetes
Go
4,540
star
2

docker-nginx

Official NGINX Dockerfiles
Shell
3,076
star
3

nginx-prometheus-exporter

NGINX Prometheus Exporter for NGINX and NGINX Plus
Go
1,441
star
4

NGINX-Demos

NGINX and NGINX Plus demos
HTML
1,232
star
5

nginx-ldap-auth

Example of LDAP authentication using ngx_http_auth_request_module
Python
678
star
6

ngx-rust

Rust binding for NGINX
Rust
673
star
7

kic-reference-architectures

MARA: Modern Application Reference Architecture
Python
625
star
8

ansible-role-nginx

Ansible role for installing NGINX
Shell
615
star
9

nginmesh

Istio compatible service mesh using NGINX
Go
611
star
10

nginx-s3-gateway

NGINX S3 Caching Gateway
JavaScript
442
star
11

nginx-gateway-fabric

NGINX Gateway Fabric provides an implementation for the Gateway API using NGINX as the data plane.
Go
361
star
12

docker-nginx-unprivileged

Unprivileged NGINX Dockerfiles
Shell
352
star
13

nginx-wiki

ARCHIVED -- Source for the now archived NGINX Wiki section of https://www.nginx.com
HTML
286
star
14

docker-nginx-amplify

Official NGINX and Amplify Dockerfiles
Shell
230
star
15

nginx-amplify-doc

Public documentation for Amplify
Makefile
201
star
16

nginx-openid-connect

Reference implementation of OpenID Connect integration for NGINX Plus
JavaScript
188
star
17

ansible-role-nginx-config

Ansible role for configuring NGINX
Jinja
144
star
18

mra-ingenious

A photo-sharing app built by NGINX and implemented using the Fabric Model from the Microservices Reference Architecture.
JavaScript
143
star
19

rtapi

Real time API latency analyzer - Create a PDF report and HDR histogram of your APIs
Go
133
star
20

nginx-otel

Perl
123
star
21

nginx-service-mesh

A service mesh powered by NGINX Plus to manage container traffic in Kubernetes environments.
Go
93
star
22

nginx-ingress-operator

WARNING - DEPRECATION NOTICE: The NGINX Ingress Operator has been updated to be a Helm based operator. This repo has been deprecated and will soon be archived - the new NGINX Ingress Operator repo can be found at https://github.com/nginxinc/nginx-ingress-helm-operator.
Go
65
star
23

ansible-collection-nginx

Ansible collection for NGINX
63
star
24

nginx-loadbalancer-kubernetes

A Kubernetes Controller to synchronize NGINX+ Resources with Kubernetes Ingress Resources
Go
57
star
25

nginx-asg-sync

NGINX Plus Integration with Cloud Autoscaling
Go
53
star
26

bank-of-sirius

Bank of Sirius
Java
52
star
27

nginx-plus-go-client

A client for NGINX Plus API for Go
Go
47
star
28

helm-charts

NGINX Helm Charts repository
47
star
29

nginx-openshift-router

NGINX and NGINX Plus OpenShift Routers
HTML
42
star
30

nginx-ingress-helm-operator

NGINX Ingress Operator for NGINX and NGINX Plus Ingress Controllers. Based on the Helm chart for NGINX Ingress Controller - https://github.com/nginxinc/helm-charts
Mustache
33
star
31

nginx-go-crossplane

A library for working with NGINX configs in Go
Go
31
star
32

docker-nginx-controller

Docker support for NGINX Controller Agent in Containers
Dockerfile
29
star
33

microservices-march

Examples from the Microservices March lectures and exercises.
26
star
34

nginx-ingress-workshops

Nginx Ingress Controller Hands on Workshops, with Lab Exercises and Guides
Shell
26
star
35

ngx-istio-mixer

NGINX module for Istio mixer
Rust
24
star
36

new-relic-agent

A new relic agent for NGINX Plus metrics
Python
23
star
37

nginx-saml

Perl
19
star
38

router-mesh-architecture

NGINX Router Mesh Network Architecture for Microservices
CSS
19
star
39

ansible-role-nginx-app-protect

Ansible role to install and configure NGINX App Protect (WAF and DoS) for NGINX Plus on your target host
Jinja
17
star
40

aws-ha-elastic-ip

Active-Passive HA Deployment on AWS Using an Elastic IP Address
Shell
17
star
41

website-resources-conf

content for nginx.com/resources/conf/ -- configuration files shared in blog posts, etc.
16
star
42

nginx-plus-dashboard

HTML
15
star
43

fabric-model-architecture

Repository for the NGINX Fabric Model Architecture
CSS
15
star
44

ngxinfo

Python
13
star
45

nginx-management-suite-iac

NMS IAC repo
HCL
12
star
46

Community-Code-of-Conduct

NGINX Open Source Community's Code of Conduct
11
star
47

nginx-amplify-agent

NGINX Amplify Agent
Python
11
star
48

mra-user-manager

User manager
HTML
10
star
49

snarejs

Snare.js
JavaScript
10
star
50

nginx-ns1-gslb

ARCHIVED - NGINX Plus Integration with NS1 GSLB
Go
10
star
51

mra-auth-proxy

Auth proxy for MRA
Jinja
9
star
52

nginx-wrapper

NGINX Event Process Wrapper
Go
9
star
53

ngx-stream-nginmesh-dest

Nginx module to get dest ip and port
C
8
star
54

ansible-role-nginx-unit

Ansible role for NGINX Unit
Jinja
7
star
55

ansible-role-nginx-management-suite

Ansible role for the NGINX Management Suite
Jinja
7
star
56

nginx-for-azure-deploy-action

Github Actions to sync NGINX configs into the NGINX for Azure service.
TypeScript
7
star
57

ebook-managing-kubernetes-nginx

Shell
7
star
58

template-repository

A template repository for new NGINX projects
7
star
59

nginx-unsupported-modules

Container builds of unsupported NGINX modules
Shell
6
star
60

nginx-hugo-theme

A hugo theme for NGINX documentation
CSS
6
star
61

mra-content-service

Go
6
star
62

mra-photouploader

HTML
5
star
63

ansible_collection_nginx_controller

Collection of NGINX Controller Roles for Ansible
5
star
64

mra-photoresizer

HTML
5
star
65

mra-pages

JavaScript
4
star
66

nginx-controller-lab

Shell
4
star
67

.github

4
star
68

mra-album-manager

Ruby
4
star
69

nginxaas-for-azure-snippets

Example ARM templates for common NGINX for Azure use cases
Python
3
star
70

ansible_role_nginx_controller_agent

Ansible role for installing the NGINX Controller agent
Jinja
3
star
71

ansible-role-nginx_controller_application

Jinja
3
star
72

nap-dos-arbitrator-helm-chart

Smarty
3
star
73

nginx-plus-install-tools

NGINX Plus Install tools
Shell
3
star
74

ansible-role-nginx_controller_publish_api

Jinja
2
star
75

kic-test-containers

Docker containers used by the KIC team
Go
2
star
76

ansible-role-nginx_controller_user

Jinja
2
star
77

ansible-role-nginx_controller_environment

Managing environments within NGINX Controller
Jinja
2
star
78

ansible-role-nginx_controller_api_definition_import

Jinja
2
star
79

ansible-role-nginx-controller-gateway

Jinja
2
star
80

ansible-role-nginx_controller_location

Jinja
2
star
81

ansible_role_nginx_controller_install

Ansible role for installing NGINX Controller
Jinja
2
star
82

ansible-role-nginx-controller-certificate

Jinja
2
star
83

ansible-role-nginx-controller-component

Jinja
2
star
84

ansible_role_nginx_controller_generate_token

Jinja
2
star
85

ansible-role-nginx-controller-license

Jinja
2
star
86

ansible-role-nginx_controller_integration

Jinja
2
star
87

nginx-aws-signature

NGINX AWS Signature Library to authenticate AWS services such as S3 and Lambda via NGINX and NGINX Plus.
JavaScript
2
star
88

nginx-basics-workshops

HTML
2
star
89

homebrew-tap

Ruby
1
star
90

ansible-role-nginx_controller_user_role

Jinja
1
star
91

ansible-role-nginx_controller_forwarder

Jinja
1
star