-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathscaffold_gha.py
More file actions
1095 lines (1002 loc) · 41.7 KB
/
scaffold_gha.py
File metadata and controls
1095 lines (1002 loc) · 41.7 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
DevOps-OS GitHub Actions Workflow Generator
This script generates GitHub Actions workflow files for CI/CD pipelines
using the DevOps-OS container as the execution environment.
Features:
- Generates workflows for build, test, deploy, or complete CI/CD
- Supports multiple programming languages
- Configurable Kubernetes deployment methods
- Customizable through command-line arguments or environment variables
- Container image configuration options
- Secrets and environment variable management
- Matrix build support for multiple OS/architectures
"""
TEMPLATE_INFO = {
"name": "gha",
"category": "CI/CD",
"description": "GitHub Actions workflows",
}
import os
import sys
import argparse
import json
import yaml
from string import Template
from pathlib import Path
class _NoAliasDumper(yaml.Dumper):
"""Custom YAML Dumper that never emits anchors or aliases.
When the same Python object (e.g. a ``branches`` list) is referenced in
multiple places inside the workflow dict, the default PyYAML serialiser
collapses those references into an anchor/alias pair such as::
branches: &id001
- main
pull_request:
branches: *id001
GitHub Actions does not support YAML aliases, and the output is
confusing to users. This dumper overrides ``ignore_aliases`` so that
every occurrence is written out in full.
"""
def ignore_aliases(self, data): # noqa: ARG002
return True
# Default paths
TEMPLATE_DIR = os.path.dirname(os.path.abspath(__file__))
OUTPUT_DIR = os.getcwd()
ENV_CONFIG_PATH = os.path.join(TEMPLATE_DIR, "devcontainer.env.json")
# Default workflow types
WORKFLOW_TYPES = ["build", "test", "deploy", "complete", "reusable"]
# Environment variable prefixes
ENV_PREFIX = "DEVOPS_OS_GHA_"
def parse_arguments():
"""Parse command line arguments with environment variable fallbacks."""
parser = argparse.ArgumentParser(description="Generate GitHub Actions workflow files for DevOps-OS")
parser.add_argument("--name",
help="Workflow name",
default=os.environ.get(f"{ENV_PREFIX}NAME", "DevOps-OS"))
parser.add_argument("--type", choices=WORKFLOW_TYPES,
help="Type of workflow to generate",
default=os.environ.get(f"{ENV_PREFIX}TYPE", "complete"))
parser.add_argument("--languages",
help="Comma-separated list of languages to enable (python,java,javascript,go)",
default=os.environ.get(f"{ENV_PREFIX}LANGUAGES", "python,javascript"))
parser.add_argument("--kubernetes", action="store_true",
help="Include Kubernetes deployment steps",
default=os.environ.get(f"{ENV_PREFIX}KUBERNETES", "false").lower() in ("true", "1", "yes"))
parser.add_argument("--registry",
help="Container registry URL",
default=os.environ.get(f"{ENV_PREFIX}REGISTRY", "ghcr.io"))
parser.add_argument("--k8s-method", choices=["kubectl", "kustomize", "argocd", "flux"],
help="Kubernetes deployment method",
default=os.environ.get(f"{ENV_PREFIX}K8S_METHOD", "kubectl"))
parser.add_argument("--output",
help="Output directory for generated workflow files",
default=os.environ.get(f"{ENV_PREFIX}OUTPUT", os.path.join(OUTPUT_DIR, ".github/workflows")))
parser.add_argument("--custom-values",
help="Path to custom values JSON file",
default=os.environ.get(f"{ENV_PREFIX}CUSTOM_VALUES"))
parser.add_argument("--image",
help="DevOps-OS container image to use",
default=os.environ.get(f"{ENV_PREFIX}IMAGE", "ghcr.io/yourorg/devops-os:latest"))
parser.add_argument("--branches",
help="Comma-separated list of branches to trigger workflow",
default=os.environ.get(f"{ENV_PREFIX}BRANCHES", "main"))
parser.add_argument("--matrix", action="store_true",
help="Enable matrix builds (multiple OS/architectures)",
default=os.environ.get(f"{ENV_PREFIX}MATRIX", "false").lower() in ("true", "1", "yes"))
parser.add_argument("--env-file",
help="Use DevOps-OS devcontainer.env.json for configuration",
default=os.environ.get(f"{ENV_PREFIX}ENV_FILE", ENV_CONFIG_PATH))
parser.add_argument("--reusable", action="store_true",
help="Generate a reusable workflow that can be called from other workflows",
default=os.environ.get(f"{ENV_PREFIX}REUSABLE", "false").lower() in ("true", "1", "yes"))
args = parser.parse_args()
# If type is 'reusable', set reusable flag to True
if args.type == "reusable":
args.reusable = True
return args
def load_custom_values(file_path):
"""Load custom values from a JSON file."""
if file_path and os.path.exists(file_path):
with open(file_path, 'r') as f:
return json.load(f)
return {}
def load_env_config(file_path):
"""Load DevOps-OS environment configuration."""
if file_path and os.path.exists(file_path):
with open(file_path, 'r') as f:
# Remove comments that start with // for JSON parsing
lines = f.readlines()
cleaned_json = ""
for line in lines:
if not line.strip().startswith("//"):
cleaned_json += line
return json.loads(cleaned_json)
return {}
def create_directory_structure(output_dir):
"""Create the necessary directory structure."""
os.makedirs(output_dir, exist_ok=True)
return output_dir
def generate_language_config(languages_str, env_config=None):
"""Generate language configuration JSON."""
languages = languages_str.split(',')
# Default to env_config if available, otherwise use languages from args
if env_config and 'languages' in env_config:
config = env_config['languages']
else:
config = {
"python": "python" in languages,
"java": "java" in languages,
"javascript": "javascript" in languages,
"go": "go" in languages
}
return config
def generate_kubernetes_config(k8s_enabled, k8s_method, env_config=None):
"""Generate Kubernetes configuration JSON."""
# Default to env_config if available
if env_config and 'kubernetes' in env_config:
return env_config['kubernetes']
if not k8s_enabled:
return {"k9s": False, "kustomize": False, "argocd_cli": False, "flux": False}
config = {
"k9s": True,
"kustomize": k8s_method == "kustomize",
"argocd_cli": k8s_method == "argocd",
"flux": k8s_method == "flux",
"kind": False,
"minikube": False
}
return config
def generate_cicd_config(env_config=None):
"""Generate CI/CD tools configuration JSON."""
if env_config and 'cicd' in env_config:
return env_config['cicd']
return {
"docker": True,
"terraform": True,
"kubectl": True,
"helm": True,
"github_actions": True
}
def generate_build_tools_config(env_config=None):
"""Generate build tools configuration JSON."""
if env_config and 'build_tools' in env_config:
return env_config['build_tools']
return {
"gradle": True,
"maven": True,
"ant": False,
"make": True,
"cmake": False
}
def generate_code_analysis_config(env_config=None):
"""Generate code analysis tools configuration JSON."""
if env_config and 'code_analysis' in env_config:
return env_config['code_analysis']
return {
"sonarqube": True,
"checkstyle": True,
"pmd": False,
"eslint": True,
"pylint": True
}
def generate_devops_tools_config(env_config=None):
"""Generate DevOps tools configuration JSON."""
if env_config and 'devops_tools' in env_config:
return env_config['devops_tools']
return {
"nexus": False,
"prometheus": True,
"grafana": True,
"elk": True,
"jenkins": False
}
def generate_build_workflow(args, values, configs):
"""Generate a build workflow."""
branches = [b.strip() for b in args.branches.split(',')]
image = values.get('container_image', args.image)
workflow = {
"name": f"{args.name} Build",
"on": {
"push": {
"branches": branches
},
"pull_request": {
"branches": branches
},
"workflow_dispatch": {}
},
"jobs": {
"build": {
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up build environment",
"run": "echo 'Setting up build environment for DevOps-OS'"
}
]
}
}
}
# Add matrix strategy if enabled
if args.matrix:
workflow["jobs"]["build"]["strategy"] = {
"matrix": {
"os": ["ubuntu-latest"],
"arch": ["amd64", "arm64"]
},
"fail-fast": False
}
workflow["jobs"]["build"]["runs-on"] = "${{ matrix.os }}"
# Add language-specific build steps
if configs["languages"].get("python", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Install Python dependencies",
"run": "if [ -f requirements.txt ]; then pip install -r requirements.txt; fi"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build Python package",
"run": "if [ -f setup.py ]; then pip install -e .; fi"
})
if configs["languages"].get("java", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Set up Java environment",
"run": "echo 'Setting up Java environment'"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build with Maven",
"run": "if [ -f pom.xml ]; then mvn -B package --file pom.xml; fi"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build with Gradle",
"run": "if [ -f build.gradle ]; then ./gradlew build; fi"
})
if configs["languages"].get("javascript", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Install Node.js dependencies",
"run": "if [ -f package.json ]; then npm ci; fi"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build JavaScript/TypeScript",
"run": "if [ -f package.json ]; then npm run build --if-present; fi"
})
if configs["languages"].get("go", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Build Go application",
"run": "if [ -f go.mod ]; then go build -v ./...; fi"
})
# Add code analysis if enabled
if configs.get("code_analysis", {}).get("sonarqube", False):
workflow["jobs"]["build"]["steps"].append({
"name": "SonarQube Analysis",
"run": "echo 'Running SonarQube analysis'"
})
# Add artifact upload
artifact_suffix = ""
if args.matrix:
artifact_suffix = "-${{ matrix.os }}-${{ matrix.arch }}"
workflow["jobs"]["build"]["steps"].append({
"name": "Upload build artifacts",
"uses": "actions/upload-artifact@v3",
"with": {
"name": f"build-artifacts{artifact_suffix}",
"path": values.get("artifact_path", "dist/"),
"retention-days": 1
}
})
return workflow
def generate_test_workflow(args, values, configs):
"""Generate a test workflow."""
branches = [b.strip() for b in args.branches.split(',')]
image = values.get('container_image', args.image)
workflow = {
"name": f"{args.name} Test",
"on": {
"push": {
"branches": branches
},
"pull_request": {
"branches": branches
},
"workflow_dispatch": {}
},
"jobs": {
"test": {
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up test environment",
"run": "echo 'Setting up test environment for DevOps-OS'"
}
]
}
}
}
# Add matrix strategy if enabled
if args.matrix:
workflow["jobs"]["test"]["strategy"] = {
"matrix": {
"os": ["ubuntu-latest"],
"arch": ["amd64", "arm64"]
},
"fail-fast": False
}
workflow["jobs"]["test"]["runs-on"] = "${{ matrix.os }}"
# Add language-specific test steps
if configs["languages"].get("python", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Install Python dependencies",
"run": "if [ -f requirements.txt ]; then pip install -r requirements.txt pytest pytest-cov; fi"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run Python tests",
"run": "if [ -d tests ]; then python -m pytest --cov=./ --cov-report=xml; fi"
})
if configs.get("code_analysis", {}).get("pylint", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run Pylint",
"run": "if command -v pylint &> /dev/null; then pylint --disable=C0111 **/*.py; fi"
})
if configs["languages"].get("java", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Set up Java environment",
"run": "echo 'Setting up Java environment'"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run Java tests with Maven",
"run": "if [ -f pom.xml ]; then mvn -B test --file pom.xml; fi"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run Java tests with Gradle",
"run": "if [ -f build.gradle ]; then ./gradlew test; fi"
})
if configs.get("code_analysis", {}).get("checkstyle", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run Checkstyle",
"run": "if [ -f pom.xml ]; then mvn checkstyle:checkstyle; fi"
})
if configs["languages"].get("javascript", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Install Node.js dependencies",
"run": "if [ -f package.json ]; then npm ci; fi"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run JavaScript tests",
"run": "if [ -f package.json ]; then npm test; fi"
})
if configs.get("code_analysis", {}).get("eslint", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run ESLint",
"run": "if [ -f package.json ] && grep -q eslint package.json; then npm run lint; fi"
})
if configs["languages"].get("go", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run Go tests",
"run": "if [ -f go.mod ]; then go test -v ./...; fi"
})
# Add test report
artifact_suffix = ""
if args.matrix:
artifact_suffix = "-${{ matrix.os }}-${{ matrix.arch }}"
workflow["jobs"]["test"]["steps"].append({
"name": "Upload test results",
"uses": "actions/upload-artifact@v3",
"with": {
"name": f"test-results{artifact_suffix}",
"path": values.get("test_report_path", "test-reports/"),
"retention-days": 1
}
})
workflow["jobs"]["test"]["steps"].append({
"name": "Upload coverage reports",
"uses": "codecov/codecov-action@v3",
"with": {
"files": "./coverage.xml,./coverage/lcov.info",
"fail_ci_if_error": False
}
})
return workflow
def generate_deploy_workflow(args, values, configs):
"""Generate a deployment workflow."""
branches = [b.strip() for b in args.branches.split(',')]
image = values.get('container_image', args.image)
workflow = {
"name": f"{args.name} Deploy",
"on": {
"push": {
"branches": branches
},
"workflow_dispatch": {
"inputs": {
"environment": {
"description": "Environment to deploy to",
"required": True,
"default": "dev",
"type": "choice",
"options": ["dev", "test", "staging", "prod"]
}
}
}
},
"jobs": {
"deploy": {
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up deployment environment",
"run": "echo 'Setting up deployment environment for DevOps-OS'"
},
{
"name": "Build and Push Docker Image",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"echo \"${{ secrets.REGISTRY_TOKEN }}\" | docker login " + args.registry + " -u ${{ github.actor }} --password-stdin",
"docker build -t " + args.registry + "/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest .",
"docker push " + args.registry + "/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest"
])
}
]
}
}
}
# Add Kubernetes deployment steps if enabled
if args.kubernetes:
if args.k8s_method == "kubectl":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy to Kubernetes",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"mkdir -p $HOME/.kube",
"echo \"${{ secrets.KUBECONFIG }}\" > $HOME/.kube/config",
"chmod 600 $HOME/.kube/config",
"kubectl apply -f ./k8s/deployment.yaml",
"kubectl apply -f ./k8s/service.yaml",
"kubectl rollout status deployment/my-app"
])
})
elif args.k8s_method == "kustomize":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy to Kubernetes with Kustomize",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"mkdir -p $HOME/.kube",
"echo \"${{ secrets.KUBECONFIG }}\" > $HOME/.kube/config",
"chmod 600 $HOME/.kube/config",
"kubectl apply -k ./k8s/overlays/${ENVIRONMENT}",
"kubectl rollout status deployment/my-app"
]),
"env": {
"ENVIRONMENT": "${{ github.event.inputs.environment || 'dev' }}"
}
})
elif args.k8s_method == "argocd":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy with ArgoCD",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"argocd login $ARGOCD_SERVER --username $ARGOCD_USERNAME --password $ARGOCD_PASSWORD --insecure",
"argocd app sync my-application",
"argocd app wait my-application --health"
]),
"env": {
"ARGOCD_SERVER": "${{ secrets.ARGOCD_SERVER }}",
"ARGOCD_USERNAME": "${{ secrets.ARGOCD_USERNAME }}",
"ARGOCD_PASSWORD": "${{ secrets.ARGOCD_PASSWORD }}"
}
})
elif args.k8s_method == "flux":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy with Flux",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"flux reconcile source git flux-system",
"flux reconcile kustomization flux-system"
])
})
return workflow
def generate_complete_workflow(args, values, configs):
"""Generate a complete CI/CD workflow."""
branches = [b.strip() for b in args.branches.split(',')]
image = values.get('container_image', args.image)
workflow = {
"name": f"{args.name} CI/CD",
"on": {
"push": {
"branches": branches
},
"pull_request": {
"branches": branches
},
"workflow_dispatch": {
"inputs": {
"environment": {
"description": "Environment to deploy to",
"required": True,
"default": "dev",
"type": "choice",
"options": ["dev", "test", "staging", "prod"]
}
}
}
},
"jobs": {
"build": {
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up build environment",
"run": "echo 'Setting up build environment for DevOps-OS'"
}
]
},
"test": {
"needs": ["build"],
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up test environment",
"run": "echo 'Setting up test environment for DevOps-OS'"
}
]
},
"deploy": {
"needs": ["test"],
"if": "github.ref == 'refs/heads/main'",
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up deployment environment",
"run": "echo 'Setting up deployment environment for DevOps-OS'"
}
]
}
}
}
# Add matrix strategy if enabled
if args.matrix:
for job in ["build", "test", "deploy"]:
workflow["jobs"][job]["strategy"] = {
"matrix": {
"os": ["ubuntu-latest"],
"arch": ["amd64", "arm64"]
},
"fail-fast": False
}
workflow["jobs"][job]["runs-on"] = "${{ matrix.os }}"
# Add language-specific build steps
if configs["languages"].get("python", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Install Python dependencies",
"run": "if [ -f requirements.txt ]; then pip install -r requirements.txt; fi"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build Python package",
"run": "if [ -f setup.py ]; then pip install -e .; elif [ -f pyproject.toml ]; then pip install -e .; fi"
})
if configs["languages"].get("java", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Set up Java environment",
"run": "echo 'Setting up Java environment'"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build with Maven",
"run": "if [ -f pom.xml ]; then mvn -B package --file pom.xml; fi"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build with Gradle",
"run": "if [ -f build.gradle ]; then ./gradlew build; fi"
})
if configs["languages"].get("javascript", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Install Node.js dependencies",
"run": "if [ -f package.json ]; then npm ci; fi"
})
workflow["jobs"]["build"]["steps"].append({
"name": "Build JavaScript/TypeScript",
"run": "if [ -f package.json ]; then npm run build --if-present; fi"
})
if configs["languages"].get("go", False):
workflow["jobs"]["build"]["steps"].append({
"name": "Build Go application",
"run": "if [ -f go.mod ]; then go build -v ./...; fi"
})
# Add artifact upload for build
artifact_suffix = ""
if args.matrix:
artifact_suffix = "-${{ matrix.os }}-${{ matrix.arch }}"
workflow["jobs"]["build"]["steps"].append({
"name": "Upload build artifacts",
"uses": "actions/upload-artifact@v3",
"with": {
"name": f"build-artifacts{artifact_suffix}",
"path": values.get("artifact_path", "dist/"),
"retention-days": 1
}
})
# Add language-specific test steps
if configs["languages"].get("python", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Install Python dependencies",
"run": "if [ -f requirements.txt ]; then pip install -r requirements.txt pytest pytest-cov; fi"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run Python tests",
"run": "if [ -d tests ]; then python -m pytest --cov=./ --cov-report=xml; fi"
})
if configs.get("code_analysis", {}).get("pylint", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run Pylint",
"run": "if command -v pylint &> /dev/null; then pylint --disable=C0111 **/*.py; fi"
})
if configs["languages"].get("java", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Set up Java environment",
"run": "echo 'Setting up Java environment'"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run Java tests with Maven",
"run": "if [ -f pom.xml ]; then mvn -B test --file pom.xml; fi"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run Java tests with Gradle",
"run": "if [ -f build.gradle ]; then ./gradlew test; fi"
})
if configs.get("code_analysis", {}).get("checkstyle", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run Checkstyle",
"run": "if [ -f pom.xml ]; then mvn checkstyle:checkstyle; fi"
})
if configs["languages"].get("javascript", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Install Node.js dependencies",
"run": "if [ -f package.json ]; then npm ci; fi"
})
workflow["jobs"]["test"]["steps"].append({
"name": "Run JavaScript tests",
"run": "if [ -f package.json ]; then npm test; fi"
})
if configs.get("code_analysis", {}).get("eslint", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run ESLint",
"run": "if [ -f package.json ] && grep -q eslint package.json; then npm run lint; fi"
})
if configs["languages"].get("go", False):
workflow["jobs"]["test"]["steps"].append({
"name": "Run Go tests",
"run": "if [ -f go.mod ]; then go test -v ./...; fi"
})
# Add test report
workflow["jobs"]["test"]["steps"].append({
"name": "Upload test results",
"uses": "actions/upload-artifact@v3",
"with": {
"name": f"test-results{artifact_suffix}",
"path": values.get("test_report_path", "test-reports/"),
"retention-days": 1
}
})
workflow["jobs"]["test"]["steps"].append({
"name": "Upload coverage reports",
"uses": "codecov/codecov-action@v3",
"with": {
"files": "./coverage.xml,./coverage/lcov.info",
"fail_ci_if_error": False
}
})
# Add deployment steps
workflow["jobs"]["deploy"]["steps"].append({
"name": "Build and Push Docker Image",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"echo \"${{ secrets.REGISTRY_TOKEN }}\" | docker login " + args.registry + " -u ${{ github.actor }} --password-stdin",
"docker build -t " + args.registry + "/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest .",
"docker push " + args.registry + "/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest"
])
})
# Add Kubernetes deployment steps if enabled
if args.kubernetes:
if args.k8s_method == "kubectl":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy to Kubernetes",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"mkdir -p $HOME/.kube",
"echo \"${{ secrets.KUBECONFIG }}\" > $HOME/.kube/config",
"chmod 600 $HOME/.kube/config",
"kubectl apply -f ./k8s/deployment.yaml",
"kubectl apply -f ./k8s/service.yaml",
"kubectl rollout status deployment/my-app"
])
})
elif args.k8s_method == "kustomize":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy to Kubernetes with Kustomize",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"mkdir -p $HOME/.kube",
"echo \"${{ secrets.KUBECONFIG }}\" > $HOME/.kube/config",
"chmod 600 $HOME/.kube/config",
"kubectl apply -k ./k8s/overlays/${ENVIRONMENT}",
"kubectl rollout status deployment/my-app"
]),
"env": {
"ENVIRONMENT": "${{ github.event.inputs.environment || 'dev' }}"
}
})
elif args.k8s_method == "argocd":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy with ArgoCD",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"argocd login $ARGOCD_SERVER --username $ARGOCD_USERNAME --password $ARGOCD_PASSWORD --insecure",
"argocd app sync my-application",
"argocd app wait my-application --health"
]),
"env": {
"ARGOCD_SERVER": "${{ secrets.ARGOCD_SERVER }}",
"ARGOCD_USERNAME": "${{ secrets.ARGOCD_USERNAME }}",
"ARGOCD_PASSWORD": "${{ secrets.ARGOCD_PASSWORD }}"
}
})
elif args.k8s_method == "flux":
workflow["jobs"]["deploy"]["steps"].append({
"name": "Deploy with Flux",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"flux reconcile source git flux-system",
"flux reconcile kustomization flux-system"
])
})
return workflow
def generate_reusable_workflow(args, values, configs):
"""Generate a reusable workflow that can be called from other workflows."""
image = values.get('container_image', args.image)
workflow = {
"name": f"{args.name} Reusable Workflow",
"on": {
"workflow_call": {
"inputs": {
"environment": {
"description": "Environment to deploy to",
"required": False,
"default": "dev",
"type": "string"
},
"languages": {
"description": "JSON string of languages to enable",
"required": False,
"default": json.dumps(configs["languages"]),
"type": "string"
},
"kubernetes_deploy": {
"description": "Whether to deploy to Kubernetes",
"required": False,
"default": args.kubernetes,
"type": "boolean"
},
"k8s_method": {
"description": "Kubernetes deployment method",
"required": False,
"default": args.k8s_method,
"type": "string"
}
},
"secrets": {
"registry_token": {
"description": "Token for container registry",
"required": False
},
"kubeconfig": {
"description": "Kubernetes configuration",
"required": False
}
}
}
},
"jobs": {
"build": {
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up build environment",
"run": "echo 'Setting up build environment for DevOps-OS'"
}
]
},
"test": {
"needs": ["build"],
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up test environment",
"run": "echo 'Setting up test environment for DevOps-OS'"
}
]
},
"deploy": {
"needs": ["test"],
"if": "github.ref == 'refs/heads/main'",
"runs-on": "ubuntu-latest",
"container": {
"image": image,
"options": "--user root"
},
"steps": [
{
"name": "Checkout code",
"uses": "actions/checkout@v3"
},
{
"name": "Set up deployment environment",
"run": "echo 'Setting up deployment environment for DevOps-OS'"
},
{
"name": "Parse input configurations",
"id": "config",
"run": "\n".join([
"echo \"languages=${{ inputs.languages }}\" >> $GITHUB_OUTPUT",
"echo \"k8s_deploy=${{ inputs.kubernetes_deploy }}\" >> $GITHUB_OUTPUT",
"echo \"k8s_method=${{ inputs.k8s_method }}\" >> $GITHUB_OUTPUT",
"echo \"env=${{ inputs.environment }}\" >> $GITHUB_OUTPUT"
])
},
{
"name": "Build and Push Docker Image",
"if": "github.ref == 'refs/heads/main'",
"run": "\n".join([
"echo \"${{ secrets.registry_token }}\" | docker login " + args.registry + " -u ${{ github.actor }} --password-stdin",
"docker build -t " + args.registry + "/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest .",
"docker push " + args.registry + "/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest"
])
}
]
}
}
}