Crossplane NGINX Configuration Parser

0.5.8 · active · verified Fri Apr 10

Crossplane is a Python library and command-line interface (CLI) tool for reliably and quickly parsing and building NGINX configuration files. It handles includes, variables, and common NGINX directives, providing a structured JSON representation of the configuration. The current version is 0.5.8, with releases occurring periodically to update NGINX directive definitions and fix bugs.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `crossplane.parse()` to transform an NGINX configuration string into a structured Python object (often represented as JSON), and then `crossplane.build()` to convert it back into an NGINX configuration string. This allows for programmatic inspection and modification of NGINX configurations.

from crossplane import parse, build
import json

nginx_config_content = '''
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for";

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }
}
'''

# Parse the NGINX configuration string
parsed_config = parse(nginx_config_content, filename='nginx.conf')

# Print the parsed structure (JSON representation)
print("Parsed NGINX Config (JSON):")
print(json.dumps(parsed_config, indent=2))

# Example of accessing parsed data
if parsed_config['status'] == 'ok' and parsed_config['config']:
    first_file_config = parsed_config['config'][0]['parsed']
    print(f"\nWorker processes: {first_file_config[1]['args'][0]}")

    # Build the config back into a string (simplified, without complex includes)
    # For real file paths, ensure the 'filename' parameter matches where crossplane expects to find included files.
    rebuilt_config = build(parsed_config)
    print("\nRebuilt NGINX Config:")
    print(rebuilt_config)

view raw JSON →