### Development Environment Setup Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/02-deployment-configuration.md Sets up a development environment by configuring specific environment variables, generating configuration, and starting services. ```bash export DNS_TLD=openbalena.local export PRODUCTION_MODE=false export LOG_LEVEL=DEBUG make config make up make self-signed ``` -------------------------------- ### Install OpenBalena Prerequisites and Docker Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Update system packages, install essential tools like make, openssl, git, jq, and curl, then install Docker Engine. Add the current user to the docker group for non-root access. ```bash # Update system sudo apt-get update && sudo apt-get upgrade -y # Install prerequisites sudo apt-get install -y \ make \ openssl \ git \ jq \ curl \ apt-transport-https \ ca-certificates # Install Docker Engine curl -fsSL https://get.docker.com | sudo sh - # Add current user to docker group (for non-root usage) sudo usermod -aG docker $USER newgrp docker # Install Docker Compose (if not included) sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose ``` -------------------------------- ### Python API Client Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt A Python script demonstrating how to interact with the Open Balena API. This example shows how to list devices. Ensure you have the 'balena-sdk' installed. ```python from balena import Balena # Initialize the Balena SDK api = Balena() # Authenticate (replace with your API key or credentials) # api.auth.login(email='your_email', password='your_password') # List all devices try: devices = api.devices.getAll() for device in devices: print(f"Device Name: {device['device_name']}, UUID: {device['uuid']}") except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### Install Essential Software Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Installs make, openssl, git, and jq on Ubuntu servers. Ensure you have root permissions. ```bash sudo apt-get update && sudo apt-get install -y make openssl git jq ``` -------------------------------- ### Install Balena CLI Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Install the balena CLI using npm, apt, or Homebrew. Ensure you have the minimum required version. ```bash # Using npm npm install -g balena-cli # Using apt (Linux) curl -sSL https://balena.io/download | bash # Using Homebrew (macOS) brew install balena-cli ``` -------------------------------- ### Start OpenBalena Services Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Commands to start OpenBalena services. Use 'make up' for all services, 'docker compose up -d ' for a specific service, or 'docker compose up -d' to start in the background without waiting for health checks. View logs with 'docker compose logs -f'. ```bash # Start all services make up # Start specific service docker compose up -d api # Start in background (no health check wait) docker compose up -d # Show startup logs docker compose logs -f ``` -------------------------------- ### Let's Encrypt with Gandi Setup Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Bash commands to set up automatic certificate provisioning using Let's Encrypt with Gandi for DNS-01 challenges. Similar to Cloudflare setup, but uses Gandi API token. ```bash export DNS_TLD=example.com export ACME_EMAIL=admin@example.com export GANDI_API_TOKEN=your-token-here make config make auto-pki ``` -------------------------------- ### Start openBalena Server Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Starts the openBalena server using Docker Compose. Set the DNS_TLD environment variable to your domain name before running. Note the SUPERUSER_EMAIL and SUPERUSER_PASSWORD outputted. ```bash export DNS_TLD=mydomain.com make up ``` -------------------------------- ### Create Application Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Illustrates the process of creating a new application (or fleet) within the open-balena system using the API. ```Bash curl -X POST \ 'https://api.example.com/v1/application' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer YOUR_JWT_TOKEN' \ -d '{ "name": "my-new-app", "description": "My new application" }' ``` -------------------------------- ### Docker Compose Example for Custom Application Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt An example docker-compose.yml file for defining multi-container applications within Open Balena. This is useful for local development and testing. ```yaml version: '2.1' services: app: build: . ports: - "80:80" volumes: - ./app:/usr/src/app environment: - MY_VARIABLE=my_value ``` -------------------------------- ### Python API Client Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Provides a basic example of how to interact with the open-balena API using a Python client. This snippet shows authentication and fetching data. ```Python import os import balena # Initialize the SDK with your API endpoint and API key balena.set_environment_variables(dict(BALENA_API_URL='https://api.balena-cloud.com')) api_key = os.environ.get('BALENA_API_KEY') # Authenticate balena.auth.login(apiKey=api_key) # Fetch a list of applications applications = balena.models.application.get_all() for app in applications: print(f"Application Name: {app['name']}, Slug: {app['slug']}") ``` -------------------------------- ### JavaScript API Client Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Illustrates how to use the open-balena API with a JavaScript client. This example covers authentication and retrieving application data. ```JavaScript const balenaSDK = require('balena-sdk'); const balena = balenaSDK.fromEnvironment(); // Authenticate using API Key balena.auth.login(process.env.BALENA_API_KEY, (err) => { if (err) { console.error('Authentication failed:', err); process.exit(1); } // Fetch applications balena.models.application.getAll((err, apps) => { if (err) { console.error('Error fetching applications:', err); process.exit(1); } console.log('Applications:'); apps.forEach(app => { console.log(`- ${app.name} (${app.slug})`); }); }); }); ``` -------------------------------- ### Install Balena Etcher Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Install Balena Etcher, a GUI tool for flashing OS images, on Linux or macOS. ```bash # Install Etcher sudo apt-get install balena-etcher-electron # Linux brew install balena-etcher # macOS # Launch and flash interactively balena-etcher-electron ``` -------------------------------- ### Create Fleet and Add Device Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md This example shows how to create a new fleet (application) and then add a specific device to that newly created fleet. ```APIDOC ## Create Fleet and Add Device ### Description Creates a new fleet (application) and then adds a device to that fleet. ### Method POST ### Endpoint POST /v6/application POST /v6/device ### Request Example (Create Fleet) ```json { "app_name": "my-fleet", "device_type": "raspberry-pi" } ``` ### Request Example (Add Device to Fleet) ```json { "device_name": "device-1", "application": } ``` ### Request Example (Full Workflow) ```bash TOKEN="your-token" API="https://api.example.com" # Create fleet FLEET=$(curl -s -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"app_name":"my-fleet","device_type":"raspberry-pi"}' \ "$API/v6/application") FLEET_ID=$(echo $FLEET | jq -r '.d.id') # Add device to fleet curl -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{"device_name":"device-1","application":$FLEET_ID}" \ "$API/v6/device" ``` ``` -------------------------------- ### JavaScript API Client Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt A JavaScript example for interacting with the Open Balena API using the official SDK. This snippet demonstrates fetching application details. ```javascript const balena = require('balena-sdk'); // Initialize the SDK const myBalena = balena.usingλικά('https://api.balena-cloud.com'); // Authenticate (replace with your API key or credentials) // myBalena.auth.loginWithCredentials({ email: 'your_email', password: 'your_password' }) // .then(user => console.log('Logged in:', user)) // .catch(err => console.error('Login failed:', err)); // Get application details myBalena.applications.getAll() .then(apps => { apps.forEach(app => { console.log(`App Name: ${app.name}, ID: ${app.id}`); }); }) .catch(err => { console.error('Failed to get applications:', err); }); ``` -------------------------------- ### Get Repository Information Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Example using curl to fetch repository catalog information from the registry API, requiring authentication. ```bash # Get repository information curl -u admin@example.com: \ https://registry2.example.com/_catalog ``` -------------------------------- ### Bash API Client Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt A Bash script using `curl` to interact with the Open Balena API. This example fetches a list of applications. Replace placeholders with your actual API endpoint and key. ```bash #!/bin/bash # Replace with your API endpoint and API key API_ENDPOINT="https://api.balena-cloud.com/v6" API_KEY="YOUR_API_KEY" # Fetch a list of applications curl -X GET \ -H "Authorization: Bearer $API_KEY" \ "$API_ENDPOINT/applications" \ -o applications.json echo "Applications list saved to applications.json" ``` -------------------------------- ### Dockerfile Example for Custom Application Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt A basic Dockerfile demonstrating how to build a custom application image for Open Balena. Ensure all necessary dependencies and application code are included. ```dockerfile FROM balenalib/%%BALENA_ARCH%%-alpine # Set working directory WORKDIR /usr/src/app # Copy application code COPY . . # Install dependencies (example for a Python app) RUN pip install -r requirements.txt # Expose application port (if applicable) EXPOSE 80 # Define the command to run your app CMD ["python", "app.py"] ``` -------------------------------- ### Re-configure and Test with Custom SSL Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Run these commands to configure the server with your custom SSL certificate and verify the setup. ```bash make pki-custom make verify ``` -------------------------------- ### Install Docker Engine Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Installs Docker Engine if not already present. This script is designed for Linux systems. ```bash which docker || curl -fsSL https://get.docker.com | sh - ``` -------------------------------- ### OData Pagination Syntax Examples Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Illustrates the use of $skip and $top query parameters for implementing pagination to control the number of results returned. ```odata $skip=50 # Skip first 50 results $top=10 # Return max 10 results ``` -------------------------------- ### Authenticate and List Devices Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md This example demonstrates how to authenticate with the API using email and password to obtain a JWT token, and then use that token to list all devices associated with the account. ```APIDOC ## Authenticate and List Devices ### Description Authenticates with the API to obtain a JWT token and then uses the token to list devices. ### Method POST, GET ### Endpoint POST /auth/login GET /v6/device ### Request Example (Login) ```json { "email": "admin@example.com", "password": "your-password" } ``` ### Response Example (Login Token) ```json { "token": "your-jwt-token" } ``` ### Request Example (List Devices) ```bash curl -H "Authorization: Bearer your-jwt-token" \ "https://api.example.com/v6/device" ``` ``` -------------------------------- ### Custom Certificates Setup with Files Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Bash commands to set up OpenBalena with custom certificates provided as files. Requires exporting the certificate and private key content into environment variables. ```bash # Option 1: From files export DNS_TLD=example.com export HAPROXY_CRT="$(cat /path/to/cert.pem)" export HAPROXY_KEY="$(cat /path/to/key.pem)" make config make up ``` -------------------------------- ### Let's Encrypt with Cloudflare Setup Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Bash commands to set up automatic certificate provisioning using Let's Encrypt with Cloudflare for DNS-01 challenges. Requires setting environment variables for domain, email, and Cloudflare API token. ```bash export DNS_TLD=example.com export ACME_EMAIL=admin@example.com export CLOUDFLARE_API_TOKEN=your-token-here make config make auto-pki ``` -------------------------------- ### Self-Signed Certificates Setup Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Bash commands to set up self-signed certificates for development or local deployment. Includes setting the DNS_TLD, configuring, and bringing up the services. ```bash export DNS_TLD=example.local make config make up make self-signed ``` -------------------------------- ### Deploy OpenBalena Services Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Start all OpenBalena services using 'make up'. The command includes a wait for the API health check. Display superuser credentials with 'make showpass'. ```bash # Start all services make up # Wait for services to be ready (~2-3 minutes) # The 'make up' command automatically waits for API health check # Display superuser credentials make showpass ``` -------------------------------- ### JWT Authentication Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Demonstrates how to authenticate using JWT tokens with the API. This is a common method for securing API requests. ```Bash curl -X POST \ 'https://api.example.com/v1/auth/login' \ -H 'Content-Type: application/json' \ -d '{ "username": "user@example.com", "password": "your_password" }' ``` -------------------------------- ### Dockerfile for OpenBalena Application Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/10-service-integration-and-examples.md A sample Dockerfile for building a custom application image for OpenBalena. It includes installing system and Python dependencies and copying application code. ```dockerfile FROM balena/generic-amd64-debian-python:3.9-latest # Install application dependencies RUN apt-get update && apt-get install -y \ python3-requests \ curl # Copy application COPY . /app WORKDIR /app # Install Python dependencies RUN pip install -r requirements.txt # Run application CMD ["python", "app.py"] ``` -------------------------------- ### Install Self-Signed Certificate for CLI Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Download the self-signed certificate from your OpenBalena server and configure the CLI to trust it. ```bash # From OpenBalena server scp user@server:.balena/ca-mydomain.pem ~/.balena/ # Configure CLI to trust certificate balena settings set caPath ~/.balena/ca-mydomain.pem ``` -------------------------------- ### Install CA Certificate on Windows Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Installs the self-signed CA certificate on a Windows system and restarts the Docker service. This uses certutil to add the certificate to the root store and then restarts the Docker service. ```powershell certutil -addstore -f "ROOT" ca.pem Stop-Service -Name Docker Start-Service -Name Docker ``` -------------------------------- ### Create Application using curl Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Example using curl to create a new application. Ensure to replace $TOKEN with your actual JWT token. ```bash curl -X POST -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"app_name":"my-app","device_type":"raspberry-pi"}' \ https://api.example.com/v6/application ``` -------------------------------- ### Monitor Device Status Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md This example demonstrates how to retrieve information about device status, including counting online devices and fetching specific status details. ```APIDOC ## Monitor Device Status ### Description Retrieves information about device status, including counting online devices and fetching specific status details. ### Method GET ### Endpoint GET /v6/device ### Parameters #### Query Parameters - **$filter** (string) - Optional - OData filter expression (e.g., `is_online eq true`). - **$select** (string) - Optional - Comma-separated list of fields to retrieve (e.g., `device_name,status,last_seen_time`). ### Request Example (Online Device Count) ```bash curl -s -H "Authorization: Bearer your-token" \ "https://api.example.com/v6/device?\ $filter=is_online%20eq%20true" | \ jq '.d | length' ``` ### Request Example (Device Status Details) ```bash curl -s -H "Authorization: Bearer your-token" \ "https://api.example.com/v6/device?\ $select=device_name,status,last_seen_time" | \ jq '.d[] | {name: .device_name, status: .status, seen: .last_seen_time}' ``` ``` -------------------------------- ### Development OpenBalena Setup Script Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md A bash script to set up a development environment with self-signed certificates. It configures DNS, sets production mode to false, and enables debug logging. ```bash #!/bin/bash # Development setup with self-signed certificates export DNS_TLD=openbalena.local export PRODUCTION_MODE=false export LOG_LEVEL=DEBUG export VERBOSE=true cd ~/open-balena make config make up make self-signed # Show credentials make showpass echo "Development OpenBalena ready at https://api.openbalena.local" ``` -------------------------------- ### Start Updated Services Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Bring up the OpenBalena services with the newly pulled code using `make up`. This command will typically recreate containers based on the updated configuration and images. ```bash make up ``` -------------------------------- ### OData Ordering Syntax Examples Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Shows how to use the $orderby query parameter for sorting results in ascending or descending order, including multiple fields. ```odata $orderby=field # Ascending $orderby=field desc # Descending $orderby=field1,field2 # Multiple fields ``` -------------------------------- ### Backup Database Volume Before Update Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Create a backup of the database volume (`db-data`) before starting the updated services. This provides a safety net in case of upgrade issues. ```bash docker volume create db-data-backup docker run --rm -v db-data:/source -v db-data-backup:/dest \ busybox cp -r /source /dest/ ``` -------------------------------- ### Configure API Resource Limits Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Example of how to define CPU and memory limits and reservations for the API service within the `docker-compose.yml` file. These settings help manage resource allocation. ```yaml services: api: # Add resource limits mem_limit: 1g cpus: 1 # Add reservations mem_reservation: 512m cpu_shares: 1024 ``` -------------------------------- ### Deploy Application using balena CLI Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Demonstrates how the balena CLI automatically handles building, tagging, authenticating, and pushing images for deployment. ```bash # Deploy application (automatic push) balena push admin/myapp # This automatically: # 1. Builds Dockerfile to OCI image # 2. Tags image for registry2.{DNS_TLD} # 3. Authenticates with API token # 4. Pushes to registry # 5. Notifies API of new release ``` -------------------------------- ### Prometheus Configuration for OpenBalena Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/10-service-integration-and-examples.md Example Prometheus configuration to scrape metrics from the OpenBalena API. Ensure the API is configured to export Prometheus metrics. ```yaml # prometheus.yml global: scrape_interval: 15s scrape_configs: - job_name: 'open-balena' static_configs: - targets: ['api.mydomain.com:9090'] # Requires API to export Prometheus metrics ``` -------------------------------- ### Install Self-Signed CA Certificate Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Command to install a self-signed CA certificate, typically used in development or testing environments. ```bash make self-signed ``` -------------------------------- ### Verify openBalena Server Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Performs a verification check on the openBalena server after initial setup and certificate generation. Ensure 'make up' has been run if the server was previously stopped. ```bash make verify ``` -------------------------------- ### Install CA Certificate on macOS Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Command to install a self-signed CA certificate on macOS. Adds the certificate to the system's keychain with trusted root status. ```bash sudo security add-trusted-cert -d -r trustRoot \ -k /Library/Keychains/System.keychain ca-example.local.pem ``` -------------------------------- ### Configure WiFi Post-Provisioning Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Set up WiFi connectivity on a device after initial provisioning by editing network interfaces or setting environment variables for SSID and password. ```bash # SSH to device balena ssh # Edit network configuration sudo nano /etc/network/interfaces.d/balena # Or set environment variable for next boot balena env add RESIN_WIFI_SSID "MyNetwork" --device balena env add RESIN_WIFI_PASSWORD "password" --device # Reboot to apply balena device reboot ``` -------------------------------- ### Generate Configuration and Deploy with Self-Signed Certificates Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/02-deployment-configuration.md Configures OpenBalena with self-signed certificates for development and testing. This involves generating the configuration, bringing up services, and installing the CA certificate locally. ```bash make config DNS_TLD=mydomain.com make up make self-signed # Install CA certificate locally ``` -------------------------------- ### Production Deployment with Custom Certificates Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/02-deployment-configuration.md Sets up a production environment using custom SSL certificates. Requires base64 encoded certificate and key. ```bash export DNS_TLD=balena.company.com export HAPROXY_CRT=$(cat cert.pem | base64 -w0) export HAPROXY_KEY=$(cat key.pem | base64 -w0) export PRODUCTION_MODE=true make config make pki-custom ``` -------------------------------- ### Install CA Certificate on Windows Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md PowerShell command to install a self-signed CA certificate on Windows systems. Imports the certificate into the local machine's root certificate store. ```powershell Import-Certificate -FilePath ca-example.local.pem \ -CertStoreLocation Cert:\LocalMachine\Root ``` -------------------------------- ### Generate OpenBalena Configuration Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/02-deployment-configuration.md Generates the OpenBalena configuration using the 'make config' target. Specify the DNS_TLD for basic setup or include additional variables for a comprehensive configuration. ```bash make config DNS_TLD=mydomain.com ``` ```bash make config \ DNS_TLD=mydomain.com \ SUPERUSER_EMAIL=admin@mydomain.com \ PRODUCTION_MODE=true \ ORG_UNIT=MyOrganization \ ACME_EMAIL=admin@email.com \ CLOUDFLARE_API_TOKEN=your-token ``` -------------------------------- ### Build Application with balena-cli for Emulation Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Build your application locally using the balena-cli, with the `--emulated` flag for local testing environments. ```bash # Or with balena-cli balena build ./ --emulated ``` -------------------------------- ### Production OpenBalena on AWS Setup Script Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md A bash script for production deployment on AWS EC2. It sets a custom domain, email for ACME, Cloudflare API token, production mode, and warning log level. ```bash #!/bin/bash # Production setup on AWS EC2 export DNS_TLD=balena.mycompany.com export ACME_EMAIL=admin@mycompany.com export CLOUDFLARE_API_TOKEN=${CF_API_TOKEN} export PRODUCTION_MODE=true export LOG_LEVEL=WARN export BALENARC_NO_ANALYTICS=1 cd ~/open-balena make config make auto-pki # Backup configuration cp .env .env.$(date +%s).backup echo "Production OpenBalena deployed" ``` -------------------------------- ### Private CA Configuration Example Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Example JSON configuration for the private CA (cfssl) to generate and sign X.509 certificates. Specifies certificate subject and key generation parameters. ```json { "CN": "example.com", "key": { "algo": "rsa", "size": 2048 }, "names": [ { "C": "US", "ST": "State", "L": "City", "O": "Organization", "OU": "Organization Unit" } ] } ``` -------------------------------- ### Install CA Certificate on Linux Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Installs the self-signed CA certificate on a Linux system. This involves copying the certificate, updating the system's CA store, and restarting the Docker service. ```bash sudo cp ca.pem /usr/local/share/ca-certificates/ sudo update-ca-certificates sudo systemctl restart docker ``` -------------------------------- ### List Devices Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md View a list of all registered devices, their status, and versions. This helps confirm successful provisioning. ```bash balena devices ID UUID DEVICE NAME DEVICE TYPE FLEET STATUS IS ONLINE SUPERVISOR VERSION OS VERSION 1 560dcc2 quiet-rock raspberrypi3 admin/myapp Idle true 16.1.10 balenaOS 5.2.8 ``` -------------------------------- ### Install CA Certificate on Linux Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Commands to install a self-signed CA certificate on Linux systems. Copies the certificate to the system's trusted certificate store and updates the CA certificate list. ```bash sudo cp ca-example.local.pem /usr/local/share/ca-certificates/ sudo update-ca-certificates ``` -------------------------------- ### Monitor Device Status Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Bash script examples for monitoring device status, including counting online devices and retrieving specific device details like name, status, and last seen time. ```bash TOKEN="your-token" API="https://api.example.com" # Get online device count curl -s -H "Authorization: Bearer $TOKEN" \ "$API/v6/device?\ $filter=is_online%20eq%20true" | \ jq '.d | length' # Get device status details curl -s -H "Authorization: Bearer $TOKEN" \ "$API/v6/device?\ $select=device_name,status,last_seen_time" | \ jq '.d[] | {name: .device_name, status: .status, seen: .last_seen_time}' ``` -------------------------------- ### Deploy an Application with Balena CLI Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/README.md Steps to deploy an application using the balena CLI, including creating a fleet, pushing code, and monitoring logs. ```bash # 1. Create fleet balena app create my-app --type generic-amd64 # 2. Deploy code balena push admin/my-app # 3. Monitor balena logs -f ``` -------------------------------- ### Install CA Certificate on macOS Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Installs the self-signed CA certificate on macOS and restarts the Docker engine. This command adds the certificate to the system keychain and then triggers a Docker engine restart via a local API call. ```bash sudo security add-trusted-cert -d \ -r trustRoot \ -k /Library/Keychains/System.keychain \ ca.pem curl http://localhost/engine/restart \ -H 'Content-Type: application/json' \ -d '{"openContainerView": true}' \ --unix-socket ~/Library/Containers/com.docker.docker/Data/backend.sock ``` -------------------------------- ### Deploying Application to OpenBalena Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/10-service-integration-and-examples.md Commands to create a new OpenBalena application (fleet), push a Docker image for deployment, and monitor the deployment logs on a specific device. ```bash # Create fleet balena app create my-app --type generic-amd64 # Deploy balena push admin/my-app # Monitor deployment balena logs -f ``` -------------------------------- ### Inspect Docker Volume Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/06-storage-and-database.md Get detailed information about a specific Docker volume. ```bash docker volume inspect db-data ``` -------------------------------- ### List all applications Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Query the openBalena server for all known applications using the 'balena fleets' command. This displays details like application ID, name, slug, device type, and counts. ```bash balena fleets ``` -------------------------------- ### Get Device Details Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Retrieves detailed information for a specific device using its ID or UUID. ```APIDOC ## GET /v6/device(id) ### Description Retrieves detailed information for a specific device. ### Method GET ### Endpoint /v6/device(id) ### Authentication Required (JWT token) ### Parameters #### Path Parameters - **id** (integer) - Required - Device ID or UUID. ### Response #### Success Response (200 OK) ```json { "d": { "id": 123456, "uuid": "abc123def456", "device_name": "my-device", "device_type": "raspberry-pi", "is_online": true, "status": "Idle", "latitude": "37.7749", "longitude": "-122.4194", "memory": 1024, "storage": 32000, "os_version": "balenaOS 5.2.8", "supervisor_version": "14.0.0", "created_at": "2024-01-15T10:30:00.000Z", "last_seen_time": "2024-06-10T15:45:30.000Z", "vpn_address": "10.0.0.5" } } ``` ### Example ```bash curl -H "Authorization: Bearer $TOKEN" \ https://api.example.com/v6/device\(123456\) ``` ``` -------------------------------- ### Get Current Redis Eviction Policy Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/06-storage-and-database.md View the current memory eviction policy for Redis. ```bash docker compose exec redis redis-cli CONFIG GET maxmemory-policy ``` -------------------------------- ### Get Manifest Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Retrieves the manifest for a specific image version (tag or digest). Authentication is required. ```APIDOC ## GET /v2/{image}/manifests/{reference} ### Description Retrieves the manifest for a specific image version (tag or digest). Authentication is required. ### Method GET ### Endpoint /v2/{image}/manifests/{reference} ### Parameters #### Path Parameters - **image** (string) - Required - Image name - **reference** (string) - Required - Tag or digest (e.g., `latest` or `sha256:abc123...`) ### Response #### Success Response (200 OK) Returns the image manifest details, including configuration and layer information. ```json { "schemaVersion": 2, "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "config": { "mediaType": "application/vnd.docker.container.image.v1+json", "size": 7023, "digest": "sha256:b5b2b2c507a1..." }, "layers": [ { "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "size": 32654, "digest": "sha256:e692418e3..." } ] } ``` ``` -------------------------------- ### Verify Deployment After Update Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Run a verification check to ensure the OpenBalena deployment is functioning correctly after an update. Replace `mydomain.com` with your actual domain. ```bash make verify DNS_TLD=mydomain.com ``` -------------------------------- ### Automate Application Deployments via CLI Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md A bash script demonstrating automated application creation, deployment, and verification on devices within a fleet. ```bash #!/bin/bash # automated-deploy.sh APP="admin/my-app" DEVICE_TYPE="generic-amd64" # Create fleet if not exists balena apps | grep -q "$APP" || balena app create "$APP" --type "$DEVICE_TYPE" # Deploy application echo "Deploying application..." balena push "$APP" # Get device UUIDs DEVICES=$(balena devices -a "$APP" --json | jq -r '.[].uuid') # Verify deployment on each device for device in $DEVICES; do echo "Checking device $device..." balena logs "$device" --tail 5 done ``` -------------------------------- ### Get Current Redis Maxmemory Setting Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/06-storage-and-database.md Check the current configured maximum memory limit for Redis. ```bash docker compose exec redis redis-cli CONFIG GET maxmemory ``` -------------------------------- ### Show Specific Service Details Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Get detailed status information for a particular service, such as the 'api' service. ```bash docker compose ps api ``` -------------------------------- ### Create Fleet and Add Device Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md A bash script demonstrating how to create a new fleet (application) and then add a device to that fleet using the API. ```bash TOKEN="your-token" API="https://api.example.com" # Create fleet FLEET=$(curl -s -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"app_name":"my-fleet","device_type":"raspberry-pi"}' \ "$API/v6/application") FLEET_ID=$(echo $FLEET | jq -r '.d.id') # Add device to fleet curl -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{"device_name":"device-1","application":$FLEET_ID}" \ "$API/v6/device" ``` -------------------------------- ### Redis Cache Operations Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/06-storage-and-database.md Commands for managing cache keys, including listing, getting, deleting, and flushing databases. ```bash # List all keys (CAUTION: slow on large databases) redis-cli KEYS "*" # List keys matching pattern redis-cli KEYS "registry:*" # Get key value redis-cli GET key-name # Delete key redis-cli DEL key-name # Delete all keys in database redis-cli FLUSHDB # Delete all keys in all databases redis-cli FLUSHALL ``` -------------------------------- ### Certbot List Installed Certificates Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/07-certificate-management.md Command to display a list of all certificates currently managed by Certbot, including their expiration dates. ```bash certbot certificates ``` -------------------------------- ### Build and Deploy Project Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Build and deploy your project to the specified fleet using the balena CLI. The `--noparent-check` flag can be used to bypass parent image checks. ```bash balena deploy --noparent-check myApp ``` -------------------------------- ### Create a New Fleet Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Create a new application fleet in OpenBalena for managing a group of devices. Verify its creation by listing all fleets. ```bash # Create new fleet balena app create my-app --type generic-amd64 # Verify fleet created balena apps ``` -------------------------------- ### Authentication Error: Token Expired Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Example JSON response for a 401 Unauthorized error indicating that the authentication token has expired. ```json { "error": { "message": "Token expired", "code": "TOKEN_EXPIRED" } } ``` -------------------------------- ### Authentication Error: Invalid Token Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Example JSON response for a 401 Unauthorized error due to an invalid authentication token. ```json { "error": { "message": "Invalid token", "code": "INVALID_TOKEN" } } ``` -------------------------------- ### Authentication Error: Missing Token Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Example JSON response for a 401 Unauthorized error due to a missing authentication token. ```json { "error": { "message": "Unauthorized", "code": "UNAUTHORIZED" } } ``` -------------------------------- ### Image Naming Convention Examples Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Illustrates the format for naming images within the registry, including namespace and tag variations. ```plaintext registry2.example.com/myapp:latest registry2.example.com/admin/myapp:v1.0.0 registry2.example.com/myapp:sha256-abc123def456 ``` -------------------------------- ### Join Open Balena from balenaCloud Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Connect a device currently managed by balenaCloud to your Open Balena instance by specifying the API URL. ```bash # From balenaCloud device balena join --url https://api.mydomain.com ``` -------------------------------- ### Create a new application (fleet) Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Use the 'balena fleet create' command to create a new application on your openBalena server. You will be prompted to select a device type. ```bash balena fleet create myApp ``` -------------------------------- ### Deploy Application to Physical Device Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Deploy your application to a physical device using the balena-cli. Ensure the correct device type is specified. ```bash # Deploy to physical device balena push admin/my-app --deviceType generic-amd64 ``` -------------------------------- ### Monitor Specific Service Stats Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Get CPU and memory usage statistics for a single service, like the 'api' service. ```bash docker compose stats api ``` -------------------------------- ### Configure OpenBalena Environment Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Set environment variables for DNS domain and optional configurations like production mode and log level. Generate the .env file using 'make config' and review it with 'make showenv'. ```bash # Set DNS domain export DNS_TLD=mydomain.com # Optional: Set additional configuration export PRODUCTION_MODE=true export LOG_LEVEL=INFO # Generate .env file make config # Review configuration make showenv ``` -------------------------------- ### Check Registry Health Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Verify if the registry is operational by sending a GET request to the /v2/ endpoint. This check does not require authentication. ```bash curl https://registry2.example.com/v2/ ``` -------------------------------- ### Add Device to Application Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Demonstrates how to associate a specific device with an application using the API. This is crucial for managing device deployments. ```Bash curl -X POST \ 'https://api.example.com/v1/application/my-new-app/device' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer YOUR_JWT_TOKEN' \ -d '{ "uuid": "YOUR_DEVICE_UUID" }' ``` -------------------------------- ### OData Query Example: Filter Devices Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Uses curl to query devices that are online and of type 'raspberry-pi' using OData filtering. ```bash # Devices online AND of type raspberry-pi curl -H "Authorization: Bearer $TOKEN" \ 'https://api.example.com/v6/device?$filter=is_online%20eq%20true%20and%20device_type%20eq%20%27raspberry-pi%27' ``` -------------------------------- ### Get Latest Release Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Retrieves the latest release(s) for a given application. Supports filtering by application, ordering, and limiting the number of results. ```APIDOC ## GET /v6/release ### Description Retrieves the latest release(s). ### Method GET ### Endpoint /v6/release ### Parameters #### Query Parameters - **$filter** (string) - Filter by application (e.g., `application eq 12345`). - **$orderby** (string) - Order by field (e.g., `-created_at`). - **$top** (integer) - Maximum results. ### Response #### Success Response (200 OK) - **d** (array) - An array of release objects. - **id** (integer) - The unique identifier for the release. - **application** (integer) - The ID of the application this release belongs to. - **commit** (string) - The commit hash associated with the release. - **description** (string) - A description of the release. - **status** (string) - The status of the release (e.g., `success`). - **created_at** (string) - The timestamp when the release was created. #### Response Example ```json { "d": [ { "id": 54321, "application": 12345, "commit": "abc1234def5678", "description": "Initial release", "status": "success", "created_at": "2024-01-15T10:30:00.000Z" } ] } ``` ``` -------------------------------- ### Create a Trivial Dockerfile Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Define a simple Dockerfile for a project that will run a 'balena-idle' command. This uses a balenalib base image. ```dockerfile FROM balenalib/%%BALENA_MACHINE_NAME%%-alpine CMD [ "balena-idle" ] ``` -------------------------------- ### Get Device Environment Variables Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Retrieves all environment variables for a given device using an OData filter. Requires JWT authentication. ```json { "d": [ { "id": 654321, "device": 123456, "env_var_name": "MY_VAR", "value": "my-value" } ] } ``` -------------------------------- ### Python API Client: List Devices Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/10-service-integration-and-examples.md A Python script demonstrating how to authenticate with the OpenBalena API and list all devices in a fleet, including their names and online status. Requires the `requests` library. ```python #!/usr/bin/env python3 import requests import json API_URL = "https://api.mydomain.com" EMAIL = "admin@mydomain.com" PASSWORD = "password" # Authenticate response = requests.post(f"{API_URL}/auth/login", json={ "email": EMAIL, "password": PASSWORD }) response.raise_for_status() token = response.json()["token"] # List devices headers = {"Authorization": f"Bearer {token}"} response = requests.get(f"{API_URL}/v6/device", headers=headers) response.raise_for_status() devices = response.json()["d"] for device in devices: print(f"{device['device_name']}: {device['is_online']}") ``` -------------------------------- ### Get Device Details by ID Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Retrieves detailed information for a specific device using its ID or UUID. Requires JWT authentication. ```bash curl -H "Authorization: Bearer $TOKEN" \ https://api.example.com/v6/device\(123456\) ``` -------------------------------- ### Show Detailed Device Information Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/09-cli-integration-and-devices.md Use the '-v' flag for verbose output when listing devices. ```bash balena devices -v ``` -------------------------------- ### Check Current Git Version Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Display the current Git tag or commit hash for the OpenBalena repository. Useful for identifying the installed version. ```bash git describe --tags ``` -------------------------------- ### Check Docker Daemon Status Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md Verify that the Docker daemon is running and healthy. This is a fundamental step in troubleshooting services that won't start. ```bash sudo systemctl status docker ``` -------------------------------- ### Configure VPN Credentials in Device Image Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/05-vpn-and-networking.md Review the balena CLI logs during device image configuration to ensure VPN credentials are correctly set. This is crucial for device authentication. ```bash # The balena CLI logs show credentials during configuration balena os configure image.img -v ``` -------------------------------- ### Full System Backup Script Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/08-deployment-and-operations.md A bash script to create a comprehensive backup of the OpenBalena instance. It backs up the `.env` file, all defined volumes, and configuration files like `docker-compose.yml` and `Makefile`. ```bash #!/bin/bash BACKUP_DIR="$HOME/openbalena-backup-$(date +%Y%m%d-%H%M%S)" mkdir -p "$BACKUP_DIR" # Backup .env configuration cp .env "$BACKUP_DIR/" # Backup all volumes for volume in db-data redis-data s3-data certs-data pki-data resin-data; do docker run --rm \ -v "$volume:/source" \ -v "$BACKUP_DIR:/backup" \ busybox tar czf "/backup/$volume.tar.gz" -C /source . done # Backup docker-compose.yml and related files cp docker-compose.yml "$BACKUP_DIR/" cp Makefile "$BACKUP_DIR/" echo "Backup complete: $BACKUP_DIR" ``` -------------------------------- ### List Repositories with Pagination Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Retrieve a list of all repositories in the registry. This endpoint is admin-only and supports pagination using 'n' for count and 'last' for the marker of the next page. ```bash # Get next page (if available) curl -u admin@example.com: \ 'https://registry2.example.com/_catalog?n=10&last=app1' ``` -------------------------------- ### Health Check Endpoint Usage Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md This command-line example shows how to check the API's availability using the /ping endpoint, which does not require authentication. ```bash curl https://api.example.com/ping ``` -------------------------------- ### Re-configure and Test openBalena PKI Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Run these commands to automatically generate a public key infrastructure (PKI) and verify the server configuration. ```bash make auto-pki make verify ``` -------------------------------- ### Get Latest Release Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/03-api-reference.md Retrieves the latest release information, optionally filtered by application and ordered by creation date. Requires JWT authentication. ```json { "d": [ { "id": 54321, "application": 12345, "commit": "abc1234def5678", "description": "Initial release", "status": "success", "created_at": "2024-01-15T10:30:00.000Z" } ] } ``` -------------------------------- ### Inspect a Specific Device Source: https://github.com/balena-io/open-balena/blob/master/docs/getting-started.md Get detailed information about a specific device, including its IP address, MAC address, fleet, and OS version. ```bash balena device 560dcc2 == WANDERING RAIN ID: 1 DEVICE TYPE: raspberrypi3 STATUS: idle IS ONLINE: true IP ADDRESS: 192.168.1.42 MAC ADDRESS: B8:27:DE:AD:BE:EF FLEET: admin/myapp LAST SEEN: 1977-08-20T14:29:00.042Z UUID: 560dcc24b221c8a264d5bd981284801f COMMIT: N/a SUPERVISOR VERSION: 16.1.10 IS WEB ACCESSIBLE: false OS VERSION: balenaOS 5.2.8 DASHBOARD URL: https://dashboard.mydomain.com/devices/560dcc24b221c8a264d5bd981284801f/summary CPU USAGE PERCENT: 2 CPU TEMP C: 39 CPU ID: 00000000335956af MEMORY USAGE MB: 140 MEMORY TOTAL MB: 971 MEMORY USAGE PERCENT: 14 STORAGE BLOCK DEVICE: /dev/mmcblk0p6 STORAGE USAGE MB: 76 STORAGE TOTAL MB: 14121 STORAGE USAGE PERCENT: 1 ``` -------------------------------- ### Initiate Blob Upload Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/04-registry-reference.md Starts a new blob upload session. Blobs are layer data or configuration data for container images. Authentication is required. ```APIDOC ## POST /v2/{image}/blobs/uploads/ ### Description Starts a new blob upload session. Blobs are layer data or configuration data for container images. Authentication is required. ### Method POST ### Endpoint /v2/{image}/blobs/uploads/ ### Parameters #### Path Parameters - **image** (string) - Required - Image name ### Response #### Success Response (202 Accepted) Returns a redirect to the upload session URL, along with upload-related headers. ### Response Headers - **Location** (string) - Upload session URL - **Docker-Upload-UUID** (string) - Unique upload session ID - **Range** (string) - Upload progress (bytes) ``` -------------------------------- ### Backup OpenBalena Configuration Source: https://github.com/balena-io/open-balena/blob/master/_autodocs/02-deployment-configuration.md Commands to back up the OpenBalena environment, including the .env file, database, and all volumes. ```bash # Backup .env file cp .env .env.backup.$(date +%s) # Backup database docker compose exec db pg_dump -U docker resin > resin_backup.sql # Backup all volumes docker run --rm -v db-data:/source -v backup:/dest \ busybox tar czf /dest/db-data.tar.gz -C /source . ```