Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat: per-service targeting for the compose env overlay

Juan Denis807ca7b05e06
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 7d17b73a..09e82a36 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -585,6 +585,25 @@ def get_app(app_id):
return jsonify({'app': _attach_deploy_config(app.to_dict(include_linked=True))}), 200
+@apps_bp.route('/<int:app_id>/compose-services', methods=['GET'])
+@jwt_required()
+def get_compose_services(app_id):
+ """List the compose service names for an app.
+
+ Lets the env-var editor offer a per-service targeting choice. Empty for
+ non-compose apps or when the base compose can't be read.
+ """
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not _can_access_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+
+ from app.services.compose_env_service import ComposeEnvService
+ return jsonify({'services': ComposeEnvService.list_services(app)}), 200
+
+
# ---- Per-resource access grants (#33 per-site ACL): share an app with a user ----
@apps_bp.route('/<int:app_id>/grants', methods=['GET'])
diff --git a/backend/app/api/env_vars.py b/backend/app/api/env_vars.py
index fd5df4b1..eefff5d3 100644
--- a/backend/app/api/env_vars.py
+++ b/backend/app/api/env_vars.py
@@ -64,12 +64,14 @@ def create_env_var(app_id):
value = data.get('value', '')
is_secret = data.get('is_secret', False)
description = data.get('description')
+ target_service = data.get('target_service')
if not key:
return jsonify({'error': 'Key is required'}), 400
env_var, created, err = EnvService.set_env_var(
- app_id, key, value, is_secret, description, current_user_id
+ app_id, key, value, is_secret, description, current_user_id,
+ target_service=target_service
)
if err:
@@ -139,6 +141,9 @@ def update_env_var(app_id, key):
if description is not None:
existing.description = description
+ if 'target_service' in data:
+ existing.target_service = data.get('target_service') or None
+
from app import db
db.session.commit()
diff --git a/backend/app/api/shared_resources.py b/backend/app/api/shared_resources.py
index 7dcbf574..4f0c66c4 100644
--- a/backend/app/api/shared_resources.py
+++ b/backend/app/api/shared_resources.py
@@ -170,6 +170,7 @@ def add_variable(group_id):
var = SharedResourceService.set_variable(
group_id, data['key'], data.get('value', ''),
is_secret=bool(data.get('is_secret', False)),
+ target_service=data.get('target_service') if 'target_service' in data else None,
)
except ValueError as e:
return _bad(str(e))
@@ -183,11 +184,11 @@ def add_variable(group_id):
@jwt_required()
def update_variable(group_id, variable_id):
data = request.get_json() or {}
- var = SharedResourceService.update_variable(
- variable_id,
- value=data.get('value'),
- is_secret=data.get('is_secret'),
- )
+ _kwargs = {'value': data.get('value'), 'is_secret': data.get('is_secret')}
+ if 'target_service' in data:
+ # Only forward when the client sent it, so it's preserved otherwise.
+ _kwargs['target_service'] = data.get('target_service')
+ var = SharedResourceService.update_variable(variable_id, **_kwargs)
if not var or var.group_id != group_id:
return _bad('variable not found', 404)
return jsonify(var.to_dict(mask_secrets=True))
diff --git a/backend/app/models/env_variable.py b/backend/app/models/env_variable.py
index 1827c315..b472c617 100644
--- a/backend/app/models/env_variable.py
+++ b/backend/app/models/env_variable.py
@@ -19,6 +19,9 @@ class EnvironmentVariable(db.Model):
encrypted_value = db.Column(db.Text, nullable=False)
is_secret = db.Column(db.Boolean, default=False) # Mark sensitive values
description = db.Column(db.String(500), nullable=True) # Optional description
+ # Compose service this var targets (NULL = all services). Lets a compose app
+ # scope a variable to one service in the managed env overlay.
+ target_service = db.Column(db.String(120), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
@@ -80,6 +83,7 @@ class EnvironmentVariable(db.Model):
'key': self.key,
'is_secret': self.is_secret,
'description': self.description,
+ 'target_service': self.target_service,
'created_at': self.created_at.isoformat() if self.created_at else None,
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
}
diff --git a/backend/app/models/shared_resource.py b/backend/app/models/shared_resource.py
index 57e80052..00cef693 100644
--- a/backend/app/models/shared_resource.py
+++ b/backend/app/models/shared_resource.py
@@ -126,6 +126,9 @@ class SharedVariable(db.Model):
key = db.Column(db.String(255), nullable=False)
encrypted_value = db.Column(db.Text, nullable=False)
is_secret = db.Column(db.Boolean, default=False)
+ # Compose service this var targets (NULL = all services), mirroring
+ # EnvironmentVariable.target_service so shared vars can also be scoped.
+ target_service = db.Column(db.String(120), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
__table_args__ = (
@@ -150,6 +153,7 @@ class SharedVariable(db.Model):
'group_id': self.group_id,
'key': self.key,
'is_secret': self.is_secret,
+ 'target_service': self.target_service,
'created_at': self.created_at.isoformat() if self.created_at else None,
}
if include_value:
diff --git a/backend/app/services/compose_env_service.py b/backend/app/services/compose_env_service.py
index eda6d2f9..ac72b390 100644
--- a/backend/app/services/compose_env_service.py
+++ b/backend/app/services/compose_env_service.py
@@ -55,6 +55,25 @@ class ComposeEnvService:
def override_path(cls, project_path):
return os.path.join(project_path, cls.OVERRIDE_NAME)
+ @classmethod
+ def list_services(cls, app):
+ """Service names declared in a managed compose app's base compose.
+
+ Used by the UI to offer a per-service targeting choice. Returns [] for
+ non-compose apps or when the base compose can't be read.
+ """
+ try:
+ root = getattr(app, 'root_path', None)
+ if not root or not os.path.isdir(root):
+ return []
+ base = cls.find_base_compose(root, getattr(app, 'compose_file', None))
+ if not base:
+ return []
+ base_path = base if os.path.isabs(base) else os.path.join(root, base)
+ return cls._service_names(base_path)
+ except Exception: # pragma: no cover - defensive
+ return []
+
@staticmethod
def _app_for_project(project_path):
"""The managed Application whose root_path is this project dir, if any."""
@@ -113,18 +132,27 @@ class ComposeEnvService:
return None
from app.services.env_service import EnvService
- env = EnvService.get_effective_env(app.id)
- if not env:
- # No effective env → make sure no stale override lingers.
+ # Per-service effective env: a variable lands on every service unless
+ # it targets a specific one (EnvironmentVariable/SharedVariable
+ # .target_service). Local env vars override shared variable groups.
+ per_service = EnvService.get_effective_env_for_services(app.id, service_names)
+ if not per_service or not any(per_service.values()):
+ # No effective env on any service → make sure no stale override lingers.
cls._remove_override(project_path)
return None
- environment = {k: cls._escape(v) for k, v in env.items() if k}
- override = {
- 'services': {
- name: {'environment': dict(environment)} for name in service_names
+ services_block = {}
+ for name in service_names:
+ svc_env = per_service.get(name) or {}
+ if not svc_env:
+ continue # nothing targeted at this service
+ services_block[name] = {
+ 'environment': {k: cls._escape(v) for k, v in svc_env.items() if k}
}
- }
+ if not services_block:
+ cls._remove_override(project_path)
+ return None
+ override = {'services': services_block}
override_path = cls.override_path(project_path)
header = (
diff --git a/backend/app/services/env_service.py b/backend/app/services/env_service.py
index 283f8954..31e61a85 100644
--- a/backend/app/services/env_service.py
+++ b/backend/app/services/env_service.py
@@ -12,6 +12,10 @@ from app.models import Application, EnvironmentVariable, EnvironmentVariableHist
logger = logging.getLogger(__name__)
+# Sentinel so callers can distinguish "leave target_service unchanged" (default)
+# from "clear it to all-services" (None) on update.
+_UNSET = object()
+
class EnvService:
"""Service for managing application environment variables."""
@@ -90,6 +94,55 @@ class EnvService:
return merged
+ @staticmethod
+ def get_effective_env_for_services(application_id, service_names):
+ """Per-service effective env for a compose app.
+
+ For each service in ``service_names`` returns the merged ``{key: value}``
+ it should receive: variables targeting all services (``target_service``
+ NULL) plus variables targeting that specific service, with the app's own
+ local env vars overriding shared variable groups. Variables targeted at a
+ *different* service are excluded for that service.
+
+ Returns ``{service_name: {key: value}}`` (decrypted). Best-effort — shared
+ resolution failures fall back to local vars and never block a deploy.
+ """
+ app = Application.query.get(application_id)
+ if not app or not service_names:
+ return {}
+
+ context = {
+ 'workspace_id': str(app.workspace_id) if app.workspace_id is not None else None,
+ 'project_id': str(app.project_id) if app.project_id is not None else None,
+ 'environment_id': str(app.environment_id) if app.environment_id is not None else None,
+ }
+ local_vars = EnvironmentVariable.query.filter_by(application_id=application_id).all()
+
+ result = {}
+ for svc in service_names:
+ env = {}
+ # Shared groups applicable to this service (NULL-target + this svc).
+ try:
+ from app.services.shared_resource_service import SharedResourceService
+ resolved = SharedResourceService.resolve_hierarchical(
+ 'application', application_id, context=context,
+ mask_secrets=False, interpolate=True, service=svc,
+ )
+ for entry in resolved or []:
+ key = entry.get('key')
+ if key:
+ env[key] = entry.get('value')
+ except Exception as e: # best-effort
+ logger.warning('Shared resolution failed for app %s svc %s: %s',
+ application_id, svc, e)
+ # Local vars override; include all-services + this-service targets.
+ for ev in local_vars:
+ tgt = ev.target_service
+ if tgt in (None, '') or tgt == svc:
+ env[ev.key] = ev.value
+ result[svc] = env
+ return result
+
@staticmethod
def get_env_var(application_id, key):
"""Get a single environment variable by key."""
@@ -104,16 +157,23 @@ class EnvService:
return EnvironmentVariable.query.get(env_var_id)
@staticmethod
- def set_env_var(application_id, key, value, is_secret=False, description=None, user_id=None):
+ def set_env_var(application_id, key, value, is_secret=False, description=None,
+ user_id=None, target_service=_UNSET):
"""
Set an environment variable (create or update).
Returns (env_var, created, error)
+
+ ``target_service`` scopes the var to one compose service (None = all
+ services). Left unset on update, the existing target is preserved.
"""
# Validate key
valid, error = EnvService.validate_key(key)
if not valid:
return None, False, error
+ # Normalize an empty target to "all services" (None).
+ norm_target = None if target_service in ('', _UNSET) else target_service
+
# Check if application exists
app = Application.query.get(application_id)
if not app:
@@ -129,6 +189,8 @@ class EnvService:
existing.is_secret = is_secret
if description is not None:
existing.description = description
+ if target_service is not _UNSET:
+ existing.target_service = norm_target
# Record history
EnvironmentVariableHistory.record_change(
@@ -144,6 +206,7 @@ class EnvService:
key=key,
is_secret=is_secret,
description=description,
+ target_service=norm_target,
created_by=user_id
)
env_var.value = value
diff --git a/backend/app/services/shared_resource_service.py b/backend/app/services/shared_resource_service.py
index 02b40774..5cf5f2e0 100644
--- a/backend/app/services/shared_resource_service.py
+++ b/backend/app/services/shared_resource_service.py
@@ -26,6 +26,9 @@ from app.models.shared_resource import (
SharedVariableGroupAttachment,
)
+# Sentinel: distinguish "leave target_service unchanged" from "clear to all (None)".
+_UNSET = object()
+
def _audit(action, **kwargs):
"""Best-effort audit log for a shared-resource mutation.
@@ -231,8 +234,12 @@ class SharedResourceService:
# --------------------------------------------- variables within a group
@staticmethod
- def set_variable(group_id, key, value, is_secret=False):
- """Create or update a variable in a group (upsert by key)."""
+ def set_variable(group_id, key, value, is_secret=False, target_service=_UNSET):
+ """Create or update a variable in a group (upsert by key).
+
+ ``target_service`` scopes the var to one compose service (None = all).
+ Left unset on update, the existing target is preserved.
+ """
group = SharedVariableGroup.query.get(group_id)
if not group:
return None
@@ -240,15 +247,19 @@ class SharedResourceService:
if not key:
raise ValueError('key is required')
+ norm_target = None if target_service in ('', _UNSET) else target_service
var = SharedVariable.query.filter_by(group_id=group_id, key=key).first()
created = var is None
if var is None:
- var = SharedVariable(group_id=group_id, key=key, is_secret=bool(is_secret))
+ var = SharedVariable(group_id=group_id, key=key, is_secret=bool(is_secret),
+ target_service=norm_target)
var.value = value if value is not None else ''
db.session.add(var)
else:
var.value = value if value is not None else ''
var.is_secret = bool(is_secret)
+ if target_service is not _UNSET:
+ var.target_service = norm_target
db.session.commit()
_audit(
'resource.update',
@@ -261,7 +272,7 @@ class SharedResourceService:
return var
@staticmethod
- def update_variable(variable_id, value=None, is_secret=None):
+ def update_variable(variable_id, value=None, is_secret=None, target_service=_UNSET):
var = SharedVariable.query.get(variable_id)
if not var:
return None
@@ -269,6 +280,8 @@ class SharedResourceService:
var.value = value
if is_secret is not None:
var.is_secret = bool(is_secret)
+ if target_service is not _UNSET:
+ var.target_service = None if target_service in ('', None) else target_service
db.session.commit()
_audit(
'resource.update',
@@ -437,7 +450,8 @@ class SharedResourceService:
@staticmethod
def resolve_hierarchical_from_layers(layers, direct_vars=None,
- mask_secrets=True, interpolate=True):
+ mask_secrets=True, interpolate=True,
+ service=None):
"""Pure merge over pre-fetched layers — the unit-testable core.
``layers`` is an ordered iterable of ``(source_scope, groups)`` tuples
@@ -459,12 +473,23 @@ class SharedResourceService:
resolved = {}
plaintext_by_key = {}
+ def _targets(var):
+ """A var applies when it targets all services (NULL) or, if a service
+ is requested, that specific service."""
+ tgt = getattr(var, 'target_service', None)
+ if service is None or tgt in (None, ''):
+ return True
+ return tgt == service
+
def _apply(source_scope, var, group):
+ if not _targets(var):
+ return
plaintext = var.value # decrypted
resolved[var.key] = {
'key': var.key,
'plaintext': plaintext,
'is_secret': bool(var.is_secret),
+ 'target_service': getattr(var, 'target_service', None),
'group_id': group.id if group is not None else None,
'group_name': group.name if group is not None else None,
'source_scope': source_scope,
@@ -497,7 +522,7 @@ class SharedResourceService:
@staticmethod
def resolve_hierarchical(resource_type, resource_id, context=None,
- mask_secrets=True, interpolate=True):
+ mask_secrets=True, interpolate=True, service=None):
"""DB-backed hierarchical resolution for a resource.
``context`` may carry ``workspace_id``, ``project_id`` and
@@ -529,5 +554,5 @@ class SharedResourceService:
return SharedResourceService.resolve_hierarchical_from_layers(
layers, direct_vars=None, mask_secrets=mask_secrets,
- interpolate=interpolate,
+ interpolate=interpolate, service=service,
)
diff --git a/backend/migrations/versions/036_env_target_service.py b/backend/migrations/versions/036_env_target_service.py
new file mode 100644
index 00000000..3a51b2da
--- /dev/null
+++ b/backend/migrations/versions/036_env_target_service.py
@@ -0,0 +1,49 @@
+"""Per-service targeting for env vars.
+
+Adds:
+- environment_variables.target_service
+- shared_variables.target_service
+
+NULL = all services. Lets a compose app scope a variable to one service in the
+managed env overlay (docker-compose.serverkit.yml).
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot
+before Alembic, so guard on the live schema.
+
+Revision ID: 036_env_target_service
+Revises: 035_app_ingress_plane
+Create Date: 2026-06-24
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '036_env_target_service'
+down_revision = '035_app_ingress_plane'
+branch_labels = None
+depends_on = None
+
+
+def _add_col(inspector, table, col):
+ if table in inspector.get_table_names():
+ cols = {c['name'] for c in inspector.get_columns(table)}
+ if col not in cols:
+ op.add_column(table, sa.Column(col, sa.String(120), nullable=True))
+
+
+def _drop_col(inspector, table, col):
+ if table in inspector.get_table_names():
+ cols = {c['name'] for c in inspector.get_columns(table)}
+ if col in cols:
+ op.drop_column(table, col)
+
+
+def upgrade():
+ inspector = sa.inspect(op.get_bind())
+ _add_col(inspector, 'environment_variables', 'target_service')
+ _add_col(inspector, 'shared_variables', 'target_service')
+
+
+def downgrade():
+ inspector = sa.inspect(op.get_bind())
+ _drop_col(inspector, 'shared_variables', 'target_service')
+ _drop_col(inspector, 'environment_variables', 'target_service')
diff --git a/backend/tests/test_compose_env_overlay.py b/backend/tests/test_compose_env_overlay.py
index 45504a17..93dfcf86 100644
--- a/backend/tests/test_compose_env_overlay.py
+++ b/backend/tests/test_compose_env_overlay.py
@@ -31,22 +31,23 @@ def _make_compose_app(tmp_path, workspace_id=99):
return a
-def _set_local(app_id, key, value, is_secret=False):
+def _set_local(app_id, key, value, is_secret=False, target_service=None):
from app import db
from app.models import EnvironmentVariable
- ev = EnvironmentVariable(application_id=app_id, key=key, is_secret=is_secret)
+ ev = EnvironmentVariable(application_id=app_id, key=key, is_secret=is_secret,
+ target_service=target_service)
ev.value = value
db.session.add(ev)
db.session.commit()
-def _make_scoped_group(scope_type, scope_id, key, value):
+def _make_scoped_group(scope_type, scope_id, key, value, target_service=None):
from app import db
from app.models.shared_resource import SharedVariableGroup, SharedVariable
g = SharedVariableGroup(scope_type=scope_type, scope_id=str(scope_id), name='g')
db.session.add(g)
db.session.commit()
- v = SharedVariable(group_id=g.id, key=key, is_secret=False)
+ v = SharedVariable(group_id=g.id, key=key, is_secret=False, target_service=target_service)
v.value = value
db.session.add(v)
db.session.commit()
@@ -82,6 +83,40 @@ def test_refresh_writes_overlay_for_every_service(app, tmp_path):
assert env['OVERRIDE_ME'] == 'local_wins' # local beat the shared group
+def test_per_service_targeting(app, tmp_path):
+ from app.services.compose_env_service import ComposeEnvService
+ with app.app_context():
+ a = _make_compose_app(tmp_path, workspace_id=77)
+ # untargeted → both services
+ _set_local(a.id, 'COMMON', 'everywhere')
+ # local targeted at web only
+ _set_local(a.id, 'WEB_ONLY', 'w', target_service='web')
+ # shared var targeted at db only
+ _make_scoped_group('workspace', 77, 'DB_ONLY', 'd', target_service='db')
+
+ path = ComposeEnvService.refresh_for_project(str(tmp_path))
+ with open(path, encoding='utf-8') as f:
+ data = yaml.safe_load(f)
+
+ web = data['services']['web']['environment']
+ db = data['services']['db']['environment']
+
+ assert web['COMMON'] == 'everywhere' and db['COMMON'] == 'everywhere'
+ assert web['WEB_ONLY'] == 'w' and 'WEB_ONLY' not in db
+ assert db['DB_ONLY'] == 'd' and 'DB_ONLY' not in web
+
+
+def test_effective_env_for_services_helper(app, tmp_path):
+ from app.services.env_service import EnvService
+ with app.app_context():
+ a = _make_compose_app(tmp_path, workspace_id=88)
+ _set_local(a.id, 'ALL', 'a')
+ _set_local(a.id, 'ONLY_DB', 'x', target_service='db')
+ per = EnvService.get_effective_env_for_services(a.id, ['web', 'db'])
+ assert per['web'] == {'ALL': 'a'}
+ assert per['db'] == {'ALL': 'a', 'ONLY_DB': 'x'}
+
+
def test_dollar_signs_are_escaped(app, tmp_path):
from app.services.compose_env_service import ComposeEnvService
with app.app_context():
diff --git a/frontend/src/components/EnvironmentVariables.jsx b/frontend/src/components/EnvironmentVariables.jsx
index 608bcc13..a9fee00d 100644
--- a/frontend/src/components/EnvironmentVariables.jsx
+++ b/frontend/src/components/EnvironmentVariables.jsx
@@ -19,12 +19,17 @@ const EnvironmentVariables = ({ appId }) => {
const [newValue, setNewValue] = useState('');
const [newIsSecret, setNewIsSecret] = useState(false);
const [newDescription, setNewDescription] = useState('');
+ const [newTargetService, setNewTargetService] = useState('');
+
+ // Compose service targeting (empty list => single-container app, hide selector)
+ const [composeServices, setComposeServices] = useState([]);
// UI state
const [showValues, setShowValues] = useState({});
const [allVisible, setAllVisible] = useState(false);
const [editingId, setEditingId] = useState(null);
const [editValue, setEditValue] = useState('');
+ const [editTargetService, setEditTargetService] = useState('');
const [showImportModal, setShowImportModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
const [importContent, setImportContent] = useState('');
@@ -36,8 +41,19 @@ const EnvironmentVariables = ({ appId }) => {
useEffect(() => {
loadEnvVars();
+ loadComposeServices();
}, [appId]);
+ async function loadComposeServices() {
+ try {
+ const data = await api.getComposeServices(appId);
+ setComposeServices(data.services || []);
+ } catch {
+ // Non-compose apps or errors: keep single-container UX (no selector).
+ setComposeServices([]);
+ }
+ }
+
async function loadEnvVars() {
try {
setLoading(true);
@@ -60,12 +76,13 @@ const EnvironmentVariables = ({ appId }) => {
setSaving(true);
try {
- await api.createEnvVar(appId, newKey.trim(), newValue, newIsSecret, newDescription || null);
+ await api.createEnvVar(appId, newKey.trim(), newValue, newIsSecret, newDescription || null, newTargetService || null);
toast.success('Environment variable added');
setNewKey('');
setNewValue('');
setNewIsSecret(false);
setNewDescription('');
+ setNewTargetService('');
loadEnvVars();
} catch (err) {
toast.error(err.message || 'Failed to add environment variable');
@@ -79,10 +96,17 @@ const EnvironmentVariables = ({ appId }) => {
setSaving(true);
try {
- await api.updateEnvVar(appId, key, { value: editValue });
+ const payload = { value: editValue };
+ // Only thread target_service through for compose apps. Empty string
+ // clears the var back to all-services; a name targets one service.
+ if (composeServices.length > 0) {
+ payload.target_service = editTargetService || '';
+ }
+ await api.updateEnvVar(appId, key, payload);
toast.success('Environment variable updated');
setEditingId(null);
setEditValue('');
+ setEditTargetService('');
loadEnvVars();
} catch (err) {
toast.error(err.message || 'Failed to update environment variable');
@@ -136,11 +160,13 @@ const EnvironmentVariables = ({ appId }) => {
function startEditing(envVar) {
setEditingId(envVar.id);
setEditValue(envVar.value);
+ setEditTargetService(envVar.target_service || '');
}
function cancelEditing() {
setEditingId(null);
setEditValue('');
+ setEditTargetService('');
}
async function handleExport(includeSecrets = true) {
@@ -310,13 +336,29 @@ const EnvironmentVariables = ({ appId }) => {
Add
</Button>
</div>
- <Input
- type="text"
- value={newDescription}
- onChange={(e) => setNewDescription(e.target.value)}
- placeholder="Optional description..."
- className="env-description-input"
- />
+ <div className="env-form-meta-row">
+ <Input
+ type="text"
+ value={newDescription}
+ onChange={(e) => setNewDescription(e.target.value)}
+ placeholder="Optional description..."
+ className="env-description-input"
+ />
+ {composeServices.length > 0 && (
+ <label className="env-target-select" title="Inject this variable into a single compose service">
+ <span className="env-target-select__label">Applies to</span>
+ <select
+ value={newTargetService}
+ onChange={(e) => setNewTargetService(e.target.value)}
+ >
+ <option value="">All services</option>
+ {composeServices.map((svc) => (
+ <option key={svc} value={svc}>{svc}</option>
+ ))}
+ </select>
+ </label>
+ )}
+ </div>
</form>
{/* Filter */}
@@ -354,6 +396,14 @@ const EnvironmentVariables = ({ appId }) => {
</svg>
</span>
)}
+ {envVar.target_service && (
+ <span
+ className="env-target-chip"
+ title={`Applies only to the "${envVar.target_service}" service`}
+ >
+ &rarr; {envVar.target_service}
+ </span>
+ )}
</span>
<div className="env-item-actions">
<button
@@ -435,6 +485,19 @@ const EnvironmentVariables = ({ appId }) => {
if (e.key === 'Escape') cancelEditing();
}}
/>
+ {composeServices.length > 0 && (
+ <select
+ className="env-target-select__control"
+ value={editTargetService}
+ onChange={(e) => setEditTargetService(e.target.value)}
+ title="Inject this variable into a single compose service"
+ >
+ <option value="">All services</option>
+ {composeServices.map((svc) => (
+ <option key={svc} value={svc}>{svc}</option>
+ ))}
+ </select>
+ )}
<Button size="sm" onClick={() => handleUpdate(envVar.key)}>
Save
</Button>
diff --git a/frontend/src/components/shared/SharedVariableGroups.jsx b/frontend/src/components/shared/SharedVariableGroups.jsx
index 413f8f90..b387dfd6 100644
--- a/frontend/src/components/shared/SharedVariableGroups.jsx
+++ b/frontend/src/components/shared/SharedVariableGroups.jsx
@@ -30,6 +30,7 @@ const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' })
const [varKey, setVarKey] = useState('');
const [varValue, setVarValue] = useState('');
const [varSecret, setVarSecret] = useState(false);
+ const [varTarget, setVarTarget] = useState('');
// attach form
const [attachType, setAttachType] = useState(RESOURCE_TYPES[0]);
@@ -96,10 +97,12 @@ const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' })
try {
await api.addGroupVariable(selectedId, {
key: varKey.trim(), value: varValue, isSecret: varSecret,
+ targetService: varTarget.trim() || null,
});
setVarKey('');
setVarValue('');
setVarSecret(false);
+ setVarTarget('');
loadDetail(selectedId);
loadGroups();
} catch (err) {
@@ -220,6 +223,7 @@ const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' })
<tr>
<th>Key</th>
<th>Value</th>
+ <th>Target service</th>
<th></th>
</tr>
</thead>
@@ -228,6 +232,18 @@ const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' })
<tr key={v.id} className={v.is_secret ? 'is-secret' : ''}>
<td className="shared-vars-table__key">{v.key}</td>
<td className="shared-vars-table__value">{v.value}</td>
+ <td className="shared-vars-table__target">
+ {v.target_service ? (
+ <span
+ className="env-target-chip"
+ title={`Applies only to the "${v.target_service}" service`}
+ >
+ &rarr; {v.target_service}
+ </span>
+ ) : (
+ <span className="shared-vars-table__target-all">all services</span>
+ )}
+ </td>
<td>
<button
type="button"
@@ -260,6 +276,14 @@ const SharedVariableGroups = ({ scopeType = 'workspace', scopeId = 'default' })
placeholder="value"
className="shared-groups__var-value"
/>
+ <Input
+ type="text"
+ value={varTarget}
+ onChange={(e) => setVarTarget(e.target.value)}
+ placeholder="all services"
+ className="shared-groups__var-target"
+ title="Target compose service (leave blank to apply to all services)"
+ />
<label className="shared-groups__secret">
<Checkbox checked={varSecret} onCheckedChange={setVarSecret} />
<span>Secret</span>
diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js
index 719032c6..ff979753 100644
--- a/frontend/src/services/api/apps.js
+++ b/frontend/src/services/api/apps.js
@@ -171,10 +171,13 @@ export async function getEnvVar(appId, key) {
return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`);
}
-export async function createEnvVar(appId, key, value, isSecret = false, description = null) {
+export async function createEnvVar(appId, key, value, isSecret = false, description = null, targetService = null) {
+ const body = { key, value, is_secret: isSecret, description };
+ // Only send target_service when set; empty/null means "all services".
+ if (targetService) body.target_service = targetService;
return this.request(`/apps/${appId}/env`, {
method: 'POST',
- body: { key, value, is_secret: isSecret, description }
+ body
});
}
@@ -220,6 +223,12 @@ export async function clearEnvVars(appId) {
});
}
+// Compose service names for an app (empty list for non-compose apps).
+// Used to target an env var at a single compose service.
+export async function getComposeServices(appId) {
+ return this.request(`/apps/${appId}/compose-services`);
+}
+
// Docker App Logs and Status
export async function getDockerAppLogs(appId, lines = 100) {
return this.request(`/apps/${appId}/logs?lines=${lines}`);
diff --git a/frontend/src/services/api/sharedResources.js b/frontend/src/services/api/sharedResources.js
index a448039a..fd8b006e 100644
--- a/frontend/src/services/api/sharedResources.js
+++ b/frontend/src/services/api/sharedResources.js
@@ -76,17 +76,22 @@ export async function deleteVariableGroup(groupId) {
// ----------------------------------------------- variables within a group
-export async function addGroupVariable(groupId, { key, value = '', isSecret = false }) {
+export async function addGroupVariable(groupId, { key, value = '', isSecret = false, targetService = null }) {
+ const body = { key, value, is_secret: isSecret };
+ // Empty/null target_service means "all services".
+ if (targetService) body.target_service = targetService;
return this.request(`/shared/variable-groups/${groupId}/variables`, {
method: 'POST',
- body: { key, value, is_secret: isSecret },
+ body,
});
}
-export async function updateGroupVariable(groupId, variableId, { value, isSecret } = {}) {
+export async function updateGroupVariable(groupId, variableId, { value, isSecret, targetService } = {}) {
const body = {};
if (value !== undefined) body.value = value;
if (isSecret !== undefined) body.is_secret = isSecret;
+ // Passing target_service (even empty string) sets it; empty clears to all services.
+ if (targetService !== undefined) body.target_service = targetService;
return this.request(`/shared/variable-groups/${groupId}/variables/${variableId}`, {
method: 'PUT',
body,
diff --git a/frontend/src/styles/components/_env-vars.scss b/frontend/src/styles/components/_env-vars.scss
index 131d751c..893d0e12 100644
--- a/frontend/src/styles/components/_env-vars.scss
+++ b/frontend/src/styles/components/_env-vars.scss
@@ -81,10 +81,60 @@
}
.env-description-input {
- width: 100%;
+ flex: 1;
font-size: $font-size-sm;
color: $text-secondary;
}
+
+ // Second form row: description + optional compose-service target
+ .env-form-meta-row {
+ display: flex;
+ gap: $space-2;
+ align-items: stretch;
+ }
+}
+
+// "Applies to" selector — compose-service targeting (add form)
+.env-target-select {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+ flex-shrink: 0;
+ color: $text-tertiary;
+ font-size: $font-size-sm;
+
+ &__label {
+ white-space: nowrap;
+ }
+
+ select,
+ &__control {
+ padding: $space-2 $space-3;
+ background: $bg-body;
+ border: 1px solid $border-subtle;
+ border-radius: $radius-sm;
+ color: $text-primary;
+ font-size: $font-size-sm;
+
+ &:hover {
+ border-color: $border-active;
+ }
+ }
+}
+
+// Standalone select control used in the inline edit row
+.env-target-select__control {
+ padding: $space-2 $space-3;
+ background: $bg-body;
+ border: 1px solid $border-subtle;
+ border-radius: $radius-sm;
+ color: $text-primary;
+ font-size: $font-size-sm;
+ flex-shrink: 0;
+
+ &:hover {
+ border-color: $border-active;
+ }
}
// Filter
@@ -187,6 +237,7 @@
display: flex;
gap: $space-2;
margin-top: $space-2;
+ flex-wrap: wrap;
input {
flex: 1;
@@ -195,6 +246,24 @@
}
}
+// Subtle chip showing the compose service a variable is scoped to.
+// Standalone so it can be reused in the shared-variables table too.
+.env-target-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-1;
+ padding: 1px $space-2;
+ border-radius: $radius-sm;
+ font-family: $font-mono;
+ font-size: $font-size-xs;
+ font-weight: 600;
+ line-height: 1.5;
+ color: $accent-primary;
+ background: rgba($accent-primary-raw, 0.12);
+ border: 1px solid rgba($accent-primary-raw, 0.22);
+ white-space: nowrap;
+}
+
.btn-icon {
display: flex;
align-items: center;
diff --git a/frontend/src/styles/components/_shared-resources.scss b/frontend/src/styles/components/_shared-resources.scss
index 4a974ba7..9c89d900 100644
--- a/frontend/src/styles/components/_shared-resources.scss
+++ b/frontend/src/styles/components/_shared-resources.scss
@@ -263,6 +263,15 @@
word-break: break-all;
}
+ &__target {
+ white-space: nowrap;
+ }
+
+ &__target-all {
+ color: $text-tertiary;
+ font-size: $font-size-xs;
+ }
+
&__group {
color: $text-tertiary;
white-space: nowrap;
@@ -424,6 +433,12 @@
min-width: 140px;
}
+ &__var-target {
+ width: 150px;
+ flex-shrink: 0;
+ font-family: $font-mono;
+ }
+
&__secret {
display: inline-flex;
align-items: center;