Tag Archives: cron

Auto deploy from BitBucket repository via Cron

Setup the environment

Create the environment for Apache

mkdir /home/deployment
chown apache:apache /home/deployment

Create ssh key in /home/deployment/.ssh/id_rsa

Create wrapper for git to auth via SSH keys

cat > /home/deployment/git.sh <<EOF
#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Git wrapper script that can specify an ssh-key file
Usage:
    git.sh -i ssh-key-file git-command
    "
    exit 1
fi

# remove temporary file on exit
trap 'rm -f /home/deployment/.git_ssh.$$' 0

if [ "$1" = "-i" ]; then
    SSH_KEY=$2; shift; shift
    echo "ssh -o StrictHostKeyChecking=no -i $SSH_KEY \$@" > /home/deployment/.git_ssh.$$
    chmod +x /home/deployment/.git_ssh.$$
    export GIT_SSH=/home/deployment/.git_ssh.$$
fi

# in case the git command is repeated
[ "$1" = "git" ] && shift

# Run the git command
git "$@"
EOF 

Run the fist clone

~# su - apache -s /bin/bash
Last login: Tue Apr  5 16:03:53 BST 2016 on pts/0
-bash-4.2$ cd /var/www/vhosts/

-bash-4.2$ /home/deployment/git.sh -i /home/deployment/.ssh/id_rsa clone [email protected]:repository01.git

Test the Re-Base

Make sure to get into the folder with .git subfolder
(in this case we did the clone into /var/www/vhosts/ BUT the code is stored into a new subfolder pulled with the domain name. So we cd into that one)

-bash-4.2$ cd /var/www/vhosts/blog.com && /home/deployment/git.sh -i /home/deployment/.ssh/id_rsa pull --rebase
Could not create directory '/usr/share/httpd/.ssh'.
Failed to add the host to the list of known hosts (/usr/share/httpd/.ssh/known_hosts).
Current branch master is up to date.
-bash-4.2$

Install the CRON

echo "*/5 * * * * apache cd /var/www/vhosts/blog.com && /home/deployment/git.sh -i /home/deployment/.ssh/id_rsa pull --rebase > /dev/null 2>&1" >> /etc/crontab

Scheduled unattended tasks – at

$ at time date

$ at 11 am may 20

# at 02:00 AM Fri
at> yum update glibc
at> echo "Executing scheduled task" | logger
at> shutdown -r +5 "Server is going to be rebooted in 5 minutes for scheduled task. Please save your work ASAP." 
at> <EOT>
job 2 at 2015-02-06 02:00

Ends using CTRL+D that generates the <EOT> bit.

Source: http://www.computerhope.com/unix/uat.htm

Check the processes in the queue

atq

Check content of a job

at -c <job number>

Delete job

atrm <job number>

Also, you can cat/modify the job in /var/spool/cron/atjobs/ or /var/spool/at (in Centos)

If not installed, on Centos, make sure to start also ‘atd‘ service.

# chkconfig atd on && service atd start