GitLab CI/CD 
============

This guide explains how to integrate Fujin with GitLab CI/CD for automated deployments.

Prerequisites
------------

Before setting up GitLab CI/CD integration, ensure you have:

1. A working Fujin project with a valid ``fujin.toml`` configuration
2. Access to your target deployment server
3. Admin access to your GitLab project

SSH Key Setup
-------------

For secure authentication between GitLab CI/CD and your deployment server, you need to set up SSH keys:

**Option 1: Reuse Existing SSH Key (Recommended)**

If you're already using Fujin with your deployment host:

* Locate your existing private key (typically ``~/.ssh/id_rsa`` or ``~/.ssh/id_ed25519``)
* Copy this key for use in your GitLab CI/CD environment

**Option 2: Generate a Dedicated Deployment Key**

For improved security isolation:

.. code-block:: bash
    
    ssh-keygen -t ed25519 -C "deployment@example.com" -f deployment_key
    ssh-copy-id -i deployment_key.pub user@your-server.com

Configure GitLab CI/CD
---------------------

1. **Configure Environment Variables**

   Go to **Settings → CI/CD → Variables** and add:
   
   * ``SSH_PRIVATE_KEY``: Your SSH private key content
   * Any application secrets referenced in your configuration

2. **Create Pipeline Configuration**

   .. code-block:: yaml
       :caption: .gitlab-ci.yml

       stages:
         - deploy

       deploy:
         stage: deploy
         image: alpine:latest
         before_script:
           - mkdir -p ~/.ssh
           - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
           - chmod 600 ~/.ssh/id_rsa
           - ssh-keyscan -H example.com >> ~/.ssh/known_hosts
         script:
           - curl -LsSf https://astral.sh/uv/install.sh | sh
           - $HOME/.local/bin/uv tool install --upgrade fujin-cli
           - $HOME/.local/bin/fujin deploy
         only:
           - main

Environment Configuration
------------------------

For CI/CD environments, configure your application environment variables directly in the ``fujin.toml`` file:

.. code-block:: toml
    :caption: fujin.toml

    [host]
    domain_name = "example.com"
    user = "deploy"
    # Use env property instead of envfile for CI/CD environments
    env = """
    DEBUG=False
    DATABASE_URL=$DATABASE_URL
    """

Handling Secrets
---------------

Sensitive information should be managed securely using Fujin's secrets feature:

.. code-block:: toml
    :caption: fujin.toml

    [secrets]
    adapter = "system"  # Use system environment variables

Secret values will be substituted from your GitLab CI/CD environment variables at deployment time. For additional secret manager options (Bitwarden, 1Password, Doppler), see the :doc:`../secrets` documentation.