aboutsummaryrefslogtreecommitdiffstats
path: root/setup-env.sh
blob: 6659d39b151f8495965eeab39679c61d84d8e62c (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
#!/bin/sh
#
# DESCRIPTION:
#   Sets up a `.env` file that may be sourced via `source .env` to populate the
#   credentials to authenticate with the Backblaze B2 backend state bucket. This
#   is setup by retrieving the credentials from 1Password.
#
# PREREQUISITES:
# - `op` (1password CLI)
# - `jq`
#
# The `op` CLI must already be authenticated via `op signin`.
#
# USAGE:
#   ./bootstrap-state-bucket.sh
#   # Next, manually: Setup a "Backblaze B2 Master Key" key entry in 1Password
#   # before you run setup-env.sh. That is needed if you want to apply the
#   # b2-backup/ workspace.
#   ./setup-env.sh
#   source .env
set -o errexit
set -o nounset

OP_TF_STATE_ITEM="Backblaze B2 Terraform State Key"
OP_MASTER_KEY_ITEM="Backblaze B2 Master Key"

main() {
  TF_STATE_KEY_ID=$(get_op_label_value "$OP_TF_STATE_ITEM" "key_id")
  TF_STATE_KEY_VALUE=$(get_op_label_value "$OP_TF_STATE_ITEM" "key_value")
  # NOTE: Terraform uses the S3 compatible B2 API, so we need the Backblaze
  # credentials setup with 'AWS' environment variables.
  printf \
    "export AWS_ACCESS_KEY_ID=%s\nexport AWS_SECRET_ACCESS_KEY=%s\n" \
    "$TF_STATE_KEY_ID" \
    "$TF_STATE_KEY_VALUE" \
    >>.env

  OP_MASTER_KEY_ID=$(get_op_label_value "$OP_MASTER_KEY_ITEM" "key_id")
  OP_MASTER_KEY_VALUE=$(get_op_label_value "$OP_MASTER_KEY_ITEM" "key_value")
  # However, when communicating with B2 directly e.g. applying the b2-backup/
  # workspace, we need the B2 specific environment variables.
  printf "export B2_APPLICATION_KEY_ID=%s\nexport B2_APPLICATION_KEY=%s\n" "$OP_MASTER_KEY_ID" "$OP_MASTER_KEY_VALUE" >>.env
}

get_op_label_value() {
  _item="$1"
  _label="$2"
  op item get "$_item" --format json | jq --raw-output ".fields[] | select(.label == \"$_label\") | .value"
}

main