Flux install of compute cluster
[icn.git] / deploy / site / common.sh
1 #!/usr/bin/env bash
2 set -eu -o pipefail
3
4 function _gpg_key_fp {
5     gpg --with-colons --list-secret-keys $1 | awk -F: '/fpr/ {print $10;exit}'
6 }
7
8 function create_gpg_key {
9     local -r key_name=$1
10
11     # Create an rsa4096 key that does not expire
12     gpg --batch --full-generate-key <<EOF
13 %no-protection
14 Key-Type: 1
15 Key-Length: 4096
16 Subkey-Type: 1
17 Subkey-Length: 4096
18 Expire-Date: 0
19 Name-Real: ${key_name}
20 EOF
21 }
22
23 function export_gpg_private_key {
24     gpg --export-secret-keys --armor "$(_gpg_key_fp $1)"
25 }
26
27 function sops_encrypt_site {
28     local -r site_yaml=$1
29     local -r key_name=$2
30
31     local -r site_dir=$(dirname ${site_yaml})
32     local -r key_fp=$(_gpg_key_fp ${key_name})
33
34     # Commit the public key to the repository so that team members who
35     # clone the repo can encrypt new files
36     echo "Creating ${site_dir}/sops.pub.asc with public key used to encrypt secrets"
37     gpg --export --armor "${key_fp}" >${site_dir}/sops.pub.asc
38
39     # Add .sops.yaml so users won't have to worry about specifying the
40     # proper key for the target cluster or namespace
41     echo "Creating ${site_dir}/.sops.yaml SOPS configuration file"
42     cat <<EOF > ${site_dir}/.sops.yaml
43 creation_rules:
44   - path_regex: .*.yaml
45     encrypted_regex: ^(bmcPassword|hashedPassword)$
46     pgp: ${key_fp}
47 EOF
48
49     sops --encrypt --in-place --config=${site_dir}/.sops.yaml ${site_yaml}
50 }
51
52 function sops_decrypt_site {
53     local -r site_yaml=$1
54
55     local -r site_dir=$(dirname ${site_yaml})
56     sops --decrypt --in-place --config=${site_dir}/.sops.yaml ${site_yaml}
57 }
58
59 function flux_create_site {
60     local -r url=$1
61     local -r branch=$2
62     local -r path=$3
63     local -r key_name=$4
64
65     local -r source_name="$(basename ${url})-${branch}"
66     local -r kustomization_name="${source_name}-site-$(basename ${path})"
67     local -r key_fp=$(gpg --with-colons --list-secret-keys ${key_name} | awk -F: '/fpr/ {print $10;exit}')
68     local -r secret_name="${key_name}-sops-gpg"
69
70     flux create source git ${source_name} --url=${url} --branch=${branch}
71     gpg --export-secret-keys --armor "$(_gpg_key_fp ${key_name})" |
72         kubectl -n flux-system create secret generic ${secret_name} --from-file=sops.asc=/dev/stdin --dry-run=client -o yaml |
73         kubectl apply -f -
74     flux create kustomization ${kustomization_name} --path=${path} --source=GitRepository/${source_name} --prune=true \
75          --decryption-provider=sops --decryption-secret=${secret_name}
76 }