Remove invalid characters from Flux resource names
[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     # Only alphanumeric and '-' are allowed in resource names
62     echo $(basename ${url})-${branch} | tr -d -c 'A-Za-z0-9-'
63 }
64
65 function _site_kustomization_name {
66     local -r url=$1
67     local -r branch=$2
68     local -r path=$3
69     # Only alphanumeric and '-' are allowed in resource names
70     echo $(_site_source_name ${url} ${branch})-site-$(basename ${path})  | tr -d -c 'A-Za-z0-9-'
71 }
72
73 function flux_create_site {
74     local -r url=$1
75     local -r branch=$2
76     local -r path=$3
77     local -r key_name=$4
78
79     local -r source_name=$(_site_source_name ${url} ${branch})
80     local -r kustomization_name=$(_site_kustomization_name ${url} ${branch} ${path})
81     local -r key_fp=$(gpg --with-colons --list-secret-keys ${key_name} | awk -F: '/fpr/ {print $10;exit}')
82     local -r secret_name="${key_name}-sops-gpg"
83
84     flux create source git ${source_name} --url=${url} --branch=${branch}
85     gpg --export-secret-keys --armor "$(_gpg_key_fp ${key_name})" |
86         kubectl -n flux-system create secret generic ${secret_name} --from-file=sops.asc=/dev/stdin --dry-run=client -o yaml |
87         kubectl apply -f -
88     kubectl create namespace ${SITE_NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
89     flux create kustomization ${kustomization_name} --target-namespace=${SITE_NAMESPACE} --path=${path} --source=GitRepository/${source_name} --prune=true \
90          --decryption-provider=sops --decryption-secret=${secret_name}
91 }
92
93 function site_deploy {
94     flux_create_site ${SITE_REPO} ${SITE_BRANCH} ${SITE_PATH} ${FLUX_SOPS_KEY_NAME}
95 }
96
97 function site_clean {
98     kubectl -n flux-system delete kustomization $(_site_kustomization_name ${SITE_REPO} ${SITE_BRANCH} ${SITE_PATH})
99 }
100
101 function _is_cluster_ready {
102     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
103         name=$(awk '/clusterName:/ {print $2}' ${yaml})
104         if [[ ! -z ${name} ]]; then
105             if [[ $(kubectl -n ${SITE_NAMESPACE} get cluster ${name} -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}') != "True" ]]; then
106                 return 1
107             fi
108         fi
109     done
110 }
111
112 function _is_control_plane_ready {
113     # Checking the Cluster resource status is not sufficient, it
114     # reports the control plane as ready before the nodes forming the
115     # control plane are ready
116     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
117         name=$(awk '/clusterName:/ {print $2}' ${yaml})
118         if [[ ! -z ${name} ]]; then
119             local replicas=$(kubectl -n ${SITE_NAMESPACE} get kubeadmcontrolplane ${name} -o jsonpath='{.spec.replicas}')
120             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
121                 return 1
122             fi
123         fi
124     done
125 }
126
127 function site_wait_for_all_ready {
128     WAIT_FOR_INTERVAL=60s
129     WAIT_FOR_TRIES=30
130     wait_for _is_cluster_ready
131     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
132         name=$(awk '/clusterName:/ {print $2}' ${yaml})
133         clusterctl -n ${SITE_NAMESPACE} get kubeconfig ${name} >${BUILDDIR}/${name}-admin.conf
134         chmod 600 ${BUILDDIR}/${name}-admin.conf
135     done
136     wait_for _is_control_plane_ready
137 }
138
139 function site_insert_control_plane_network_identity_into_ssh_config {
140     # This enables logging into the control plane machines from this
141     # machine without specifying the identify file on the command line
142
143     if [[ ! $(which ipcalc) ]]; then
144         apt-get install -y ipcalc
145     fi
146
147     # Create ssh config if it doesn't exist
148     mkdir -p ${HOME}/.ssh && chmod 700 ${HOME}/.ssh
149     touch ${HOME}/.ssh/config
150     chmod 600 ${HOME}/.ssh/config
151     # Add the entry for the control plane network, host value in ssh
152     # config is a wildcard
153     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
154         name=$(awk '/name:/ {NAME=$2} /chart: deploy\/cluster/ {print NAME; exit}' ${yaml})
155         if [[ ! -z ${name} ]]; then
156             endpoint=$(helm -n ${SITE_NAMESPACE} get values -a ${name} | awk '/controlPlaneEndpoint:/ {print $2}')
157             prefix=$(helm -n ${SITE_NAMESPACE} get values -a ${name} | awk '/controlPlanePrefix:/ {print $2}')
158             host=$(ipcalc ${endpoint}/${prefix} | awk '/Network:/ {sub(/\.0.*/,".*"); print $2}')
159             if [[ $(grep -c "Host ${host}" ${HOME}/.ssh/config) != 0 ]]; then
160                 sed -i -e '/Host '"${host}"'/,+3 d' ${HOME}/.ssh/config
161             fi
162             cat <<EOF >>${HOME}/.ssh/config
163 Host ${host}
164   IdentityFile ${SCRIPTDIR}/id_rsa
165   StrictHostKeyChecking no
166   UserKnownHostsFile /dev/null
167 EOF
168         fi
169     done
170     # Add the identity to authorized keys on this host to enable ssh
171     # logins via its control plane address
172     authorized_key=$(cat ${SCRIPTDIR}/id_rsa.pub)
173     sed -i -e '\!'"${authorized_key}"'!d' ${HOME}/.ssh/authorized_keys
174     cat ${SCRIPTDIR}/id_rsa.pub >> ~/.ssh/authorized_keys
175 }
176
177 function _is_cluster_deleted {
178     for yaml in ${SCRIPTDIR}/deployment/*.yaml; do
179         name=$(awk '/clusterName:/ {print $2}' ${yaml})
180         ! kubectl -n ${SITE_NAMESPACE} get cluster ${name}
181     done
182 }
183
184 function site_wait_for_all_deleted {
185     WAIT_FOR_INTERVAL=60s
186     WAIT_FOR_TRIES=30
187     wait_for _is_cluster_deleted
188 }