Extract common code from site scripts
[icn.git] / deploy / site / common.sh
1 #!/usr/bin/env bash
2 set -eu -o pipefail
3
4 FLUX_SOPS_KEY_NAME=${FLUX_SOPS_KEY_NAME:-"icn-site-vm"}
5 FLUX_SOPS_PRIVATE_KEY="$(readlink -f $(dirname ${BASH_SOURCE[0]}))/secrets/sops.asc"
6 SITE_NAMESPACE="${SITE_NAMESPACE:-metal3}"
7
8 function _gpg_key_fp {
9     gpg --with-colons --list-secret-keys $1 | awk -F: '/fpr/ {print $10;exit}'
10 }
11
12 function sops_encrypt {
13     local -r yaml=$1
14     local -r yaml_dir=$(dirname ${yaml})
15
16     local -r key_name=$2
17     local -r key_fp=$(_gpg_key_fp ${key_name})
18
19     local site_dir=${yaml_dir}
20     if [[ $# -eq 3 ]]; then
21         site_dir=$3
22     fi
23
24     # Commit the public key to the repository so that team members who
25     # clone the repo can encrypt new files
26     echo "Creating ${yaml_dir}/sops.pub.asc with public key used to encrypt secrets"
27     gpg --export --armor "${key_fp}" >${site_dir}/sops.pub.asc
28
29     # Add .sops.yaml so users won't have to worry about specifying the
30     # proper key for the target cluster or namespace
31     echo "Creating ${site_dir}/.sops.yaml SOPS configuration file"
32     encrypted_regex="(bmcPassword|ca-key.pem|decryptionSecret|hashedPassword|emcoPassword|rootPassword)"
33     cat <<EOF > ${site_dir}/.sops.yaml
34 creation_rules:
35   - path_regex: .*.yaml
36     encrypted_regex: ^${encrypted_regex}$
37     pgp: ${key_fp}
38 EOF
39
40     if [[ $(grep -c $(echo ${encrypted_regex} | sed -e 's/(/\\(/g' -e 's/|/\\|/g' -e 's/)/\\)/') ${yaml}) -ne 0 ]]; then
41         sops --encrypt --in-place --config=${site_dir}/.sops.yaml ${yaml}
42     fi
43 }
44
45 function sops_decrypt {
46     local -r yaml=$1
47     local -r yaml_dir=$(dirname ${yaml})
48     local site_dir=${yaml_dir}
49     if [[ $# -eq 2 ]]; then
50         site_dir=$2
51     fi
52
53     if [[ $(grep -c "^sops:" ${yaml}) -ne 0 ]]; then
54         sops --decrypt --in-place --config=${site_dir}/.sops.yaml ${yaml}
55     fi
56 }
57
58 function _site_source_name {
59     local -r url=$1
60     local -r branch=$2
61     echo $(basename ${url})-${branch}
62 }
63
64 function _site_kustomization_name {
65     local -r url=$1
66     local -r branch=$2
67     local -r path=$3
68     echo $(_site_source_name ${url} ${branch})-site-$(basename ${path})
69 }
70
71 function flux_create_site {
72     local -r url=$1
73     local -r branch=$2
74     local -r path=$3
75     local -r key_name=$4
76
77     local -r source_name=$(_site_source_name ${url} ${branch})
78     local -r kustomization_name=$(_site_kustomization_name ${url} ${branch} ${path})
79     local -r key_fp=$(gpg --with-colons --list-secret-keys ${key_name} | awk -F: '/fpr/ {print $10;exit}')
80     local -r secret_name="${key_name}-sops-gpg"
81
82     flux create source git ${source_name} --url=${url} --branch=${branch}
83     gpg --export-secret-keys --armor "$(_gpg_key_fp ${key_name})" |
84         kubectl -n flux-system create secret generic ${secret_name} --from-file=sops.asc=/dev/stdin --dry-run=client -o yaml |
85         kubectl apply -f -
86     kubectl create namespace ${SITE_NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
87     flux create kustomization ${kustomization_name} --target-namespace=${SITE_NAMESPACE} --path=${path} --source=GitRepository/${source_name} --prune=true \
88          --decryption-provider=sops --decryption-secret=${secret_name}
89 }
90
91 function site_deploy {
92     flux_create_site ${SITE_REPO} ${SITE_BRANCH} ${SITE_PATH} ${FLUX_SOPS_KEY_NAME}
93 }
94
95 function site_clean {
96     kubectl -n flux-system delete kustomization $(_site_kustomization_name ${SITE_REPO} ${SITE_BRANCH} ${SITE_PATH})
97 }
98
99 function _is_cluster_ready {
100     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
101         name=$(awk '/clusterName:/ {print $2}' ${yaml})
102         if [[ ! -z ${name} ]]; then
103             if [[ $(kubectl -n ${SITE_NAMESPACE} get cluster ${name} -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}') != "True" ]]; then
104                 return 1
105             fi
106         fi
107     done
108 }
109
110 function _is_control_plane_ready {
111     # Checking the Cluster resource status is not sufficient, it
112     # reports the control plane as ready before the nodes forming the
113     # control plane are ready
114     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
115         name=$(awk '/clusterName:/ {print $2}' ${yaml})
116         if [[ ! -z ${name} ]]; then
117             local replicas=$(kubectl -n ${SITE_NAMESPACE} get kubeadmcontrolplane ${name} -o jsonpath='{.spec.replicas}')
118             if [[ $(kubectl --kubeconfig=${BUILDDIR}/${name}-admin.conf get nodes -l node-role.kubernetes.io/control-plane -o jsonpath='{range .items[*]}{.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}' | grep -c True) != ${replicas} ]]; then
119                 return 1
120             fi
121         fi
122     done
123 }
124
125 function site_wait_for_all_ready {
126     WAIT_FOR_INTERVAL=60s
127     WAIT_FOR_TRIES=30
128     wait_for _is_cluster_ready
129     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
130         name=$(awk '/clusterName:/ {print $2}' ${yaml})
131         clusterctl -n ${SITE_NAMESPACE} get kubeconfig ${name} >${BUILDDIR}/${name}-admin.conf
132         chmod 600 ${BUILDDIR}/${name}-admin.conf
133     done
134     wait_for _is_control_plane_ready
135 }
136
137 function site_insert_control_plane_network_identity_into_ssh_config {
138     # This enables logging into the control plane machines from this
139     # machine without specifying the identify file on the command line
140
141     if [[ ! $(which ipcalc) ]]; then
142         apt-get install -y ipcalc
143     fi
144
145     # Create ssh config if it doesn't exist
146     mkdir -p ${HOME}/.ssh && chmod 700 ${HOME}/.ssh
147     touch ${HOME}/.ssh/config
148     chmod 600 ${HOME}/.ssh/config
149     # Add the entry for the control plane network, host value in ssh
150     # config is a wildcard
151     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
152         name=$(awk '/name:/ {NAME=$2} /chart: deploy\/cluster/ {print NAME; exit}' ${yaml})
153         if [[ ! -z ${name} ]]; then
154             endpoint=$(helm -n ${SITE_NAMESPACE} get values -a ${name} | awk '/controlPlaneEndpoint:/ {print $2}')
155             prefix=$(helm -n ${SITE_NAMESPACE} get values -a ${name} | awk '/controlPlanePrefix:/ {print $2}')
156             host=$(ipcalc ${endpoint}/${prefix} | awk '/Network:/ {sub(/\.0.*/,".*"); print $2}')
157             if [[ $(grep -c "Host ${host}" ${HOME}/.ssh/config) != 0 ]]; then
158                 sed -i -e '/Host '"${host}"'/,+3 d' ${HOME}/.ssh/config
159             fi
160             cat <<EOF >>${HOME}/.ssh/config
161 Host ${host}
162   IdentityFile ${SCRIPTDIR}/id_rsa
163   StrictHostKeyChecking no
164   UserKnownHostsFile /dev/null
165 EOF
166         fi
167     done
168     # Add the identity to authorized keys on this host to enable ssh
169     # logins via its control plane address
170     authorized_key=$(cat ${SCRIPTDIR}/id_rsa.pub)
171     sed -i -e '\!'"${authorized_key}"'!d' ${HOME}/.ssh/authorized_keys
172     cat ${SCRIPTDIR}/id_rsa.pub >> ~/.ssh/authorized_keys
173 }
174
175 function _is_cluster_deleted {
176     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
177         name=$(awk '/clusterName:/ {print $2}' ${yaml})
178         ! kubectl -n ${SITE_NAMESPACE} get cluster ${name}
179     done
180 }
181
182 function site_wait_for_all_deleted {
183     WAIT_FOR_INTERVAL=60s
184     WAIT_FOR_TRIES=30
185     wait_for _is_cluster_deleted
186 }