-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathansible-manager.sh
More file actions
1294 lines (1100 loc) · 38.1 KB
/
ansible-manager.sh
File metadata and controls
1294 lines (1100 loc) · 38.1 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
#!/bin/bash
#
# ansible-manager - Because typing ansible-vault commands gets old fast
#
# Author: Dxsk
# License: MIT
#
set -euo pipefail
IFS=$'\n\t'
SCRIPT_NAME=""
SCRIPT_NAME=$(basename "$0")
readonly SCRIPT_NAME
readonly SCRIPT_VERSION="2.0.0"
readonly GITHUB_REPO="Dxsk/ansible-manager.sh" # Format: owner/repo
readonly E_SUCCESS=0
readonly E_ERROR=1
readonly E_MISSING_DEPS=2
readonly E_INVALID_ARGS=3
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly NC='\033[0m'
# Defaults - override these in .ansible-manager.conf
VAULT_FILE="group_vars/all/vault.yml"
VAULT_DIR="$HOME/.ans_vaults"
INVENTORY_FILE="inventory.yml"
PLAYBOOKS_DIR="."
ROLES_DIR="roles"
LOG_FILE=""
VERBOSITY=0
readonly REQUIRED_COMMANDS=(
"ansible"
"ansible-vault"
"ansible-playbook"
"openssl"
"sha256sum"
)
declare -a TEMP_FILES=()
# Used by cleanup trap to re-encrypt if we get interrupted
SECURE_RUN_WAS_ENCRYPTED=false
SECURE_RUN_VAULT_FILE=""
###############################################################################
# Logging
###############################################################################
log_info() {
echo -e "${GREEN}[INFO]${NC} $*" >&2
[[ -n "$LOG_FILE" ]] && echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') $*" >> "$LOG_FILE"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $*" >&2
[[ -n "$LOG_FILE" ]] && echo "[WARN] $(date '+%Y-%m-%d %H:%M:%S') $*" >> "$LOG_FILE"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $*" >&2
[[ -n "$LOG_FILE" ]] && echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') $*" >> "$LOG_FILE"
}
log_debug() {
if (( VERBOSITY >= 1 )); then
echo -e "${BLUE}[DEBUG]${NC} $*" >&2
[[ -n "$LOG_FILE" ]] && echo "[DEBUG] $(date '+%Y-%m-%d %H:%M:%S') $*" >> "$LOG_FILE"
fi
}
log_trace() {
if (( VERBOSITY >= 2 )); then
echo -e "${CYAN}[TRACE]${NC} $*" >&2
[[ -n "$LOG_FILE" ]] && echo "[TRACE] $(date '+%Y-%m-%d %H:%M:%S') $*" >> "$LOG_FILE"
fi
}
die() {
log_error "$*"
exit ${E_ERROR}
}
###############################################################################
# Utilities
###############################################################################
# Safety net - if something goes wrong, we don't leave the vault decrypted
cleanup() {
local exit_code=$?
if [[ "$SECURE_RUN_WAS_ENCRYPTED" == true ]] && [[ -n "$SECURE_RUN_VAULT_FILE" ]]; then
if [[ -f "$SECURE_RUN_VAULT_FILE" ]] && ! grep -q "\$ANSIBLE_VAULT" "$SECURE_RUN_VAULT_FILE" 2>/dev/null; then
log_warn "Secure-run interrupted, re-encrypting vault..."
ansible-vault encrypt "$SECURE_RUN_VAULT_FILE" --vault-password-file "$(get_vault_pass_file)" 2>/dev/null || true
fi
fi
if (( ${#TEMP_FILES[@]} > 0 )); then
log_debug "Cleaning up ${#TEMP_FILES[@]} temporary files..."
for tmp_file in "${TEMP_FILES[@]}"; do
if [[ -f "$tmp_file" ]]; then
rm -f "$tmp_file" 2>/dev/null || true
fi
done
fi
exit $exit_code
}
load_config() {
local config_files=(
".ansible-manager.conf"
"$HOME/.ansible-manager.conf"
"/etc/ansible-manager.conf"
)
for config_file in "${config_files[@]}"; do
if [[ -f "$config_file" ]]; then
log_debug "Loading configuration from $config_file"
# shellcheck source=/dev/null
source "$config_file"
return 0
fi
done
log_debug "No configuration file found, using defaults"
return 0
}
check_dependencies() {
local missing_deps=()
for cmd in "${REQUIRED_COMMANDS[@]}"; do
command -v "$cmd" >/dev/null 2>&1 || missing_deps+=("$cmd")
done
if (( ${#missing_deps[@]} > 0 )); then
log_error "Missing required dependencies: ${missing_deps[*]}"
exit ${E_MISSING_DEPS}
fi
}
check_optional_command() {
local cmd="$1"
command -v "$cmd" >/dev/null 2>&1 || die "Command '$cmd' is not installed. Please install it first."
}
init_vault_dir() {
if [[ ! -d "$VAULT_DIR" ]]; then
log_info "Creating vault directory at $VAULT_DIR..."
mkdir -p "$VAULT_DIR"
chmod 700 "$VAULT_DIR"
log_info "Vault directory created with secure permissions"
else
chmod 700 "$VAULT_DIR" 2>/dev/null || log_warn "Could not update permissions on existing vault directory"
fi
}
# Each project gets its own password file based on directory hash
generate_vault_id() {
pwd | sha256sum | cut -c1-30
}
get_vault_pass_file() {
echo "$VAULT_DIR/$(generate_vault_id)"
}
generate_vault_pass() {
local vault_pass_file
vault_pass_file=$(get_vault_pass_file)
log_info "Generating new vault password..."
if ! openssl rand -base64 32 > "$vault_pass_file"; then
die "Failed to generate vault password"
fi
chmod 600 "$vault_pass_file" || die "Failed to set permissions on vault password file"
log_info "New vault password generated at $vault_pass_file"
}
check_vault_file() {
local vault="$1"
[[ -f "$vault" ]] || die "Vault file $vault does not exist"
}
check_vault_pass() {
local vault_pass_file
vault_pass_file=$(get_vault_pass_file)
if [[ ! -f "$vault_pass_file" ]]; then
log_warn "Password file $vault_pass_file does not exist, generating it..."
generate_vault_pass
fi
}
check_inventory_file() {
[[ -f "$INVENTORY_FILE" ]] || die "Inventory file $INVENTORY_FILE does not exist"
}
is_vault_encrypted() {
grep -q "\$ANSIBLE_VAULT" "$1"
}
create_temp_file() {
local tmp_file
tmp_file=$(mktemp)
TEMP_FILES+=("$tmp_file")
echo "$tmp_file"
}
parse_ansible_options() {
local -n args_ref=$1
shift
while [[ $# -gt 0 ]]; do
case "$1" in
--check)
args_ref+=("--check")
shift
;;
--diff)
args_ref+=("--diff")
shift
;;
--limit)
[[ -z "${2-}" ]] && die "Error: --limit requires a pattern"
args_ref+=("--limit" "$2")
shift 2
;;
--tags)
[[ -z "${2-}" ]] && die "Error: --tags requires tag names"
args_ref+=("--tags" "$2")
shift 2
;;
--skip-tags)
[[ -z "${2-}" ]] && die "Error: --skip-tags requires tag names"
args_ref+=("--skip-tags" "$2")
shift 2
;;
-e|--extra-vars)
[[ -z "${2-}" ]] && die "Error: --extra-vars requires variables"
args_ref+=("--extra-vars" "$2")
shift 2
;;
--ask-become-pass|-K)
args_ref+=("--ask-become-pass")
shift
;;
--become|-b)
args_ref+=("--become")
shift
;;
--vault)
[[ -z "${2-}" ]] && die "Error: --vault requires a vault file path"
VAULT_FILE="$2"
shift 2
;;
-v) args_ref+=("-v"); shift ;;
-vv) args_ref+=("-vv"); shift ;;
-vvv) args_ref+=("-vvv"); shift ;;
-vvvv) args_ref+=("-vvvv"); shift ;;
*) die "Unknown option: $1" ;;
esac
done
}
show_help() {
cat <<EOF
${GREEN}Ansible Manager v${SCRIPT_VERSION}${NC}
Usage: $SCRIPT_NAME [command] [playbook/host] [options]
${YELLOW}Vault Commands:${NC}
encrypt Encrypt the vault file
decrypt Decrypt the vault file
edit Edit the vault file
view View vault content
rekey Change the vault password
status Show vault encryption status
encrypt-string Encrypt a string for inline use in playbooks
diff Compare two vault files (decrypted diff)
${YELLOW}Playbook Commands:${NC}
run Run a playbook (requires playbook name)
secure-run Run with automatic encryption/decryption handling
retry Re-run a playbook on previously failed hosts
syntax-check Check playbook syntax without executing
list List available playbooks
${YELLOW}Inventory Commands:${NC}
ping Test connectivity with all inventory machines
inventory Display parsed inventory (list or graph)
facts Gather facts from a host
ssh-check Verify SSH connectivity and configuration
${YELLOW}Project Commands:${NC}
init Initialize a new role, collection, or project
galaxy Install roles/collections from requirements.yml
lint Run ansible-lint on playbooks
${YELLOW}Utility Commands:${NC}
genpass Generate/regenerate vault password file
backup Backup the vault password file
completion Generate bash completion script
check-update Check for new versions on GitHub
help Show this help
version Show version information
${YELLOW}Common Options:${NC}
--check Run in check mode (dry-run)
--diff Show differences when files are changed
--limit Limit execution to specific hosts/groups
--tags Only run plays and tasks tagged with these values
--skip-tags Skip plays and tasks tagged with these values
-e, --extra-vars Set additional variables (key=value or @file.yml)
-K, --ask-become-pass Ask for privilege escalation password
-b, --become Run operations with become
--vault Specify vault file path (default: $VAULT_FILE)
-v/-vv/-vvv Increase verbosity level
${YELLOW}Configuration:${NC}
The script looks for configuration in these locations (first found wins):
1. .ansible-manager.conf (current directory)
2. ~/.ansible-manager.conf (home directory)
3. /etc/ansible-manager.conf (system-wide)
${YELLOW}Examples:${NC}
$SCRIPT_NAME run site.yml --limit webservers --tags deploy
$SCRIPT_NAME secure-run deploy.yml --check --diff
$SCRIPT_NAME retry site.yml
$SCRIPT_NAME ping --limit "web*"
$SCRIPT_NAME ssh-check webservers
$SCRIPT_NAME facts webserver01
$SCRIPT_NAME encrypt-string "secret" --name api_key
$SCRIPT_NAME diff group_vars/dev/vault.yml group_vars/prod/vault.yml
$SCRIPT_NAME init role my_new_role
$SCRIPT_NAME init project my_ansible_project
EOF
}
show_version() {
echo -e "${GREEN}Ansible Manager${NC} v${SCRIPT_VERSION}"
echo "Ansible version: $(ansible --version | head -1)"
}
# Compare semantic versions: returns 0 if $1 > $2, 1 otherwise
version_gt() {
local v1="${1#v}"
local v2="${2#v}"
# Simple comparison for x.y.z format
local i
local v1_parts v2_parts
IFS='.' read -ra v1_parts <<< "$v1"
IFS='.' read -ra v2_parts <<< "$v2"
for ((i=0; i<${#v1_parts[@]}; i++)); do
local n1="${v1_parts[i]:-0}"
local n2="${v2_parts[i]:-0}"
# Remove non-numeric suffixes for comparison
n1="${n1%%[!0-9]*}"
n2="${n2%%[!0-9]*}"
((n1 > n2)) && return 0
((n1 < n2)) && return 1
done
return 1
}
# shellcheck disable=SC2120 # Arguments are optional (silent mode)
check_update() {
local silent="${1:-false}"
local latest_version=""
local release_url=""
local api_url="https://api.github.com/repos/${GITHUB_REPO}/releases/latest"
local tags_url="https://api.github.com/repos/${GITHUB_REPO}/tags"
# Check if curl is available - silently skip if not
if ! command -v curl >/dev/null 2>&1; then
[[ "$silent" != "true" ]] && log_warn "curl is required for update checking"
return 0
fi
[[ "$silent" != "true" ]] && log_info "Checking for updates..."
# Try releases first (preferred) - short timeout to avoid blocking
local response
response=$(curl -sf --max-time 5 --connect-timeout 3 "$api_url" 2>/dev/null) && {
latest_version=$(echo "$response" | grep -oP '"tag_name":\s*"\K[^"]+' | head -1)
release_url=$(echo "$response" | grep -oP '"html_url":\s*"\K[^"]+' | head -1)
}
# Fallback to tags if no releases found
if [[ -z "$latest_version" ]]; then
response=$(curl -sf --max-time 5 --connect-timeout 3 "$tags_url" 2>/dev/null) && {
latest_version=$(echo "$response" | grep -oP '"name":\s*"\K[^"]+' | head -1)
release_url="https://github.com/${GITHUB_REPO}/releases/tag/${latest_version}"
}
fi
# Silently fail if we can't reach GitHub - don't block the user
if [[ -z "$latest_version" ]]; then
[[ "$silent" != "true" ]] && log_warn "Could not fetch version information from GitHub"
return 0
fi
# Normalize versions for comparison (strip 'v' prefix if present)
local current_clean="${SCRIPT_VERSION#v}"
local latest_clean="${latest_version#v}"
if [[ "$silent" == "true" ]]; then
# Silent mode: only show a short notice if update available
if version_gt "$latest_clean" "$current_clean"; then
echo -e "${YELLOW}[UPDATE]${NC} v${latest_version} available - run '$SCRIPT_NAME check-update' for details" >&2
fi
else
# Verbose mode: show full info
echo -e "${CYAN}Update Check:${NC}"
echo " Current version: v${current_clean}"
echo " Latest version: ${latest_version}"
if version_gt "$latest_clean" "$current_clean"; then
echo
echo -e " ${YELLOW}Update available!${NC}"
echo -e " ${GREEN}→${NC} Download: ${release_url}"
echo
echo -e " To update, run:"
echo -e " curl -fsSL https://raw.githubusercontent.com/${GITHUB_REPO}/main/ansible-manager.sh -o ansible-manager.sh"
else
echo
echo -e " ${GREEN}You are running the latest version${NC}"
fi
fi
return 0
}
###############################################################################
# Command handlers
###############################################################################
handle_encrypt() {
local vault="${1:-$VAULT_FILE}"
check_vault_file "$vault"
check_vault_pass
if is_vault_encrypted "$vault"; then
log_warn "Vault file $vault is already encrypted"
return 0
fi
log_info "Encrypting vault file $vault..."
ansible-vault encrypt "$vault" --vault-password-file "$(get_vault_pass_file)"
log_info "Vault encrypted successfully"
}
handle_decrypt() {
local vault="${1:-$VAULT_FILE}"
check_vault_file "$vault"
check_vault_pass
if ! is_vault_encrypted "$vault"; then
log_warn "Vault file $vault is not encrypted"
return 0
fi
log_info "Decrypting vault file $vault..."
ansible-vault decrypt "$vault" --vault-password-file "$(get_vault_pass_file)"
log_info "Vault decrypted successfully"
}
handle_edit() {
local vault="${1:-$VAULT_FILE}"
check_vault_file "$vault"
check_vault_pass
log_info "Editing vault file $vault..."
ansible-vault edit "$vault" --vault-password-file "$(get_vault_pass_file)"
}
handle_view() {
local vault="${1:-$VAULT_FILE}"
check_vault_file "$vault"
check_vault_pass
log_info "Viewing vault content of $vault..."
ansible-vault view "$vault" --vault-password-file "$(get_vault_pass_file)"
}
handle_rekey() {
local vault="${1:-$VAULT_FILE}"
check_vault_file "$vault"
check_vault_pass
is_vault_encrypted "$vault" || die "Vault file $vault is not encrypted. Encrypt it first."
local old_pass_file new_pass_file
old_pass_file=$(get_vault_pass_file)
new_pass_file=$(create_temp_file)
log_info "Generating new vault password..."
openssl rand -base64 32 > "$new_pass_file"
chmod 600 "$new_pass_file"
log_info "Rekeying vault file $vault..."
if ansible-vault rekey "$vault" \
--vault-password-file "$old_pass_file" \
--new-vault-password-file "$new_pass_file"; then
cp "$new_pass_file" "$old_pass_file"
chmod 600 "$old_pass_file"
log_info "Vault rekeyed successfully with new password"
else
die "Failed to rekey vault"
fi
}
handle_run() {
local playbook="$1"
shift
local ansible_args=()
parse_ansible_options ansible_args "$@"
check_vault_file "$VAULT_FILE"
check_vault_pass
check_inventory_file
[[ -f "$playbook" ]] || die "Playbook '$playbook' does not exist"
log_info "Running playbook $playbook..."
log_debug "Arguments: ${ansible_args[*]:-none}"
ansible-playbook -i "$INVENTORY_FILE" \
--vault-password-file "$(get_vault_pass_file)" \
"${ansible_args[@]}" \
"$playbook"
}
handle_secure_run() {
local playbook="$1"
shift
local ansible_args=()
local playbook_status
parse_ansible_options ansible_args "$@"
check_vault_file "$VAULT_FILE"
check_vault_pass
check_inventory_file
[[ -f "$playbook" ]] || die "Playbook '$playbook' does not exist"
SECURE_RUN_VAULT_FILE="$VAULT_FILE"
if is_vault_encrypted "$VAULT_FILE"; then
SECURE_RUN_WAS_ENCRYPTED=true
log_warn "Vault is encrypted, temporary decryption..."
ansible-vault decrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
fi
log_info "Running playbook $playbook..."
log_debug "Arguments: ${ansible_args[*]:-none}"
set +e
ansible-playbook -i "$INVENTORY_FILE" \
--vault-password-file "$(get_vault_pass_file)" \
"${ansible_args[@]}" \
"$playbook"
playbook_status=$?
set -e
if [[ "$SECURE_RUN_WAS_ENCRYPTED" == true ]]; then
log_warn "Re-encrypting vault..."
ansible-vault encrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
SECURE_RUN_WAS_ENCRYPTED=false
fi
return ${playbook_status}
}
handle_ping() {
local ansible_args=()
local was_encrypted=false
while [[ $# -gt 0 ]]; do
case "$1" in
--limit)
[[ -z "${2-}" ]] && die "Error: --limit requires a pattern"
ansible_args+=("--limit" "$2")
shift 2
;;
*)
die "Unknown option: $1"
;;
esac
done
check_vault_file "$VAULT_FILE"
check_vault_pass
check_inventory_file
if is_vault_encrypted "$VAULT_FILE"; then
was_encrypted=true
log_warn "Vault is encrypted, temporary decryption..."
ansible-vault decrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
fi
log_info "Testing connectivity with machines..."
set +e
ansible all -m ping -i "$INVENTORY_FILE" "${ansible_args[@]}"
local ping_status=$?
set -e
if [[ "$was_encrypted" == true ]]; then
log_warn "Re-encrypting vault..."
ansible-vault encrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
fi
return $ping_status
}
handle_status() {
local vault="${1:-$VAULT_FILE}"
if [[ ! -f "$vault" ]]; then
log_error "Vault file $vault does not exist"
return 1
fi
echo -e "${CYAN}Vault Status:${NC}"
echo " File: $vault"
if is_vault_encrypted "$vault"; then
echo -e " Status: ${GREEN}Encrypted${NC}"
else
echo -e " Status: ${YELLOW}Not encrypted${NC}"
fi
local vault_pass_file
vault_pass_file=$(get_vault_pass_file)
echo " Password file: $vault_pass_file"
if [[ -f "$vault_pass_file" ]]; then
echo -e " Password status: ${GREEN}Exists${NC}"
else
echo -e " Password status: ${YELLOW}Not found${NC}"
fi
}
handle_backup() {
local vault_pass_file backup_file
vault_pass_file=$(get_vault_pass_file)
backup_file="vault_pass_$(generate_vault_id).backup"
[[ -f "$vault_pass_file" ]] || die "No vault password file found to backup"
log_warn "WARNING: This will create a backup of your vault password in the current directory."
log_warn " Make sure to:"
log_warn " 1. Never commit this file to version control"
log_warn " 2. Delete it after use"
log_warn " 3. Store it securely if you need to keep it"
read -p "Do you want to continue? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log_info "Backup cancelled"
exit ${E_SUCCESS}
fi
log_info "Creating backup of vault password file..."
cp "$vault_pass_file" "$backup_file"
chmod 600 "$backup_file"
log_info "Backup created at: $backup_file"
log_warn "Remember to delete this file after use!"
}
handle_syntax_check() {
local playbook="$1"
check_vault_pass
check_inventory_file
[[ -f "$playbook" ]] || die "Playbook '$playbook' does not exist"
log_info "Checking syntax of $playbook..."
if ansible-playbook -i "$INVENTORY_FILE" \
--vault-password-file "$(get_vault_pass_file)" \
--syntax-check "$playbook"; then
log_info "Syntax check passed"
else
die "Syntax check failed"
fi
}
handle_list() {
local search_dir="${1:-$PLAYBOOKS_DIR}"
log_info "Available playbooks in $search_dir:"
echo
local count=0
while IFS= read -r -d '' playbook; do
local name
name=$(basename "$playbook")
[[ "$name" == _* ]] && continue
echo -e " ${GREEN}•${NC} $playbook"
((count++))
done < <(find "$search_dir" -maxdepth 2 -name "*.yml" -o -name "*.yaml" 2>/dev/null | grep -v "group_vars\|host_vars\|roles\|inventory\|requirements\|vault" | sort -z)
echo
log_info "Found $count playbook(s)"
}
handle_galaxy() {
local requirements_file="${1:-requirements.yml}"
local galaxy_args=()
check_optional_command "ansible-galaxy"
[[ -f "$requirements_file" ]] || die "Requirements file '$requirements_file' does not exist"
if grep -q "^roles:" "$requirements_file" || ! grep -q "^collections:" "$requirements_file"; then
log_info "Installing roles from $requirements_file..."
ansible-galaxy role install -r "$requirements_file" --roles-path "${ROLES_DIR}" "${galaxy_args[@]}"
fi
if grep -q "^collections:" "$requirements_file"; then
log_info "Installing collections from $requirements_file..."
ansible-galaxy collection install -r "$requirements_file" "${galaxy_args[@]}"
fi
log_info "Galaxy dependencies installed successfully"
}
handle_lint() {
local target="${1:-.}"
check_optional_command "ansible-lint"
log_info "Running ansible-lint on $target..."
ansible-lint "$target"
}
handle_inventory() {
local format="${1:-list}"
check_optional_command "ansible-inventory"
check_inventory_file
check_vault_pass
log_info "Displaying inventory ($format)..."
case "$format" in
list)
ansible-inventory -i "$INVENTORY_FILE" \
--vault-password-file "$(get_vault_pass_file)" \
--list
;;
graph)
ansible-inventory -i "$INVENTORY_FILE" \
--vault-password-file "$(get_vault_pass_file)" \
--graph
;;
*)
die "Unknown inventory format: $format (use 'list' or 'graph')"
;;
esac
}
handle_facts() {
local host="$1"
local was_encrypted=false
[[ -z "$host" ]] && die "Host name required. Usage: $SCRIPT_NAME facts <hostname>"
check_vault_file "$VAULT_FILE"
check_vault_pass
check_inventory_file
if is_vault_encrypted "$VAULT_FILE"; then
was_encrypted=true
log_warn "Vault is encrypted, temporary decryption..."
ansible-vault decrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
fi
log_info "Gathering facts from $host..."
set +e
ansible "$host" -m setup -i "$INVENTORY_FILE"
local facts_status=$?
set -e
if [[ "$was_encrypted" == true ]]; then
log_warn "Re-encrypting vault..."
ansible-vault encrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
fi
return $facts_status
}
handle_encrypt_string() {
local string="$1"
local var_name="${2:-}"
[[ -z "$string" ]] && die "String to encrypt is required. Usage: $SCRIPT_NAME encrypt-string <string> [--name <var_name>]"
check_vault_pass
log_info "Encrypting string..."
if [[ -n "$var_name" ]]; then
ansible-vault encrypt_string "$string" --vault-password-file "$(get_vault_pass_file)" --name "$var_name"
else
ansible-vault encrypt_string "$string" --vault-password-file "$(get_vault_pass_file)"
fi
}
handle_retry() {
local playbook="$1"
shift
local ansible_args=()
local retry_file
parse_ansible_options ansible_args "$@"
[[ -f "$playbook" ]] || die "Playbook '$playbook' does not exist"
# Find the retry file
retry_file="${playbook%.yml}.retry"
[[ -f "$retry_file" ]] || retry_file="${playbook%.yaml}.retry"
[[ -f "$retry_file" ]] || die "No retry file found for $playbook (looked for ${playbook%.yml}.retry)"
check_vault_file "$VAULT_FILE"
check_vault_pass
check_inventory_file
local failed_hosts
failed_hosts=$(cat "$retry_file")
log_info "Retrying on failed hosts: $failed_hosts"
ansible_args+=("--limit" "@$retry_file")
# Clean up retry file on success
if ansible-playbook -i "$INVENTORY_FILE" \
--vault-password-file "$(get_vault_pass_file)" \
"${ansible_args[@]}" \
"$playbook"; then
rm -f "$retry_file"
log_info "Retry successful, removed $retry_file"
fi
}
handle_init() {
local init_type="${1:-}"
local name="${2:-}"
check_optional_command "ansible-galaxy"
case "$init_type" in
role)
[[ -z "$name" ]] && die "Role name required. Usage: $SCRIPT_NAME init role <name>"
log_info "Initializing new role: $name"
ansible-galaxy role init "$name" --init-path "${ROLES_DIR}"
log_info "Role created at ${ROLES_DIR}/$name"
;;
collection)
[[ -z "$name" ]] && die "Collection name required (format: namespace.name). Usage: $SCRIPT_NAME init collection <namespace.name>"
log_info "Initializing new collection: $name"
ansible-galaxy collection init "$name"
log_info "Collection created: $name"
;;
project)
[[ -z "$name" ]] && name="."
log_info "Initializing new Ansible project structure in $name"
mkdir -p "$name"/{group_vars/all,host_vars,roles,playbooks,files,templates,inventory}
# Create basic files
[[ -f "$name/inventory/hosts.yml" ]] || cat > "$name/inventory/hosts.yml" <<'INVENTORY'
---
all:
hosts:
localhost:
ansible_connection: local
children:
webservers:
hosts:
dbservers:
hosts:
INVENTORY
[[ -f "$name/ansible.cfg" ]] || cat > "$name/ansible.cfg" <<'ANSIBLECFG'
[defaults]
inventory = inventory/hosts.yml
roles_path = roles
host_key_checking = False
retry_files_enabled = True
[privilege_escalation]
become = False
become_method = sudo
become_ask_pass = False
ANSIBLECFG
[[ -f "$name/group_vars/all/vault.yml" ]] || echo "---" > "$name/group_vars/all/vault.yml"
[[ -f "$name/playbooks/site.yml" ]] || cat > "$name/playbooks/site.yml" <<'SITEYML'
---
- name: Main playbook
hosts: all
gather_facts: true
roles: []
SITEYML
[[ -f "$name/requirements.yml" ]] || cat > "$name/requirements.yml" <<'REQYML'
---
roles: []
collections: []
REQYML
log_info "Project structure created successfully"
echo -e "\n${CYAN}Created structure:${NC}"
find "$name" -type f | head -20 | sed 's/^/ /'
;;
*)
echo -e "${YELLOW}Usage:${NC} $SCRIPT_NAME init <type> <name>"
echo
echo -e "${YELLOW}Types:${NC}"
echo " role Create a new role with ansible-galaxy"
echo " collection Create a new collection with ansible-galaxy"
echo " project Create a complete project structure"
echo
echo -e "${YELLOW}Examples:${NC}"
echo " $SCRIPT_NAME init role my_role"
echo " $SCRIPT_NAME init collection myns.mycollection"
echo " $SCRIPT_NAME init project my_ansible_project"
;;
esac
}
handle_diff() {
local vault1="$1"
local vault2="$2"
[[ -z "$vault1" || -z "$vault2" ]] && die "Two vault files required. Usage: $SCRIPT_NAME diff <vault1> <vault2>"
[[ -f "$vault1" ]] || die "Vault file $vault1 does not exist"
[[ -f "$vault2" ]] || die "Vault file $vault2 does not exist"
check_vault_pass
local tmp1 tmp2
tmp1=$(create_temp_file)
tmp2=$(create_temp_file)
log_info "Decrypting vaults for comparison..."
# Decrypt both vaults to temp files
if is_vault_encrypted "$vault1"; then
ansible-vault view "$vault1" --vault-password-file "$(get_vault_pass_file)" > "$tmp1"
else
cp "$vault1" "$tmp1"
fi
if is_vault_encrypted "$vault2"; then
ansible-vault view "$vault2" --vault-password-file "$(get_vault_pass_file)" > "$tmp2"
else
cp "$vault2" "$tmp2"
fi
log_info "Comparing $vault1 vs $vault2:"
echo
# Use diff with colors if available
if command -v colordiff >/dev/null 2>&1; then
colordiff -u "$tmp1" "$tmp2" --label "$vault1" --label "$vault2" || true
else
diff -u "$tmp1" "$tmp2" --label "$vault1" --label "$vault2" || true
fi
}
handle_ssh_check() {
local target="${1:-all}"
local was_encrypted=false
check_vault_file "$VAULT_FILE"
check_vault_pass
check_inventory_file
if is_vault_encrypted "$VAULT_FILE"; then
was_encrypted=true
log_warn "Vault is encrypted, temporary decryption..."
ansible-vault decrypt "$VAULT_FILE" --vault-password-file "$(get_vault_pass_file)"
fi
echo -e "${CYAN}SSH Configuration Check${NC}"
echo
log_info "Checking SSH connectivity and configuration for: $target"
echo
# Test raw SSH connection (bypasses Python)