-
Notifications
You must be signed in to change notification settings - Fork 0
348 lines (307 loc) · 14.4 KB
/
dispatch-helm.yml
File metadata and controls
348 lines (307 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
name: "Dispatch to Helm Repository"
# Reusable workflow for dispatching workflow_dispatch events to Helm chart repositories
# Sends a SINGLE dispatch with ALL components to enable single commit updates
# Uses workflow_dispatch instead of repository_dispatch to allow targeting specific branches
#
# Usage (with path mapping - recommended):
# env:
# PATH_MAPPING: |
# {
# "src": {"name": "my-api", "context": "."},
# "console": {"name": "my-console", "context": "console"}
# }
# ...
# dispatch-helm:
# uses: LerianStudio/github-actions-shared-workflows/.github/workflows/dispatch-helm.yml@main
# with:
# helm_repository: org/helm-repo
# chart: my-app
# target_ref: develop
# version: ${{ github.ref_name }}
# paths_matrix: ${{ needs.detect.outputs.matrix }}
# path_mapping: ${{ env.PATH_MAPPING }}
# secrets:
# helm_repo_token: ${{ secrets.HELM_REPO_TOKEN }}
#
# Usage (advanced - with full components_json):
# dispatch-helm:
# uses: LerianStudio/github-actions-shared-workflows/.github/workflows/dispatch-helm.yml@main
# with:
# helm_repository: org/helm-repo
# chart: my-app
# components_json: '[{"name":"backend","version":"1.0.0"},{"name":"frontend","version":"1.0.0"}]'
# secrets:
# helm_repo_token: ${{ secrets.HELM_REPO_TOKEN }}
on:
workflow_call:
inputs:
helm_repository:
description: 'Helm repository to dispatch to (org/repo format)'
type: string
required: true
target_ref:
description: 'Target branch/ref to trigger the workflow on (e.g., develop, main)'
type: string
default: 'develop'
workflow_file:
description: 'Workflow file name to trigger (e.g., app-sync.yml)'
type: string
default: 'app-sync.yml'
chart:
description: 'Helm chart name'
type: string
required: true
version:
description: 'Version to apply to all components (e.g., from git tag). Removes "v" prefix automatically.'
type: string
required: true
paths_matrix:
description: 'Raw paths matrix from changed-paths action (e.g., ["src","console"]). Use with path_mapping.'
type: string
required: false
path_mapping:
description: 'JSON mapping of paths to app names (e.g., {"src":"my-api","console":"my-console"})'
type: string
required: false
components_json:
description: 'JSON array of components (alternative to paths_matrix): [{"name":"backend","version":"1.0.0"},...]'
type: string
required: false
components_base_path:
description: 'Base path for components (default: components)'
type: string
default: 'components'
env_file:
description: 'Env example file name relative to component path (default: .env.example)'
type: string
default: '.env.example'
detect_env_changes:
description: 'Whether to detect new environment variables'
type: boolean
default: true
values_key_mappings:
description: 'JSON mapping of component names to values.yaml keys. If not mapped, uses component name as fallback.'
type: string
default: ''
runner_type:
description: 'GitHub runner type to use'
type: string
default: 'blacksmith-4vcpu-ubuntu-2404'
secrets:
helm_repo_token:
description: 'GitHub token with access to Helm repository (needs repo scope)'
required: true
jobs:
prepare-and-dispatch:
name: Prepare and Dispatch
runs-on: ${{ inputs.runner_type }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Process all components
id: process
run: |
BASE_PATH="${{ inputs.components_base_path }}"
ENV_FILE="${{ inputs.env_file }}"
DETECT_ENV="${{ inputs.detect_env_changes }}"
VALUES_KEY_MAPPINGS='${{ inputs.values_key_mappings }}'
# Determine BEFORE_SHA for comparison
# For tags, github.event.before is 0000..., so we need to find the previous tag
BEFORE_SHA="${{ github.event.before }}"
if [ "$BEFORE_SHA" = "0000000000000000000000000000000000000000" ] || [ -z "$BEFORE_SHA" ]; then
# For tags, get the previous tag to compare against
CURRENT_TAG="${{ github.ref_name }}"
# Get list of tags sorted by version, find the one before current
PREVIOUS_TAG=$(git tag --sort=-v:refname | grep -A1 "^${CURRENT_TAG}$" | tail -1)
if [ -n "$PREVIOUS_TAG" ] && [ "$PREVIOUS_TAG" != "$CURRENT_TAG" ]; then
BEFORE_SHA=$(git rev-parse "${PREVIOUS_TAG}^{}" 2>/dev/null || echo "")
echo "Using previous tag for comparison: $PREVIOUS_TAG ($BEFORE_SHA)"
else
echo "No previous tag found, will treat all env vars as new"
BEFORE_SHA=""
fi
fi
# Get version from input (remove 'v' prefix if present)
INPUT_VERSION="${{ inputs.version }}"
INPUT_VERSION="${INPUT_VERSION#v}"
# Build components JSON from paths_matrix + path_mapping OR use components_json directly
if [ -n "${{ inputs.paths_matrix }}" ] && [ -n "${{ inputs.path_mapping }}" ]; then
echo "Using paths_matrix + path_mapping mode"
PATHS_MATRIX='${{ inputs.paths_matrix }}'
PATH_MAPPING='${{ inputs.path_mapping }}'
# Build components_json from paths and mapping
# Supports both simple format: {"src": "app-name"}
# and extended format: {"src": {"name": "app-name", "context": "."}}
COMPONENTS_JSON=$(echo "$PATHS_MATRIX" | jq -c --argjson mapping "$PATH_MAPPING" '
[.[] | . as $path | $mapping[$path] |
if type == "object" then
{name: .name, path: $path}
elif type == "string" then
{name: ., path: $path}
else
{name: $path, path: $path}
end
]
')
echo "Built components from paths: $COMPONENTS_JSON"
else
echo "Using components_json mode"
# Normalize components_json: handle both 'path' and 'working_dir' fields
RAW_COMPONENTS='${{ inputs.components_json }}'
echo "Raw components_json: $RAW_COMPONENTS"
# Normalize to use 'path' field (convert working_dir to path if needed)
COMPONENTS_JSON=$(echo "$RAW_COMPONENTS" | jq -c '[.[] | {name: .name, path: (.path // .working_dir // null), version: (.version // null)}]')
echo "Normalized components: $COMPONENTS_JSON"
fi
echo "Processing components: $COMPONENTS_JSON"
# Initialize output array
PROCESSED_COMPONENTS="["
FIRST=true
HAS_NEW_ENV_VARS=false
# Process each component
for row in $(echo "$COMPONENTS_JSON" | jq -c '.[]'); do
COMP_NAME=$(echo "$row" | jq -r '.name')
COMP_PATH=$(echo "$row" | jq -r '.path // empty')
COMP_VERSION=$(echo "$row" | jq -r '.version // empty')
# Use input version if provided and component doesn't have its own
if [ -z "$COMP_VERSION" ] && [ -n "$INPUT_VERSION" ]; then
COMP_VERSION="$INPUT_VERSION"
fi
# Determine component path
if [ -z "$COMP_PATH" ]; then
COMP_PATH="${BASE_PATH}/${COMP_NAME}"
fi
echo "Processing component: $COMP_NAME (path: $COMP_PATH)"
# Determine values_key (from mapping or fallback to component name)
VALUES_KEY="$COMP_NAME"
if [ -n "$VALUES_KEY_MAPPINGS" ] && [ "$VALUES_KEY_MAPPINGS" != "" ]; then
MAPPED_KEY=$(echo "$VALUES_KEY_MAPPINGS" | jq -r --arg name "$COMP_NAME" '.[$name] // empty')
if [ -n "$MAPPED_KEY" ]; then
VALUES_KEY="$MAPPED_KEY"
echo " Values key (mapped): $VALUES_KEY"
else
echo " Values key (fallback): $VALUES_KEY"
fi
else
echo " Values key: $VALUES_KEY"
fi
# Use component version or input version
VERSION="$COMP_VERSION"
echo " Version: $VERSION"
# Detect new env vars
ENV_VARS_JSON="{}"
if [ "$DETECT_ENV" = "true" ]; then
FULL_ENV_FILE="${COMP_PATH}/${ENV_FILE}"
if [ -f "$FULL_ENV_FILE" ]; then
CURRENT_VARS=$(grep -E "^[A-Z_][A-Z0-9_]*=" "$FULL_ENV_FILE" | cut -d'=' -f1 | sort || echo "")
PREVIOUS_VARS=""
if [ -n "$BEFORE_SHA" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then
PREVIOUS_VARS=$(git show "${BEFORE_SHA}:${FULL_ENV_FILE}" 2>/dev/null | grep -E "^[A-Z_][A-Z0-9_]*=" | cut -d'=' -f1 | sort || echo "")
fi
# Find new variables
NEW_VARS=""
if [ -n "$CURRENT_VARS" ]; then
while IFS= read -r var; do
if [ -n "$var" ] && ! echo "$PREVIOUS_VARS" | grep -q "^${var}$"; then
NEW_VARS="${NEW_VARS} ${var}"
fi
done <<< "$CURRENT_VARS"
fi
# Build JSON for new vars using jq for proper escaping
if [ -n "$(echo "$NEW_VARS" | tr -d '[:space:]')" ]; then
HAS_NEW_ENV_VARS=true
ENV_VARS_JSON="{}"
for var in $NEW_VARS; do
# Extract value after =, handle quoted values with inline comments
RAW_LINE=$(grep "^${var}=" "$FULL_ENV_FILE" | head -1)
RAW_VALUE="${RAW_LINE#*=}"
# If value starts with quote, extract only the quoted part (handles inline comments)
if [[ "$RAW_VALUE" == \"* ]]; then
# Remove leading quote and extract until closing quote
RAW_VALUE="${RAW_VALUE#\"}"
RAW_VALUE="${RAW_VALUE%%\"*}"
elif [[ "$RAW_VALUE" == \'* ]]; then
# Handle single quotes
RAW_VALUE="${RAW_VALUE#\'}"
RAW_VALUE="${RAW_VALUE%%\'*}"
else
# Unquoted value - strip inline comments (space + #)
RAW_VALUE="${RAW_VALUE%% #*}"
RAW_VALUE="${RAW_VALUE%% #*}" # tab + #
fi
# Use jq to properly escape the value for JSON
ENV_VARS_JSON=$(echo "$ENV_VARS_JSON" | jq --arg key "$var" --arg val "$RAW_VALUE" '. + {($key): $val}')
done
echo " New env vars: $NEW_VARS"
fi
fi
fi
# Build component object
COMP_OBJ="{\"name\":\"${COMP_NAME}\",\"values_key\":\"${VALUES_KEY}\",\"version\":\"${VERSION}\",\"env_vars\":${ENV_VARS_JSON}}"
if [ "$FIRST" = "true" ]; then
PROCESSED_COMPONENTS="${PROCESSED_COMPONENTS}${COMP_OBJ}"
FIRST=false
else
PROCESSED_COMPONENTS="${PROCESSED_COMPONENTS},${COMP_OBJ}"
fi
done
PROCESSED_COMPONENTS="${PROCESSED_COMPONENTS}]"
echo "Processed components: $PROCESSED_COMPONENTS"
echo "has_new_env_vars=$HAS_NEW_ENV_VARS" >> $GITHUB_OUTPUT
# Save to file to avoid escaping issues
echo "$PROCESSED_COMPONENTS" > /tmp/components_payload.json
- name: Dispatch to Helm repository
run: |
COMPONENTS=$(cat /tmp/components_payload.json)
# Build the full payload
PAYLOAD=$(jq -n \
--arg chart "${{ inputs.chart }}" \
--argjson components "$COMPONENTS" \
--arg has_new_env_vars "${{ steps.process.outputs.has_new_env_vars }}" \
--arg source_repo "${{ github.repository }}" \
--arg source_sha "${{ github.sha }}" \
--arg source_ref "${{ github.ref_name }}" \
--arg source_actor "${{ github.actor }}" \
'{
chart: $chart,
components: $components,
has_new_env_vars: ($has_new_env_vars == "true"),
source_repo: $source_repo,
source_sha: $source_sha,
source_ref: $source_ref,
source_actor: $source_actor
}')
echo "Dispatching payload:"
echo "$PAYLOAD" | jq .
# Convert payload to compact JSON string for workflow_dispatch input
PAYLOAD_STRING=$(echo "$PAYLOAD" | jq -c .)
# Send workflow_dispatch (allows targeting specific branch)
HTTP_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
-H "Authorization: token ${{ secrets.helm_repo_token }}" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ inputs.helm_repository }}/actions/workflows/${{ inputs.workflow_file }}/dispatches" \
-d "{\"ref\":\"${{ inputs.target_ref }}\",\"inputs\":{\"payload\":$(echo "$PAYLOAD_STRING" | jq -R .)}}")
HTTP_BODY=$(echo "$HTTP_RESPONSE" | sed '$d')
HTTP_CODE=$(echo "$HTTP_RESPONSE" | tail -n1)
echo "HTTP Status: $HTTP_CODE"
if [ "$HTTP_CODE" != "204" ]; then
echo "::error::Failed to dispatch workflow. HTTP $HTTP_CODE"
echo "$HTTP_BODY" | jq . 2>/dev/null || echo "$HTTP_BODY"
exit 1
fi
echo "Workflow dispatched successfully"
- name: Summary
run: |
COMPONENTS=$(cat /tmp/components_payload.json)
echo "### Dispatch Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Repository:** \`${{ inputs.helm_repository }}\`" >> $GITHUB_STEP_SUMMARY
echo "**Chart:** \`${{ inputs.chart }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Components:**" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Component | Version | New Env Vars |" >> $GITHUB_STEP_SUMMARY
echo "|-----------|---------|--------------|" >> $GITHUB_STEP_SUMMARY
echo "$COMPONENTS" | jq -r '.[] | "| \(.name) | \(.version) | \(.env_vars | if . == {} then "-" else (. | keys | join(", ")) end) |"' >> $GITHUB_STEP_SUMMARY