Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1238 lines (1164 loc) · 44.3 KB
/
Copy pathmain.go
File metadata and controls
1238 lines (1164 loc) · 44.3 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
// Package main implements the entry point for the Ansible Playbook Wrapper.
// This application executes Ansible playbooks and supports various configuration options.
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
ansible "github.com/arillso/go.ansible/v2"
"github.com/joho/godotenv"
cli "github.com/urfave/cli/v3"
)
// Errors defined for better error handling
var (
ErrPlaybookExecution = errors.New("playbook execution failed")
ErrConfigLoad = errors.New("failed to load configuration")
ErrInvalidParameter = errors.New("invalid parameter provided")
)
// appFlags defines all CLI flags for the application.
// Exported as a package-level variable so tests can reuse the same flag definitions.
var appFlags = []cli.Flag{
&cli.IntFlag{
Name: "execution-timeout",
Usage: "Timeout in minutes for the playbook execution (default: 30)",
Value: 30,
Sources: cli.EnvVars("ANSIBLE_EXECUTION_TIMEOUT", "INPUT_EXECUTION_TIMEOUT", "PLUGIN_EXECUTION_TIMEOUT"),
},
// Galaxy-related options
&cli.StringFlag{
Name: "galaxy-file",
Usage: "Path to the Ansible Galaxy requirements file",
Sources: cli.EnvVars("ANSIBLE_GALAXY_FILE", "INPUT_GALAXY_FILE", "PLUGIN_GALAXY_FILE"),
},
&cli.BoolFlag{
Name: "galaxy-force",
Usage: "Force reinstallation of roles or collections from the Galaxy file",
Sources: cli.EnvVars("ANSIBLE_GALAXY_FORCE", "INPUT_GALAXY_FORCE", "PLUGIN_GALAXY_FORCE"),
},
&cli.StringFlag{
Name: "galaxy-api-key",
Usage: "API key for authenticating with Ansible Galaxy",
Sources: cli.EnvVars("ANSIBLE_GALAXY_API_KEY"),
},
&cli.StringFlag{
Name: "galaxy-api-server-url",
Usage: "URL of the Ansible Galaxy API server",
Sources: cli.EnvVars("ANSIBLE_GALAXY_API_SERVER_URL"),
},
&cli.StringFlag{
Name: "galaxy-collections-path",
Usage: "Path to the directory where Galaxy collections are stored",
Sources: cli.EnvVars("ANSIBLE_GALAXY_COLLECTIONS_PATH"),
},
&cli.BoolFlag{
Name: "galaxy-disable-gpg-verify",
Usage: "Disable GPG signature verification for Galaxy operations",
Sources: cli.EnvVars("ANSIBLE_GALAXY_DISABLE_GPG_VERIFY"),
},
&cli.BoolFlag{
Name: "galaxy-force-with-deps",
Usage: "Force installation of collections including their dependencies",
Sources: cli.EnvVars("ANSIBLE_GALAXY_FORCE_WITH_DEPS"),
},
&cli.BoolFlag{
Name: "galaxy-ignore-certs",
Usage: "Ignore SSL certificate validation for Galaxy requests",
Sources: cli.EnvVars("ANSIBLE_GALAXY_IGNORE_CERTS"),
},
&cli.StringSliceFlag{
Name: "galaxy-ignore-signature-status-codes",
Usage: "Comma-separated list of HTTP status codes to ignore during signature validation",
Sources: cli.EnvVars("ANSIBLE_GALAXY_IGNORE_SIGNATURE_STATUS_CODES"),
},
&cli.StringFlag{
Name: "galaxy-keyring",
Usage: "Path to the GPG keyring file for Galaxy",
Sources: cli.EnvVars("ANSIBLE_GALAXY_KEYRING"),
},
&cli.BoolFlag{
Name: "galaxy-offline",
Usage: "Enable offline mode to prevent requests to Ansible Galaxy",
Sources: cli.EnvVars("ANSIBLE_GALAXY_OFFLINE"),
},
&cli.BoolFlag{
Name: "galaxy-pre",
Usage: "Allow installation of pre-release versions from Galaxy",
Sources: cli.EnvVars("ANSIBLE_GALAXY_PRE"),
},
&cli.IntFlag{
Name: "galaxy-required-valid-signature-count",
Usage: "Required number of valid GPG signatures for Galaxy content",
Sources: cli.EnvVars("ANSIBLE_GALAXY_REQUIRED_VALID_SIGNATURE_COUNT"),
},
&cli.StringFlag{
Name: "galaxy-requirements-file",
Usage: "Path to the Ansible Galaxy requirements file",
Sources: cli.EnvVars("ANSIBLE_GALAXY_REQUIREMENTS_FILE"),
},
&cli.StringFlag{
Name: "galaxy-signature",
Usage: "Specific GPG signature to verify for Galaxy content",
Sources: cli.EnvVars("ANSIBLE_GALAXY_SIGNATURE"),
},
&cli.IntFlag{
Name: "galaxy-timeout",
Usage: "Timeout (in seconds) for Galaxy operations",
Sources: cli.EnvVars("ANSIBLE_GALAXY_TIMEOUT"),
},
&cli.BoolFlag{
Name: "galaxy-upgrade",
Usage: "Automatically upgrade Galaxy collections to the latest version",
Sources: cli.EnvVars("ANSIBLE_GALAXY_UPGRADE"),
},
&cli.BoolFlag{
Name: "galaxy-no-deps",
Usage: "Disable automatic dependency resolution for Galaxy",
Sources: cli.EnvVars("ANSIBLE_GALAXY_NO_DEPS"),
},
// Inventory and playbook options
&cli.StringSliceFlag{
Name: "inventory",
Aliases: []string{"i"},
Usage: "Path to one or more inventory files for Ansible",
Sources: cli.EnvVars("ANSIBLE_INVENTORY", "INPUT_INVENTORY", "PLUGIN_INVENTORY"),
Required: true,
},
&cli.StringSliceFlag{
Name: "playbook",
Aliases: []string{"p"},
Usage: "List of playbooks to run",
Sources: cli.EnvVars("ANSIBLE_PLAYBOOK", "INPUT_PLAYBOOK", "PLUGIN_PLAYBOOK"),
Required: true,
},
&cli.StringFlag{
Name: "limit",
Aliases: []string{"l"},
Usage: "Limit playbook execution to a specific host group",
Sources: cli.EnvVars("ANSIBLE_LIMIT", "INPUT_LIMIT", "PLUGIN_LIMIT"),
},
&cli.StringFlag{
Name: "skip-tags",
Usage: "Skip plays and tasks that match the given tags",
Sources: cli.EnvVars("ANSIBLE_SKIP_TAGS", "INPUT_SKIP_TAGS", "PLUGIN_SKIP_TAGS"),
},
&cli.StringFlag{
Name: "start-at-task",
Usage: "Start playbook execution at the task with the given name",
Sources: cli.EnvVars("ANSIBLE_START_AT_TASK", "INPUT_START_AT_TASK", "PLUGIN_START_AT_TASK"),
},
&cli.StringFlag{
Name: "tags",
Aliases: []string{"t"},
Usage: "Run only tasks and plays with the specified tags",
Sources: cli.EnvVars("ANSIBLE_TAGS", "INPUT_TAGS", "PLUGIN_TAGS"),
},
&cli.StringSliceFlag{
Name: "extra-vars",
Aliases: []string{"e"},
Usage: "Set additional variables in key=value format",
Sources: cli.EnvVars("ANSIBLE_EXTRA_VARS", "INPUT_EXTRA_VARS", "PLUGIN_EXTRA_VARS"),
},
&cli.StringSliceFlag{
Name: "module-path",
Aliases: []string{"M"},
Usage: "Prepend directories to the module library path",
Sources: cli.EnvVars("ANSIBLE_MODULE_PATH", "INPUT_MODULE_PATH", "PLUGIN_MODULE_PATH"),
},
&cli.BoolFlag{
Name: "check",
Aliases: []string{"C"},
Usage: "Perform a dry run without making any changes",
Sources: cli.EnvVars("ANSIBLE_CHECK", "INPUT_CHECK", "PLUGIN_CHECK"),
},
&cli.BoolFlag{
Name: "diff",
Aliases: []string{"D"},
Usage: "Show the differences in files or templates when changes occur",
Sources: cli.EnvVars("ANSIBLE_DIFF", "INPUT_DIFF", "PLUGIN_DIFF"),
},
&cli.BoolFlag{
Name: "dry-run",
Usage: "Enable both check and diff mode for a dry run",
Sources: cli.EnvVars("ANSIBLE_DRY_RUN", "INPUT_DRY_RUN", "PLUGIN_DRY_RUN"),
},
&cli.BoolFlag{
Name: "flush-cache",
Usage: "Clear the fact cache for all hosts in the inventory",
Sources: cli.EnvVars("ANSIBLE_FLUSH_CACHE", "INPUT_FLUSH_CACHE", "PLUGIN_FLUSH_CACHE"),
},
&cli.BoolFlag{
Name: "force-handlers",
Usage: "Run all handlers even if a task fails",
Sources: cli.EnvVars("ANSIBLE_FORCE_HANDLERS", "INPUT_FORCE_HANDLERS", "PLUGIN_FORCE_HANDLERS"),
},
&cli.BoolFlag{
Name: "list-hosts",
Usage: "Display a list of matching hosts",
Sources: cli.EnvVars("ANSIBLE_LIST_HOSTS", "INPUT_LIST_HOSTS", "PLUGIN_LIST_HOSTS"),
},
&cli.BoolFlag{
Name: "list-tags",
Usage: "List all available tags",
Sources: cli.EnvVars("ANSIBLE_LIST_TAGS", "INPUT_LIST_TAGS", "PLUGIN_LIST_TAGS"),
},
&cli.BoolFlag{
Name: "list-tasks",
Usage: "List all tasks that would be executed",
Sources: cli.EnvVars("ANSIBLE_LIST_TASKS", "INPUT_LIST_TASKS", "PLUGIN_LIST_TASKS"),
},
&cli.BoolFlag{
Name: "syntax-check",
Usage: "Perform a syntax check on the playbook without executing it",
Sources: cli.EnvVars("ANSIBLE_SYNTAX_CHECK", "INPUT_SYNTAX_CHECK", "PLUGIN_SYNTAX_CHECK"),
},
&cli.IntFlag{
Name: "forks",
Aliases: []string{"f"},
Usage: "Number of parallel processes to use during playbook execution",
Value: 5,
Sources: cli.EnvVars("ANSIBLE_FORKS", "INPUT_FORKS", "PLUGIN_FORKS"),
},
// Vault and authentication options
&cli.StringFlag{
Name: "vault-id",
Usage: "Identity to use when accessing an Ansible Vault",
Sources: cli.EnvVars("ANSIBLE_VAULT_ID", "INPUT_VAULT_ID", "PLUGIN_VAULT_ID"),
},
&cli.StringFlag{
Name: "vault-password",
Usage: "Password for decrypting an Ansible Vault",
Sources: cli.EnvVars("ANSIBLE_VAULT_PASSWORD", "INPUT_VAULT_PASSWORD", "PLUGIN_VAULT_PASSWORD"),
},
&cli.IntFlag{
Name: "verbose",
Aliases: []string{"v"},
Usage: "Set the verbosity level, ranging from 0 (minimal output) to 4 (maximum verbosity)",
Sources: cli.EnvVars("ANSIBLE_VERBOSE", "INPUT_VERBOSE", "PLUGIN_VERBOSE"),
},
&cli.StringFlag{
Name: "private-key",
Aliases: []string{"k"},
Usage: "Path to the SSH private key for connection",
Sources: cli.EnvVars("ANSIBLE_PRIVATE_KEY", "INPUT_PRIVATE_KEY", "PLUGIN_PRIVATE_KEY"),
},
&cli.StringFlag{
Name: "private-key-passphrase",
Usage: "Passphrase for the SSH private key (used with ssh-agent)",
Sources: cli.EnvVars("ANSIBLE_PRIVATE_KEY_PASSPHRASE", "INPUT_PRIVATE_KEY_PASSPHRASE", "PLUGIN_PRIVATE_KEY_PASSPHRASE"),
},
&cli.StringFlag{
Name: "private-key-file",
Usage: "Path to the file containing the SSH private key",
Sources: cli.EnvVars("ANSIBLE_PRIVATE_KEY_FILE", "INPUT_PRIVATE_KEY_FILE", "PLUGIN_PRIVATE_KEY_FILE"),
},
&cli.StringSliceFlag{
Name: "additional-private-keys",
Usage: "Additional SSH private keys to load into ssh-agent (multiline or comma-separated)",
Sources: cli.EnvVars("ANSIBLE_ADDITIONAL_PRIVATE_KEYS", "INPUT_ADDITIONAL_PRIVATE_KEYS", "PLUGIN_ADDITIONAL_PRIVATE_KEYS"),
},
&cli.StringFlag{
Name: "user",
Aliases: []string{"u"},
Usage: "Username to use for the connection",
Sources: cli.EnvVars("ANSIBLE_USER", "INPUT_USER", "PLUGIN_USER"),
},
&cli.StringFlag{
Name: "connection",
Aliases: []string{"c"},
Usage: "Type of connection to use (e.g., SSH)",
Sources: cli.EnvVars("ANSIBLE_CONNECTION", "INPUT_CONNECTION", "PLUGIN_CONNECTION"),
},
&cli.IntFlag{
Name: "timeout",
Aliases: []string{"T"},
Usage: "Override the connection timeout (in seconds)",
Sources: cli.EnvVars("ANSIBLE_TIMEOUT", "INPUT_TIMEOUT", "PLUGIN_TIMEOUT"),
},
&cli.StringFlag{
Name: "ssh-common-args",
Usage: "Common arguments passed to all SSH-based connection methods",
Sources: cli.EnvVars("ANSIBLE_SSH_COMMON_ARGS", "INPUT_SSH_COMMON_ARGS", "PLUGIN_SSH_COMMON_ARGS"),
},
&cli.StringFlag{
Name: "sftp-extra-args",
Usage: "Extra arguments passed exclusively to SFTP",
Sources: cli.EnvVars("ANSIBLE_SFTP_EXTRA_ARGS", "INPUT_SFTP_EXTRA_ARGS", "PLUGIN_SFTP_EXTRA_ARGS"),
},
&cli.StringFlag{
Name: "scp-extra-args",
Usage: "Extra arguments passed exclusively to SCP",
Sources: cli.EnvVars("ANSIBLE_SCP_EXTRA_ARGS", "INPUT_SCP_EXTRA_ARGS", "PLUGIN_SCP_EXTRA_ARGS"),
},
&cli.StringFlag{
Name: "ssh-extra-args",
Usage: "Extra arguments passed exclusively to SSH",
Sources: cli.EnvVars("ANSIBLE_SSH_EXTRA_ARGS", "INPUT_SSH_EXTRA_ARGS", "PLUGIN_SSH_EXTRA_ARGS"),
},
&cli.StringFlag{
Name: "known-hosts",
Usage: "SSH known hosts entries for host key verification",
Sources: cli.EnvVars("ANSIBLE_KNOWN_HOSTS", "INPUT_KNOWN_HOSTS", "PLUGIN_KNOWN_HOSTS"),
},
&cli.BoolFlag{
Name: "become",
Aliases: []string{"b"},
Usage: "Enable privilege escalation to run tasks as another user",
Sources: cli.EnvVars("ANSIBLE_BECOME", "INPUT_BECOME", "PLUGIN_BECOME"),
},
&cli.StringFlag{
Name: "become-method",
Usage: "Method to use for privilege escalation (e.g., sudo)",
Sources: cli.EnvVars("ANSIBLE_BECOME_METHOD", "INPUT_BECOME_METHOD", "PLUGIN_BECOME_METHOD"),
},
&cli.StringFlag{
Name: "become-user",
Usage: "User to impersonate when using privilege escalation",
Sources: cli.EnvVars("ANSIBLE_BECOME_USER", "INPUT_BECOME_USER", "PLUGIN_BECOME_USER"),
},
&cli.BoolFlag{
Name: "ask-become-pass",
Usage: "Prompt for the become password",
Sources: cli.EnvVars("ANSIBLE_ASK_BECOME_PASS", "INPUT_ASK_BECOME_PASS", "PLUGIN_ASK_BECOME_PASS"),
},
&cli.BoolFlag{
Name: "ask-pass",
Usage: "Prompt for the SSH password",
Sources: cli.EnvVars("ANSIBLE_ASK_PASS", "INPUT_ASK_PASS", "PLUGIN_ASK_PASS"),
},
&cli.BoolFlag{
Name: "step",
Usage: "Prompt for confirmation before each task",
Sources: cli.EnvVars("ANSIBLE_STEP", "INPUT_STEP", "PLUGIN_STEP"),
},
&cli.StringFlag{
Name: "ssh-transfer-method",
Usage: "Method for file transfer over SSH (e.g., scp or sftp)",
Sources: cli.EnvVars("ANSIBLE_SSH_TRANSFER_METHOD", "INPUT_SSH_TRANSFER_METHOD", "PLUGIN_SSH_TRANSFER_METHOD"),
},
&cli.StringFlag{
Name: "output-callback",
Usage: "Set the stdout callback plugin for Ansible output",
Sources: cli.EnvVars("ANSIBLE_OUTPUT_CALLBACK", "INPUT_OUTPUT_CALLBACK", "PLUGIN_OUTPUT_CALLBACK"),
},
&cli.BoolFlag{
Name: "no-color",
Usage: "Disable colorized output",
Sources: cli.EnvVars("ANSIBLE_NO_COLOR", "INPUT_NO_COLOR", "PLUGIN_NO_COLOR"),
},
&cli.StringFlag{
Name: "vault-password-file",
Usage: "Path to a file containing the vault password",
Sources: cli.EnvVars("ANSIBLE_VAULT_PASSWORD_FILE", "INPUT_VAULT_PASSWORD_FILE", "PLUGIN_VAULT_PASSWORD_FILE"),
},
&cli.BoolFlag{
Name: "ask-vault-pass",
Usage: "Prompt for the vault password",
Sources: cli.EnvVars("ANSIBLE_ASK_VAULT_PASS", "INPUT_ASK_VAULT_PASS", "PLUGIN_ASK_VAULT_PASS"),
},
&cli.StringFlag{
Name: "fact-path",
Usage: "Path to local fact files",
Sources: cli.EnvVars("ANSIBLE_FACT_PATH", "INPUT_FACT_PATH", "PLUGIN_FACT_PATH"),
},
&cli.StringFlag{
Name: "fact-caching",
Usage: "Caching method to use for facts",
Sources: cli.EnvVars("ANSIBLE_FACT_CACHING", "INPUT_FACT_CACHING", "PLUGIN_FACT_CACHING"),
},
&cli.IntFlag{
Name: "fact-caching-timeout",
Usage: "Timeout (in seconds) for fact caching",
Sources: cli.EnvVars("ANSIBLE_FACT_CACHING_TIMEOUT", "INPUT_FACT_CACHING_TIMEOUT", "PLUGIN_FACT_CACHING_TIMEOUT"),
},
&cli.StringFlag{
Name: "callbacks-enabled",
Usage: "Comma-separated list of enabled callback plugins",
Sources: cli.EnvVars(
"ANSIBLE_CALLBACKS_ENABLED", "INPUT_CALLBACKS_ENABLED", "PLUGIN_CALLBACKS_ENABLED",
// deprecated aliases - remove in next major version
"ANSIBLE_CALLBACK_WHITELIST", "INPUT_CALLBACK_WHITELIST", "PLUGIN_CALLBACK_WHITELIST",
),
},
&cli.IntFlag{
Name: "poll-interval",
Usage: "Interval (in seconds) for polling",
Sources: cli.EnvVars("ANSIBLE_POLL_INTERVAL", "INPUT_POLL_INTERVAL", "PLUGIN_POLL_INTERVAL"),
},
&cli.StringFlag{
Name: "gather-subset",
Usage: "Limit the scope of gathered facts",
Sources: cli.EnvVars("ANSIBLE_GATHER_SUBSET", "INPUT_GATHER_SUBSET", "PLUGIN_GATHER_SUBSET"),
},
&cli.IntFlag{
Name: "gather-timeout",
Usage: "Timeout (in seconds) for gathering facts",
Sources: cli.EnvVars("ANSIBLE_GATHER_TIMEOUT", "INPUT_GATHER_TIMEOUT", "PLUGIN_GATHER_TIMEOUT"),
},
&cli.StringFlag{
Name: "strategy-plugin",
Usage: "Specify the strategy plugin to use",
Sources: cli.EnvVars("ANSIBLE_STRATEGY_PLUGIN", "INPUT_STRATEGY_PLUGIN", "PLUGIN_STRATEGY_PLUGIN"),
},
&cli.IntFlag{
Name: "max-fail-percentage",
Usage: "Max percentage of hosts that can fail before the playbook aborts",
Sources: cli.EnvVars("ANSIBLE_MAX_FAIL_PERCENTAGE", "INPUT_MAX_FAIL_PERCENTAGE", "PLUGIN_MAX_FAIL_PERCENTAGE"),
},
&cli.BoolFlag{
Name: "any-errors-fatal",
Usage: "Treat any error as fatal",
Sources: cli.EnvVars("ANSIBLE_ANY_ERRORS_FATAL", "INPUT_ANY_ERRORS_FATAL", "PLUGIN_ANY_ERRORS_FATAL"),
},
&cli.StringFlag{
Name: "config-file",
Usage: "Path to the configuration file",
Sources: cli.EnvVars("ANSIBLE_CONFIG_FILE", "INPUT_CONFIG_FILE", "PLUGIN_CONFIG_FILE"),
},
&cli.StringFlag{
Name: "temp-dir",
Usage: "Directory for temporary files",
Sources: cli.EnvVars("ANSIBLE_TEMP_DIR", "INPUT_TEMP_DIR", "PLUGIN_TEMP_DIR"),
},
&cli.IntFlag{
Name: "retries",
Usage: "Number of times to retry on failure (0 = no retries)",
Value: 0,
Sources: cli.EnvVars("ANSIBLE_RETRIES", "INPUT_RETRIES", "PLUGIN_RETRIES"),
},
&cli.IntFlag{
Name: "retry-delay",
Usage: "Delay in seconds between retries",
Value: 30,
Sources: cli.EnvVars("ANSIBLE_RETRY_DELAY", "INPUT_RETRY_DELAY", "PLUGIN_RETRY_DELAY"),
},
&cli.BoolFlag{
Name: "lint",
Usage: "Run ansible-lint on playbooks before execution",
Sources: cli.EnvVars("ANSIBLE_LINT", "INPUT_LINT", "PLUGIN_LINT"),
},
&cli.StringFlag{
Name: "output-file",
Usage: "Save Ansible stdout to a file (useful for capturing diff output)",
Sources: cli.EnvVars("ANSIBLE_OUTPUT_FILE", "INPUT_OUTPUT_FILE", "PLUGIN_OUTPUT_FILE"),
},
}
func main() {
// Load environment file if specified.
if filename, found := os.LookupEnv("PLUGIN_ENV_FILE"); found {
if err := godotenv.Load(filename); err != nil {
log.Printf("Warning: Could not load env file: %v", err)
}
}
cmd := &cli.Command{
Name: "Ansible Playbook Wrapper",
Usage: "Execute Ansible Playbooks",
Authors: []any{
"arillso <hello@arillso.io>",
},
Flags: appFlags,
Action: run,
}
if err := cmd.Run(context.Background(), os.Args); err != nil {
var ansibleErr *ansible.AnsibleError
if errors.As(err, &ansibleErr) {
if ansibleErr.ExitCode != 0 {
log.Printf("Error: %v", err)
}
os.Exit(ansibleErr.ExitCode)
}
log.Fatalf("Error: %v", err)
}
}
// normalizeSlice splits each element of a string slice on newlines and trims
// whitespace, filtering out empty entries. This allows GitHub Actions multiline
// inputs (using YAML |) to work alongside comma-separated values.
func normalizeSlice(values []string) []string {
var result []string
for _, v := range values {
for _, line := range strings.Split(v, "\n") {
line = strings.TrimSpace(line)
if line != "" {
result = append(result, line)
}
}
}
return result
}
// validateParameters checks that the given inventory files, playbook files,
// and galaxy file (if any) exist on disk. Callers should pass already-normalized
// slices so that normalization happens exactly once.
func validateParameters(inventories, playbooks []string, galaxyFile string) error {
for _, inv := range inventories {
if _, err := os.Stat(inv); os.IsNotExist(err) {
return fmt.Errorf("%w: inventory file does not exist: %s", ErrInvalidParameter, inv)
}
}
for _, pb := range playbooks {
if _, err := os.Stat(pb); os.IsNotExist(err) {
return fmt.Errorf("%w: playbook file does not exist: %s", ErrInvalidParameter, pb)
}
}
if galaxyFile != "" {
if _, err := os.Stat(galaxyFile); os.IsNotExist(err) {
return fmt.Errorf("%w: galaxy file does not exist: %s", ErrInvalidParameter, galaxyFile)
}
}
return nil
}
// setupKnownHosts appends SSH known host entries to ~/.ssh/known_hosts.
func setupKnownHosts(content string) error {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to determine home directory: %w", err)
}
sshDir := filepath.Join(home, ".ssh")
if err := os.MkdirAll(sshDir, 0700); err != nil {
return fmt.Errorf("failed to create .ssh directory: %w", err)
}
normalized := strings.ReplaceAll(content, "\r\n", "\n")
if !strings.HasSuffix(normalized, "\n") {
normalized += "\n"
}
khPath := filepath.Join(sshDir, "known_hosts")
// #nosec G304 -- path is built from os.UserHomeDir() and fixed literals,
// no part of it comes from action input. Mode stays 0600 on purpose.
f, err := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open known_hosts: %w", err)
}
defer func() { _ = f.Close() }()
if _, err := f.WriteString(normalized); err != nil {
return fmt.Errorf("failed to write known_hosts: %w", err)
}
var entryCount int
for _, line := range strings.Split(strings.TrimSpace(normalized), "\n") {
if line != "" && !strings.HasPrefix(line, "#") {
entryCount++
}
}
log.Printf("Written %d known host entries", entryCount)
return nil
}
// sshAgent holds the state of a running ssh-agent process.
type sshAgent struct {
sock string
pid string
}
// validateAgentSock checks that an SSH_AUTH_SOCK value parsed from ssh-agent
// output has the expected shape: a non-empty absolute path with no embedded
// newline or NUL byte (which could smuggle extra environment entries or break
// the child-process env block).
func validateAgentSock(sock string) error {
if strings.ContainsAny(sock, "\n\r\x00") {
return fmt.Errorf("contains a newline or NUL byte")
}
if !strings.HasPrefix(sock, "/") {
return fmt.Errorf("not an absolute path: %q", sock)
}
return nil
}
// validateAgentPID checks that an SSH_AGENT_PID value is a positive integer.
func validateAgentPID(pid string) error {
n, err := strconv.Atoi(pid)
if err != nil {
return fmt.Errorf("not an integer: %q", pid)
}
if n <= 0 {
return fmt.Errorf("not a positive PID: %d", n)
}
return nil
}
// startSSHAgent starts an ssh-agent, adds the given private key, and returns
// the agent state for cleanup. The key content is written to a temporary file
// which is removed immediately after being added to the agent.
func startSSHAgent(privateKey, passphrase string) (*sshAgent, error) {
// Start ssh-agent and capture its output.
var buf bytes.Buffer
agentCmd := exec.Command("ssh-agent", "-s")
agentCmd.Stdout = &buf
if err := agentCmd.Run(); err != nil {
return nil, fmt.Errorf("failed to start ssh-agent: %w", err)
}
// Parse SSH_AUTH_SOCK and SSH_AGENT_PID from agent output.
output := buf.String()
agent := &sshAgent{}
for _, line := range strings.Split(output, "\n") {
if strings.HasPrefix(line, "SSH_AUTH_SOCK=") {
agent.sock = strings.SplitN(strings.TrimPrefix(line, "SSH_AUTH_SOCK="), ";", 2)[0]
}
if strings.HasPrefix(line, "SSH_AGENT_PID=") {
agent.pid = strings.SplitN(strings.TrimPrefix(line, "SSH_AGENT_PID="), ";", 2)[0]
}
}
if agent.sock == "" {
return nil, fmt.Errorf("failed to parse SSH_AUTH_SOCK from ssh-agent output")
}
// Validate the parsed values before they are exported into the environment
// or used as a PID. ssh-agent is a trusted local process, but the output is
// passed straight into child-process env / signals, so enforce the expected
// shape as defence in depth (no newlines/NUL, socket is an absolute path,
// PID is a positive integer).
if err := validateAgentSock(agent.sock); err != nil {
return nil, fmt.Errorf("invalid SSH_AUTH_SOCK from ssh-agent: %w", err)
}
if agent.pid != "" {
if err := validateAgentPID(agent.pid); err != nil {
return nil, fmt.Errorf("invalid SSH_AGENT_PID from ssh-agent: %w", err)
}
}
// Write private key to a temporary file for ssh-add.
tmpFile, err := os.CreateTemp("", "ssh-agent-key-")
if err != nil {
return nil, fmt.Errorf("failed to create temp key file: %w", err)
}
keyPath := tmpFile.Name()
// Normalize line endings and ensure trailing newline.
normalized := strings.ReplaceAll(privateKey, "\r\n", "\n")
if !strings.HasSuffix(normalized, "\n") {
normalized += "\n"
}
if _, err := tmpFile.WriteString(normalized); err != nil {
_ = tmpFile.Close()
_ = os.Remove(keyPath)
return nil, fmt.Errorf("failed to write temp key file: %w", err)
}
if err := tmpFile.Close(); err != nil {
_ = os.Remove(keyPath)
return nil, fmt.Errorf("failed to close temp key file: %w", err)
}
// Add the key to the agent.
addCtx, addCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer addCancel()
addCmd := exec.CommandContext(addCtx, "ssh-add", keyPath)
addCmd.Env = append(os.Environ(), "SSH_AUTH_SOCK="+agent.sock)
// If a passphrase is provided, use SSH_ASKPASS to supply it non-interactively.
if passphrase != "" {
askpassScript, err := os.CreateTemp("", "ssh-askpass-")
if err != nil {
_ = os.Remove(keyPath)
return nil, fmt.Errorf("failed to create askpass script: %w", err)
}
askpassPath := askpassScript.Name()
// The script reads the passphrase from an environment variable rather
// than having it interpolated into the script body. This avoids any
// shell-escaping/injection concern: the passphrase never appears as a
// shell token, only as $ANSIBLE_ASKPASS_VALUE which the shell expands
// as data. It outputs the value once, then exits with error on retries
// to prevent ssh-add from looping indefinitely on wrong passphrases.
flagFile := askpassPath + ".used"
scriptContent := fmt.Sprintf(
"#!/bin/sh\nif [ -f '%s' ]; then exit 1; fi\ntouch '%s'\nprintf '%%s\\n' \"$ANSIBLE_ASKPASS_VALUE\"\n",
flagFile, flagFile)
if _, err := askpassScript.WriteString(scriptContent); err != nil {
_ = askpassScript.Close()
_ = os.Remove(askpassPath)
_ = os.Remove(keyPath)
return nil, fmt.Errorf("failed to write askpass script: %w", err)
}
_ = askpassScript.Close()
// #nosec G302 -- SSH_ASKPASS must be executable, so 0700 is the
// tightest mode that works; the file is a private temp file owned by
// this process and is removed once ssh-add returns.
if err := os.Chmod(askpassPath, 0700); err != nil {
_ = os.Remove(askpassPath)
_ = os.Remove(keyPath)
return nil, fmt.Errorf("failed to set askpass script permissions: %w", err)
}
addCmd.Env = append(addCmd.Env,
"SSH_ASKPASS="+askpassPath,
"SSH_ASKPASS_REQUIRE=force",
"DISPLAY=",
"ANSIBLE_ASKPASS_VALUE="+passphrase,
)
// Detach from controlling TTY so ssh-add uses SSH_ASKPASS.
addCmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
addCmd.Stdin = nil
defer func() {
_ = os.Remove(askpassPath)
_ = os.Remove(flagFile)
}()
}
if out, err := addCmd.CombinedOutput(); err != nil {
_ = os.Remove(keyPath)
return nil, fmt.Errorf("failed to add key to ssh-agent: %w: %s", err, string(out))
}
// Remove the temporary key file immediately after adding to agent.
_ = os.Remove(keyPath)
log.Printf("SSH agent started and key added (PID: %s)", agent.pid)
return agent, nil
}
// addKey adds an additional private key (without passphrase) to a running agent.
func (a *sshAgent) addKey(keyContent string) error {
tmpFile, err := os.CreateTemp("", "ssh-extra-key-")
if err != nil {
return fmt.Errorf("failed to create temp key file: %w", err)
}
keyPath := tmpFile.Name()
normalized := strings.ReplaceAll(keyContent, "\r\n", "\n")
if !strings.HasSuffix(normalized, "\n") {
normalized += "\n"
}
if _, err := tmpFile.WriteString(normalized); err != nil {
_ = tmpFile.Close()
_ = os.Remove(keyPath)
return fmt.Errorf("failed to write temp key file: %w", err)
}
if err := tmpFile.Close(); err != nil {
_ = os.Remove(keyPath)
return fmt.Errorf("failed to close temp key file: %w", err)
}
addCtx, addCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer addCancel()
addCmd := exec.CommandContext(addCtx, "ssh-add", keyPath)
addCmd.Env = append(os.Environ(), "SSH_AUTH_SOCK="+a.sock)
if out, err := addCmd.CombinedOutput(); err != nil {
_ = os.Remove(keyPath)
return fmt.Errorf("failed to add key to ssh-agent: %w: %s", err, string(out))
}
_ = os.Remove(keyPath)
log.Printf("Additional SSH key added to agent")
return nil
}
// splitPEMKeys splits raw input values into individual PEM key blocks.
// Unlike normalizeSlice, this preserves multi-line PEM content by splitting
// on PEM block boundaries rather than on bare newlines.
func splitPEMKeys(values []string) []string {
var keys []string
for _, v := range values {
v = strings.TrimSpace(v)
if v == "" {
continue
}
// Split on PEM END markers to separate multiple keys in one value.
rest := v
for rest != "" {
idx := strings.Index(rest, "-----END ")
if idx == -1 {
// No END marker; treat the remainder as a single key.
if k := strings.TrimSpace(rest); k != "" {
keys = append(keys, k)
}
break
}
// Find the closing "-----" after the END tag.
endIdx := strings.Index(rest[idx+len("-----END "):], "-----")
if endIdx == -1 {
// Malformed; take everything.
if k := strings.TrimSpace(rest); k != "" {
keys = append(keys, k)
}
break
}
boundary := idx + len("-----END ") + endIdx + len("-----")
key := strings.TrimSpace(rest[:boundary])
if key != "" {
keys = append(keys, key)
}
rest = rest[boundary:]
}
}
return keys
}
// stop kills the ssh-agent process.
func (a *sshAgent) stop() {
if a == nil || a.pid == "" {
return
}
killCmd := exec.Command("ssh-agent", "-k")
killCmd.Env = append(os.Environ(), "SSH_AGENT_PID="+a.pid, "SSH_AUTH_SOCK="+a.sock)
if err := killCmd.Run(); err != nil {
log.Printf("Warning: failed to stop ssh-agent (PID %s): %v", a.pid, err)
} else {
log.Printf("SSH agent stopped (PID: %s)", a.pid)
}
}
// defaultGalaxyFiles lists common Galaxy requirements filenames to search for
// when no explicit galaxy-file is provided.
var defaultGalaxyFiles = []string{
"requirements.yml",
"requirements.yaml",
}
// detectGalaxyFile returns the first existing file from defaultGalaxyFiles,
// or an empty string if none are found. dir specifies the directory to search in.
func detectGalaxyFile(dir string) string {
for _, name := range defaultGalaxyFiles {
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
log.Printf("Auto-detected Galaxy requirements file: %s", name)
return name
}
}
return ""
}
// createVaultPasswordFile writes the vault password to a secure temporary file
// and returns the file path. The caller is responsible for removing the file.
func createVaultPasswordFile(password string) (string, error) {
f, err := os.CreateTemp("", "vault-pass-")
if err != nil {
return "", fmt.Errorf("failed to create vault password file: %w", err)
}
path := f.Name()
if _, err := f.WriteString(password + "\n"); err != nil {
_ = f.Close()
_ = os.Remove(path)
return "", fmt.Errorf("failed to write vault password file: %w", err)
}
if err := f.Close(); err != nil {
_ = os.Remove(path)
return "", fmt.Errorf("failed to close vault password file: %w", err)
}
if err := os.Chmod(path, 0600); err != nil {
_ = os.Remove(path)
return "", fmt.Errorf("failed to set vault password file permissions: %w", err)
}
return path, nil
}
// execWithRetry runs fn up to (1 + retries) times with a delay between attempts.
// It returns nil on the first successful call, or the last error if all attempts fail.
func execWithRetry(ctx context.Context, retries int, delay time.Duration, fn func(ctx context.Context) error) error {
if retries < 0 {
retries = 0
}
var err error
for attempt := 0; attempt <= retries; attempt++ {
if attempt > 0 {
log.Printf("Retry %d/%d after %v delay...", attempt, retries, delay)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
}
err = fn(ctx)
if err == nil {
return nil
}
log.Printf("Attempt %d failed: %v", attempt+1, err)
}
return err
}
// runAnsibleLint runs ansible-lint on the given playbooks. It returns an error
// if ansible-lint is not installed or if linting fails.
func runAnsibleLint(ctx context.Context, playbooks []string) error {
if _, err := exec.LookPath("ansible-lint"); err != nil {
return fmt.Errorf("ansible-lint is not installed: %w", err)
}
cmd := exec.CommandContext(ctx, "ansible-lint", playbooks...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Printf("Running ansible-lint on %d playbook(s)...", len(playbooks))
if err := cmd.Run(); err != nil {
return fmt.Errorf("ansible-lint failed: %w", err)
}
log.Printf("ansible-lint passed")
return nil
}
// run is the main action for executing the playbooks.
// numericBound describes the accepted range for an integer action input.
// min/max are inclusive. warnAbove (when > 0) logs a warning for values that
// are technically valid but almost certainly a misconfiguration.
type numericBound struct {
flag string
min int
max int
warnAbove int
}
// numericBounds lists the validation rules for every integer input. Timeouts
// must be at least 1 (a zero execution-timeout would cancel the context
// immediately); counters and delays must be non-negative.
// For the optional ansible timeouts a value of 0 means "unset — use ansible's
// own default", so their minimum is 0. execution-timeout drives the action's
// own context and must be at least 1 (its default is 30); forks defaults to 5.
var numericBounds = []numericBound{
{flag: "execution-timeout", min: 1, max: 1440, warnAbove: 360}, // minutes (<= 24h)
{flag: "forks", min: 1, max: 1000, warnAbove: 100}, // parallelism (default 5)
{flag: "timeout", min: 0, max: 3600, warnAbove: 600}, // connection seconds (0 = ansible default)
{flag: "galaxy-timeout", min: 0, max: 3600, warnAbove: 600}, // seconds (0 = ansible default)
{flag: "fact-caching-timeout", min: 0, max: 31536000}, // seconds (0 = no expiry)
{flag: "gather-timeout", min: 0, max: 3600, warnAbove: 600}, // seconds (0 = ansible default)
{flag: "poll-interval", min: 0, max: 3600}, // seconds (0 = ansible default)
{flag: "retries", min: 0, max: 100, warnAbove: 20}, // attempts (0 = no retries)
{flag: "retry-delay", min: 0, max: 3600, warnAbove: 600}, // seconds
{flag: "verbose", min: 0, max: 4}, // -v .. -vvvv
{flag: "max-fail-percentage", min: 0, max: 100}, // percent
{flag: "galaxy-required-valid-signature-count", min: 0, max: 100}, // GPG signatures (0 = unset)
}
// validateNumericInputs enforces numericBounds for every integer flag in the
// table, returning an error for out-of-range values and logging a warning for
// suspiciously large but valid ones. Every entry is checked unconditionally;
// each flag's default sits within its own bound (e.g. retries defaults to 0 and
// has min 0), so unset flags pass without a special skip.
func validateNumericInputs(c *cli.Command) error {
for _, b := range numericBounds {
v := c.Int(b.flag)
if v < b.min || v > b.max {
return fmt.Errorf("invalid value for --%s: %d (must be between %d and %d)", b.flag, v, b.min, b.max)
}
if b.warnAbove > 0 && v > b.warnAbove {
log.Printf("WARNING: --%s is set to %d, which is unusually high (> %d) — double-check this is intended", b.flag, v, b.warnAbove)
}
}
return nil
}
func run(ctx context.Context, c *cli.Command) (execErr error) {
defer func() { writeActionOutputs(execErr) }()
// Normalize slice flags once to support both comma-separated and multiline inputs.
inventories := normalizeSlice(c.StringSlice("inventory"))
playbooks := normalizeSlice(c.StringSlice("playbook"))
extraVars := normalizeSlice(c.StringSlice("extra-vars"))
modulePath := normalizeSlice(c.StringSlice("module-path"))
// Auto-detect Galaxy file if not explicitly provided.
galaxyFile := c.String("galaxy-file")
if galaxyFile == "" {
galaxyFile = detectGalaxyFile(".")
}
// Validate parameters using the already-normalized slices.
if err := validateParameters(inventories, playbooks, galaxyFile); err != nil {
return err
}
// Validate numeric inputs (bounds, non-negative, sane maxima).
if err := validateNumericInputs(c); err != nil {
return err
}
// Run ansible-lint if requested.
if c.Bool("lint") {
if err := runAnsibleLint(ctx, playbooks); err != nil {
return err
}
}
// Set execution timeout based on flag. validateNumericInputs guarantees a
// minimum of 1 minute, so the context can never be created already-expired.
timeoutDuration := time.Duration(c.Int("execution-timeout")) * time.Minute
log.Printf("Setting execution timeout to %d minute(s)", c.Int("execution-timeout"))
// Create context with timeout.
ctx, cancel := context.WithTimeout(ctx, timeoutDuration)
defer cancel()