# Nushell Plugin Examples

Practical examples using Provisioning's native Rust plugins for template rendering,
configuration, encryption, and secrets management.

## Template Rendering with Tera

Generate infrastructure configurations from templates:

```nushell
# Load plugin
plugin add nu_plugin_tera

# Define template
let infra_template = "
servers:
  {% for server in servers %}
  - name: {{ server.name }}
    provider: {{ server.provider }}
    cpu: {{ server.cpu }}
    memory: {{ server.memory }}
    tags:
      {% for tag in server.tags %}
      - {{ tag }}
      {% endfor %}
  {% endfor %}
load_balancer:
  name: {{ load_balancer.name }}
  replicas: {{ servers | length }}
"

# Define context
let context = {
  servers: [
    { name: "web-01", provider: "aws", cpu: 4, memory: 8, tags: ["frontend", "prod"] },
    { name: "web-02", provider: "aws", cpu: 4, memory: 8, tags: ["frontend", "prod"] },
    { name: "api-01", provider: "upcloud", cpu: 8, memory: 16, tags: ["backend", "prod"] }
  ],
  load_balancer: { name: "main-lb" }
}

# Render template
$infra_template | tera render $context
```

Generate from file:

```nushell
# Load template file
let template = open templates/infrastructure.j2 | into string

# Render with variables from CSV
let servers = open servers.csv | from csv
let context = { servers: $servers }

$template | tera render $context | save generated-config.yaml
```

## Configuration with Nickel

Validate and merge Nickel configurations:

```nushell
# Load plugin
plugin add nu_plugin_nickel

# Parse Nickel expression
let base_config = "{ name = \"app\", version = \"1.0\", replicas = 3 }" | nickel eval

# Load from file
let env_config = open config/prod-defaults.ncl | into string | nickel eval

# Merge configurations
let merged = $base_config | nickel merge $env_config

# Validate against schema
let schema = open schemas/app-schema.ncl | into string
$merged | nickel validate --schema-file ([$schema] | into string)

# Output as YAML
$merged | nickel to-yaml | save final-config.yaml
```

Transformation example:

```nushell
# Transform YAML to type-safe Nickel
let yaml_config = open untrusted-config.yaml | from yaml
let typed_config = $yaml_config | nickel validate --schema deployment-schema.ncl

# If validation passes, use config; otherwise fail with error
if ($typed_config | is-valid) {
  $typed_config | nickel to-json | save config.json
} else {
  error "Configuration validation failed"
}
```

## Secrets with SecretumVault

Post-quantum cryptography secure secret management:

```nushell
# Load plugin
plugin add nu_plugin_secretumvault

# Store credentials
secretumvault-plugin store "database-password" "MySecurePassword123!"
secretumvault-plugin store "api-key" "sk-1234567890abcdef"

# Retrieve for use
let db_pass = (secretumvault-plugin retrieve "database-password")
let api_key = (secretumvault-plugin retrieve "api-key")

# Use in environment
with-env { DB_PASSWORD: $db_pass, API_KEY: $api_key } {
  ./deploy.sh
}
```

Batch secret operations:

```nushell
# Store multiple secrets from CSV
let secrets = open secrets.csv | from csv
$secrets | each { | secret |
  secretumvault-plugin store $secret.name $secret.value
}

# Verify storage
secretumvault-plugin list | length
```

## Encryption Operations

Encrypt/decrypt data with KMS:

```nushell
plugin add nu_plugin_kms

# Encrypt data
let sensitive_data = "confidential-information"
let encrypted = $sensitive_data | kms encrypt --algorithm aes-256-gcm

# Store encrypted data
{ data: $encrypted, timestamp: (now) } | to json | save encrypted-backup.json

# Later: decrypt
let encrypted_backup = open encrypted-backup.json | from json
let decrypted = $encrypted_backup.data | kms decrypt

print $decrypted
```

File encryption:

```nushell
# Encrypt entire file
open infrastructure.ncl | kms encrypt --key master-key | save infrastructure.ncl.enc

# Decrypt and validate
open infrastructure.ncl.enc | kms decrypt | nickel eval
```

## Authentication Token Management

JWT token operations:

```nushell
plugin add nu_plugin_auth

# Login and get token
let token = auth login --method jwt --provider openid

# Store in secure keyring
auth set-token $token --store-keyring

# Verify token validity
auth verify-token

# Get current user
auth whoami

# Refresh expired token
let new_token = auth refresh-token
auth set-token $new_token
```

OAuth2 integration:

```nushell
# GitHub authentication
let token = auth login --method oauth2 --provider github

# Use token for API calls
with-env { GITHUB_TOKEN: $token } {
  http get  [https://api.github.com/user](https://api.github.com/user)
}
```

## Cryptographic Hashing

Validate data integrity:

```nushell
plugin add nu_plugin_hashes

# Hash file for integrity verification
let file_hash = open deployment.tar.gz | hashes sha256

# Store hash
{ file: "deployment.tar.gz", hash: $file_hash } | to json | save checksums.json

# Verify downloaded file
let expected = open checksums.json | from json | where file == "deployment.tar.gz" | first | get hash
let actual = open deployment.tar.gz | hashes sha256

if ($expected == $actual) {
  print "Integrity verified"
} else {
  error "Checksum mismatch - file corrupted"
}
```

Batch hashing:

```nushell
# Hash all configuration files
glob "config/**/*.ncl" | each { | file |
  {
    file: $file,
    sha256: (open $file | hashes sha256),
    blake3: (open $file | hashes blake3)
  }
} | save config-hashes.json
```

## Syntax Highlighting

Format code for output:

```nushell
plugin add nu_plugin_highlight

# Highlight Nickel code
let nickel_code = open schemas/infrastructure.ncl | into string
$nickel_code | highlight --language nickel

# Highlight and log
let bash_script = open deployment.sh | into string
print ($bash_script | highlight --language bash)
```

## Image Processing

Logo and diagram management:

```nushell
plugin add nu_plugin_image

# Resize logo for documentation
open assets/logo.png | image resize --width 200 --height 200 | save assets/logo-thumb.png

# Convert format for web
open assets/diagram.png | image convert --format webp | save assets/diagram.webp

# Get image metadata
open assets/screenshot.jpg | image info
```

## Clipboard Operations

Copy deployment confirmation:

```nushell
plugin add nu_plugin_clipboard

# Generate summary
let summary = "Deployment to production approved by admin. Config hash: $(config | hashes sha256)"

# Copy to clipboard for sharing
$summary | clipboard copy

print "Summary copied to clipboard"
```

## Desktop Notifications

Alert on long operations:

```nushell
plugin add nu_plugin_desktop_notifications

# Start deployment
print "Starting deployment..."

# Do work
time { ./deploy.sh }

# Notify completion
notifications notify "Deployment completed successfully" --type success

# Error notification
if $env.LAST_EXIT_CODE != 0 {
  notifications notify "Deployment failed with errors" --type error
}
```

## QR Code Generation

Share configuration links:

```nushell
plugin add nu_plugin_qr_maker

# Generate QR for workspace setup link
let setup_link = " [https://provisioning.example.com/setup?token=abc123"](https://provisioning.example.com/setup?token=abc123")
$setup_link | qr-maker generate --output workspace-setup.png

# ASCII QR for terminal
let config_command = "provisioning workspace load prod-workspace"
$config_command | qr-maker generate --ascii
```

## Port Utilities

Network diagnostics:

```nushell
plugin add nu_plugin_port_extension

# Find process using port
port-extension list-open --port 8080

# Check if port available
port-extension check-available --port 9000

# List all listening ports
port-extension list-listening
```

## Combined Workflow

Complete secure deployment workflow:

```nushell
# Initialize plugins
plugin add nu_plugin_nickel
plugin add nu_plugin_secretumvault
plugin add nu_plugin_kms
plugin add nu_plugin_auth
plugin add nu_plugin_hashes
plugin add nu_plugin_tera

# 1. Authenticate
let token = auth login --method oauth2 --provider github
auth set-token $token --store-keyring

# 2. Generate config from template
let template = open deployment-template.j2 | into string
let context = { environment: "production", version: "3.2.0" }
let generated_config = $template | tera render $context

# 3. Validate Nickel config
let validated = $generated_config | nickel validate --schema deployment-schema.ncl

# 4. Encrypt sensitive values
let db_password = secretumvault-plugin retrieve "database-password"
let encrypted_creds = { password: $db_password } | kms encrypt --algorithm aes-256-gcm

# 5. Create deployment artifact
{
  config: $validated,
  credentials: $encrypted_creds,
  hash: ($validated | hashes sha256),
  timestamp: (now)
} | to json | save deployment-artifact.json

# 6. Notify completion
notifications notify "Deployment artifact created" --type success

print "Deployment ready: deployment-artifact.json"
```

## Related Documentation

- [Nushell Plugins](../features/plugins.md)
- [SecretumVault Guide](../security/secretumvault-guide.md)
- [KMS Guide](../security/kms-guide.md)
- [Nushell Guidelines](.../guidelines/nushell.md)
