Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cron: rewrite ansible-daily-run script #246

Merged
merged 1 commit into from
Apr 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 36 additions & 12 deletions roles/cron/templates/ansible-daily-run.sh.j2
Original file line number Diff line number Diff line change
@@ -1,18 +1,42 @@
#!/bin/bash
set -eo pipefail

readonly LOGFILE=$(mktemp)
trap "rm -f ${LOGFILE}" EXIT
readonly ANSIBLE_LOCAL_REPO=${ANSIBLE_LOCAL_REPO:-'/etc/ansible'}
readonly GIT_BRANCH=${GIT_BRANCH:-'main'}
readonly GIT_REMOTE=${GIT_REMOTE:-'origin'}
readonly ZEUS_STATUS_FILE=${ZEUS_STATUS_FILE:-'/etc/ansible/zeus_daily_run_status.txt'}

rm "${ZEUS_STATUS_FILE}"
touch "${ZEUS_STATUS_FILE}"

readonly LOGFILE="$(mktemp)"
echo "Ansible Daily run on Olympus" > "${LOGFILE}"

cd /etc/ansible
git pull origin olympus >> "${LOGFILE}"
# TODO: update /etc/ansible/vars too
zeus_status() {
if [ -s "${ZEUS_STATUS_FILE}" ]; then
cat "${ZEUS_STATUS_FILE}"
else
echo "Ansible did not ran"
fi
}

set +e
ansible-playbook -D /etc/ansible/zeus.yml 2>&1 >> "${LOGFILE}"
echo "${?}" > /etc/ansible/zeus_daily_run_status.txt
set -e
mail_report() {
local subject=$(head -1 "${LOGFILE}" | sed -e "s;$; (Status: $(zeus_status));")
cat "${LOGFILE}" | \
mailx -r "{{ mailer.to }}" -s "{{ jobs.name }}:${subject}" \
-S smtp="{{ mailer.smtp.host }}:{{mailer.smtp.port }}" "{{ mailer.replyTo }}"
}

run_zeus() {
echo "Set working directory ${ANSIBLE_LOCAL_REPO}."
cd "${ANSIBLE_LOCAL_REPO}"
echo "Update local Zeus repository ($(pwd))"
git pull "${GIT_REMOTE}" "${GIT_BRANCH}"
ansible-playbook -D "${ANSIBLE_LOCAL_REPO}/zeus.yml" 2>&1
echo "${?}" > "${ZEUS_STATUS_FILE}"
}

trap mail_report EXIT
trap "rm -f ${LOGFILE}" EXIT

readonly SUBJECT=$(tail -2 "${LOGFILE}" | sed '/^$/d' | head -1)
cat "${LOGFILE}" | \
mailx -r "{{ mailer.to }}" -s "{{ jobs.name }}:${SUBJECT}" -S smtp="{{ mailer.smtp.host }}:{{mailer.smtp.port }}" "{{ mailer.replyTo }}"
run_zeus >> "${LOGFILE}"
Loading