Commit 46ca6a96 authored by Pedro Eduardo Trujillo's avatar Pedro Eduardo Trujillo
Browse files

Refactoriza '_prepare-deploy.sh' y retoca detalles

Separa lógica presente en este script en diferentes scripts, para
mejorar su mantenimiento.

Retoca algunas comprobaciones, tanto iniciales como de códigos de salida
de comandos.
parent b08cd47c
Loading
Loading
Loading
Loading
+31 −0
Original line number Diff line number Diff line
#!/bin/sh

echo -e "\n${INFO_COLOR}Checking deployment configuration in compose files ..${NULL_COLOR}"
echo -e "  ${INFO_COLOR}compose files [ ${DATA_COLOR}${COMPOSE_FILE}${INFO_COLOR} ]${NULL_COLOR}"
echo -en "  ${INFO_COLOR}check command [ ${DATA_COLOR}"

# Antes de continuar, se comprueba que la configuración de despliegue sea válida para compose o swarm.
if [ ${docker23CompatibleTarget} -eq 0 ] && [ ${deployingToSwarm} -eq 0 ]
then
	echo -e "docker stack config${INFO_COLOR} ]${NULL_COLOR}\n"
	grep -v '^[#| ]' .env | sed -r "s/(\w+)=(.*)/export \1='\2'/g" > .env-config

	env -i /bin/sh -c "\
		. $(pwd)/.env-config && \
		rm .env-config && \
		/usr/local/bin/docker stack config -c ${swarmComposeFileSplitted} > /dev/null"
else
	echo -e "docker compose config${INFO_COLOR} ]${NULL_COLOR}\n"

	docker compose config -q
fi

if [ ${?} -eq 0 ]
then
	echo -e "${PASS_COLOR}Valid compose configuration!${NULL_COLOR}"
else
	echo -e "\n${FAIL_COLOR}Invalid compose configuration!${NULL_COLOR}"
	eval "${restoreEnvFileCmd}"
	eval "${closeSshCmd}"
	exit 1
fi

script/_check-env.sh

0 → 100755
+58 −0
Original line number Diff line number Diff line
#!/bin/sh

# Se comprueba si está disponible el binario docker en el entorno donde se va a desplegar.
checkDockerCmd="docker --version > /dev/null 2>&1"
if ! ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDockerCmd}
then
	echo -e "\n${FAIL_COLOR}Docker is not available at deployment target host environment!${NULL_COLOR}"
	eval "${closeSshCmd}"
	exit 1
fi

# Se comprueba si la versión de Docker en el entorno donde se va a desplegar es >= v23.0.0.
checkDocker23Cmd="[ \$(docker --version | sed -r 's/.* ([0-9]+)\..*/\1/g') -ge 23 ]"
ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDocker23Cmd}
docker23CompatibleTarget=${?}

# Se comprueba si se desea y si es posible desplegar en modo Swarm.
checkDeploymentTypeCmd="[ ${FORCE_DOCKER_COMPOSE} -eq 0 ] && docker stack ls > /dev/null 2>&1"
ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDeploymentTypeCmd}
deployingToSwarm=${?}

# Se comprueba si está disponible el plugin compose de docker o el antiguo binario docker-compose.
if [ ${docker23CompatibleTarget} -eq 0 ]
then
	checkDockerComposeCmd="docker compose version > /dev/null 2>&1"
	dockerVersionLabel=">= v23"
	composeVersionLabel="current >=v2 plugin"
else
	checkDockerComposeCmd="docker-compose version > /dev/null 2>&1"
	dockerVersionLabel="< v23"
	composeVersionLabel="deprecated v1 binary"
fi

echo -e "  ${INFO_COLOR}host Docker version [ ${DATA_COLOR}${dockerVersionLabel}${INFO_COLOR} ]${NULL_COLOR}"

if [ ${deployingToSwarm} -eq 0 ]
then
	deploymentTypeLabel="Swarm"

	# Prepara los argumentos necesarios para indicar los ficheros compose a usar, para swarm o para compose.
	swarmComposeFileSplitted=$(echo ${COMPOSE_FILE} | sed 's/:/ -c /g')
else
	deploymentTypeLabel="Compose"

	# Prepara los argumentos necesarios para indicar los ficheros compose a usar, para compose.
	standardComposeFileSplitted=$(echo ${COMPOSE_FILE} | sed 's/:/ -f /g')

	if ! ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDockerComposeCmd}
	then
		echo -e "\n${FAIL_COLOR}Docker Compose (${composeVersionLabel}) is not available at deployment target host environment!${NULL_COLOR}"
		eval "${closeSshCmd}"
		exit 1
	fi

	echo -e "  ${INFO_COLOR}host Docker Compose version [ ${DATA_COLOR}${composeVersionLabel}${INFO_COLOR} ]${NULL_COLOR}"
fi

echo -e "  ${INFO_COLOR}deployment type [ ${DATA_COLOR}${deploymentTypeLabel}${INFO_COLOR} ]${NULL_COLOR}"
+0 −133
Original line number Diff line number Diff line
#!/bin/sh

echo -e "${INFO_COLOR}Performing a deployment at host ${DATA_COLOR}${remoteHost}${INFO_COLOR} ..${NULL_COLOR}"

# Se comprueba si está disponible el binario docker en el entorno donde se va a desplegar.
checkDockerCmd="docker --version > /dev/null 2>&1"
if ! ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDockerCmd}
then
	echo -e "\n${FAIL_COLOR}Docker is not available at deployment target host environment!${NULL_COLOR}"
	eval "${closeSshCmd}"
	exit 1
fi

# Se comprueba si la versión de Docker en el entorno donde se va a desplegar es >= v23.0.0.
checkDocker23Cmd="[ \$(docker --version | sed -r 's/.* ([0-9]+)\..*/\1/g') -ge 23 ]"
ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDocker23Cmd}
docker23CompatibleTarget=${?}

# Se comprueba si se desea y si es posible desplegar en modo Swarm.
checkDeploymentTypeCmd="[ ${FORCE_DOCKER_COMPOSE} -eq 0 ] && docker stack ls > /dev/null 2>&1"
ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDeploymentTypeCmd}
deployingToSwarm=${?}

# Se comprueba si está disponible el plugin compose de docker o el antiguo binario docker-compose.
if [ ${docker23CompatibleTarget} -eq 0 ]
then
	checkDockerComposeCmd="docker compose version > /dev/null 2>&1"
	dockerVersionLabel=">= v23"
	composeVersionLabel="current >=v2 plugin"
else
	checkDockerComposeCmd="docker-compose version > /dev/null 2>&1"
	dockerVersionLabel="< v23"
	composeVersionLabel="deprecated v1 binary"
fi

echo -e "  ${INFO_COLOR}host Docker version [ ${DATA_COLOR}${dockerVersionLabel}${INFO_COLOR} ]${NULL_COLOR}"

if [ ${deployingToSwarm} -eq 0 ]
then
	deploymentTypeLabel="Swarm"

	# Prepara los argumentos necesarios para indicar los ficheros compose a usar, para swarm o para compose.
	swarmComposeFileSplitted=$(echo ${COMPOSE_FILE} | sed 's/:/ -c /g')
else
	deploymentTypeLabel="Compose"

	# Prepara los argumentos necesarios para indicar los ficheros compose a usar, para compose.
	standardComposeFileSplitted=$(echo ${COMPOSE_FILE} | sed 's/:/ -f /g')

	if ! ssh ${SSH_PARAMS} "${SSH_REMOTE}" ${checkDockerComposeCmd}
	then
		echo -e "\n${FAIL_COLOR}Docker Compose (${composeVersionLabel}) is not available at deployment target host environment!${NULL_COLOR}"
		eval "${closeSshCmd}"
		exit 1
	fi

	echo -e "  ${INFO_COLOR}host Docker Compose version [ ${DATA_COLOR}${composeVersionLabel}${INFO_COLOR} ]${NULL_COLOR}"
fi

echo -e "  ${INFO_COLOR}deployment type [ ${DATA_COLOR}${deploymentTypeLabel}${INFO_COLOR} ]${NULL_COLOR}"

# Se preparan rutas de despliegue.
randomValue="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)"
deployHomeParent="${DEPLOY_PATH}/docker-deploy"
@@ -67,7 +8,6 @@ deployHome="${deployHomeParent}/${randomValue}"
# Se comprueba si existe directorio con recursos de despliegue o están en la raíz del proyecto.
if [ -d "${DEPLOY_DIR_NAME}" ]
then
	cd "${DEPLOY_DIR_NAME}"
	deployFiles="-r $(pwd)"
	createDirCmd="mkdir -p ${deployHomeParent}"
else
@@ -75,79 +15,6 @@ else
	createDirCmd="mkdir -p ${deployHome}"
fi

# Se obtienen los nombres de servicio presentes en ficheros compose, con prefijo de stack.
servicesInComposeFiles=$(docker compose config --services 2> /dev/null | sed "s/^/${STACK}_/g" | tr '\n' ' ')
servicesToDeployLabel=${SERVICES_TO_DEPLOY:-${servicesInComposeFiles}}

echo -e "  ${INFO_COLOR}services to deploy [ ${DATA_COLOR}${servicesToDeployLabel}${INFO_COLOR}]${NULL_COLOR}\n"
echo -e "${PASS_COLOR}Host environment is valid for deployment!${NULL_COLOR}"

echo -e "\n${INFO_COLOR}Setting environment variables to local and deployment target host environments ..${NULL_COLOR}"
echo -en "  ${INFO_COLOR}variable names [ ${DATA_COLOR}STACK${INFO_COLOR}"

envDefs="STACK=${STACK}"

addVariableToEnv() {
	envDefs="${envDefs}\\n${1}"
	variableName=$(echo "${1}" | cut -d '=' -f 1)
	echo -en "${INFO_COLOR}, ${DATA_COLOR}${variableName}${INFO_COLOR}"
}

# Se toma como base el entorno actual, incluyendo solo las variables cuyo nombre comience con el prefijo deseado.
currEnv=$(env | grep "^${ENV_PREFIX}" | sed "s/${ENV_PREFIX}//g" | sed "s/ /${ENV_SPACE_REPLACEMENT}/g")
for currEnvItem in ${currEnv}
do
	cleanItem=$(echo "${currEnvItem}" | sed "s/${ENV_SPACE_REPLACEMENT}/ /g")
	addVariableToEnv "${cleanItem}"
done

# Los argumentos pasados (opcionales) se tratan como variables. Sobreescriben a los valores procedentes del entorno.
for arg in "${@}"
do
	addVariableToEnv "${arg}"
done

# Se prepara el fichero .env para usarlas en la máquina destino y se setean en este entorno también.
restoreEnvFileCmd="mv .env-original .env"
if [ ! -f .env ]
then
	touch .env
	restoreEnvFileCmd="${restoreEnvFileCmd}; rm .env"
fi
cp -a .env .env-original
echo -e ${envDefs} >> .env

echo -e " ]${NULL_COLOR}\n"
echo -e "${PASS_COLOR}All environment variables set!${NULL_COLOR}"

echo -e "\n${INFO_COLOR}Checking deployment configuration in compose files ..${NULL_COLOR}"
echo -e "  ${INFO_COLOR}compose files [ ${DATA_COLOR}${COMPOSE_FILE}${INFO_COLOR} ]${NULL_COLOR}"
echo -en "  ${INFO_COLOR}check command [ ${DATA_COLOR}"

# Antes de continuar, se comprueba que la configuración de despliegue sea válida para compose o swarm.
if [ ${docker23CompatibleTarget} -eq 0 ] && [ ${deployingToSwarm} -eq 0 ]
then
	echo -e "docker stack config${INFO_COLOR} ]${NULL_COLOR}\n"
	grep -v '^[#| ]' .env | sed -r "s/(\w+)=(.*)/export \1='\2'/g" > .env-config
	checkComposeFilesCmd="env -i /bin/sh -c \". \$(pwd)/.env-config && /usr/local/bin/docker stack config -c ${swarmComposeFileSplitted} > /dev/null\""
else
	echo -e "docker compose config${INFO_COLOR} ]${NULL_COLOR}\n"
	checkComposeFilesCmd="docker compose config -q"
fi

cleanEnvConfigCmd="[ -f .env-config ] && rm -f .env-config"
if eval "${checkComposeFilesCmd}"
then
	echo -e "${PASS_COLOR}Valid compose configuration!${NULL_COLOR}"
	eval "${cleanEnvConfigCmd}"
else
	echo -e "\n${FAIL_COLOR}Invalid compose configuration!${NULL_COLOR}"
	eval "${cleanEnvConfigCmd}"
	eval "${restoreEnvFileCmd}"
	eval "${closeSshCmd}"
	exit 1
fi

echo -e "\n${INFO_COLOR}Sending deployment resources to host ${DATA_COLOR}${remoteHost}${INFO_COLOR} ..${NULL_COLOR}"

echo -e "  ${INFO_COLOR}deployment path [ ${DATA_COLOR}${deployHome}${INFO_COLOR} ]${NULL_COLOR}"

script/_prepare-env.sh

0 → 100755
+52 −0
Original line number Diff line number Diff line
#!/bin/sh

# Se cambia la ruta si existe directorio con recursos de despliegue, si no se permanece en la raíz del proyecto.
if [ -d "${DEPLOY_DIR_NAME}" ]
then
	cd "${DEPLOY_DIR_NAME}"
fi

# Se obtienen los nombres de servicio presentes en ficheros compose, con prefijo de stack.
servicesInComposeFiles=$(docker compose config --services 2> /dev/null | sed "s/^/${STACK}_/g" | tr '\n' ' ')
servicesToDeployLabel=${SERVICES_TO_DEPLOY:-${servicesInComposeFiles}}

echo -e "  ${INFO_COLOR}services to deploy [ ${DATA_COLOR}${servicesToDeployLabel}${INFO_COLOR}]${NULL_COLOR}\n"
echo -e "${PASS_COLOR}Host environment is valid for deployment!${NULL_COLOR}"

echo -e "\n${INFO_COLOR}Setting environment variables to local and deployment target host environments ..${NULL_COLOR}"
echo -en "  ${INFO_COLOR}variable names [ ${DATA_COLOR}STACK${INFO_COLOR}"

envDefs="STACK=${STACK}"

addVariableToEnv() {
	envDefs="${envDefs}\\n${1}"
	variableName=$(echo "${1}" | cut -d '=' -f 1)
	echo -en "${INFO_COLOR}, ${DATA_COLOR}${variableName}${INFO_COLOR}"
}

# Se toma como base el entorno actual, incluyendo solo las variables cuyo nombre comience con el prefijo deseado.
currEnv=$(env | grep "^${ENV_PREFIX}" | sed "s/${ENV_PREFIX}//g" | sed "s/ /${ENV_SPACE_REPLACEMENT}/g")
for currEnvItem in ${currEnv}
do
	cleanItem=$(echo "${currEnvItem}" | sed "s/${ENV_SPACE_REPLACEMENT}/ /g")
	addVariableToEnv "${cleanItem}"
done

# Los argumentos pasados (opcionales) se tratan como variables. Sobreescriben a los valores procedentes del entorno.
for arg in "${@}"
do
	addVariableToEnv "${arg}"
done

# Se prepara el fichero .env para usarlas en la máquina destino y se setean en este entorno también.
restoreEnvFileCmd="mv .env-original .env"
if [ ! -f .env ]
then
	touch .env
	restoreEnvFileCmd="${restoreEnvFileCmd}; rm .env"
fi
cp -a .env .env-original
echo -e ${envDefs} >> .env

echo -e " ]${NULL_COLOR}\n"
echo -e "${PASS_COLOR}All environment variables set!${NULL_COLOR}"
+7 −1
Original line number Diff line number Diff line
@@ -2,12 +2,18 @@

if [ -z "${SSH_REMOTE}" ]
then
	echo -e "${FAIL_COLOR}You must define 'SSH_REMOTE' in environment, with remote user and hostname (like 'ssh-user@ssh-remote')${NULL_COLOR}"
	echo -e "${FAIL_COLOR}You must define 'SSH_REMOTE' in environment${NULL_COLOR}"
	exit 1
fi

remoteHost=$(echo "${SSH_REMOTE}" | cut -f 2 -d '@')

if [ -z "${remoteHost}" ]
then
	echo -e "${FAIL_COLOR}Remote host not found, define 'SSH_REMOTE' with remote user and hostname (like 'ssh-user@ssh-remote')${NULL_COLOR}"
	exit 1
fi

if [ -z "${DEPLOY_KEY}" ]
then
	echo -e "${FAIL_COLOR}You must define 'DEPLOY_KEY' in environment, with a SSH private key accepted by remote host${NULL_COLOR}"
Loading