summaryrefslogtreecommitdiff
path: root/environment.sh
blob: 38a383401e72825fa79ce58e49b85186b0dce215 (plain) (blame)
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
##
## must be sourced in your interactive shell or by scripts before using vault files
##

print_error() {
  echo "\033[1;31mERROR:\033[1;0m $1"
}

vault_environment__get() {
  echo "${ANSIBLE_VAULT_IDENTITY_LIST}" | tr ',' '\n' | awk -F '@' '{ print($1) }' | sed '/^$/d'
}

vault_environment__set() {
  unset ANSIBLE_VAULT_IDENTITY_LIST
  for e in "$@"; do
    vault_environment__activate $e
  done
}

vault_environment__activate() {
  if [ -z "$1" ]; then
    print_error "please specify an environment"
    return
  fi

  if [ ! -f "gpg/get-vault-pass-$1" ]; then
    print_error "failed to activate environment: '$1' .. could not find password file 'gpg/get-vault-pass-$1'"
    return
  fi

  for e in $(vault_environment__get); do
    if [ "$1" = "$e" ]; then
      return
    fi
  done

  if [ -z "${ANSIBLE_VAULT_IDENTITY_LIST}" ]; then
    export ANSIBLE_VAULT_IDENTITY_LIST="$1@gpg/get-vault-pass-$1"
  else
    export ANSIBLE_VAULT_IDENTITY_LIST="${ANSIBLE_VAULT_IDENTITY_LIST},$1@gpg/get-vault-pass-$1"
  fi
}

vault_environment__deactivate() {
  local new_list

  if [ -z "$1" ]; then
    print_error "please specify an environment"
    return
  fi

  new_list=""
  for e in $(vault_environment__get); do
    if [ "$1" != "$e" ]; then
      if [ -z "$new_list" ]; then
        new_list="$e@gpg/get-vault-pass-$e"
      else
        new_list="$new_list,$e@gpg/get-vault-pass-$e"
      fi
    fi
  done

  if [ -z "$new_list" ]; then
    unset ANSIBLE_VAULT_IDENTITY_LIST
  else
    export ANSIBLE_VAULT_IDENTITY_LIST="$new_list"
  fi
}

op="$1"
if [ -n "$op" ]; then
  shift
fi

case $op in
  activate|deactivate|set|get)
    "vault_environment__$op" "$@"
    ;;
  *)
    print_error "unknown operation: '$op'"
    ;;
esac