Shell script for backup on Jenkins freestyle without password input

Shell script for backup on Jenkins freestyle without password input

If you have password problems when using sudo in a Jenkins Freestyle project, you can set up passwordless sudo just for the commands your backup script needs. Here's an example shell script to use in a Jenkins Freestyle project for backups without needing a password:

#!/bin/bash

# Disable the requiretty setting in sudoers
echo "Defaults !requiretty" | sudo tee -a /etc/sudoers

# Define backup directories and locations
backup_dir="/path/to/backup/folder"
system_dirs=("/etc" "/var" "/home")

# Create a timestamp for the backup
timestamp=$(date +"%Y%m%d%H%M%S")
backup_file="system_backup_$timestamp.tar.gz"

# Create the backup directory if it doesn't exist
mkdir -p "$backup_dir"

# Use sudo without password to create a compressed tarball of system directories
sudo -n tar -czvf "$backup_dir/$backup_file" "${system_dirs[@]}"

# Check if the backup was successful
if [ $? -eq 0 ]; then
  echo "System backup completed successfully. Backup stored in: $backup_dir/$backup_file"
else
  echo "System backup failed."
fi

# Enable the requiretty setting in sudoers
# This is a security measure to re-enable password requirement for other sudo commands
echo "Defaults requiretty" | sudo tee /etc/sudoers.d/requiretty

In this script:

  1. We temporarily disable the requiretty setting in the sudoers file, which allows sudo to run without a terminal.

  2. We perform the backup using sudo -n with the -n option to run sudo without a password prompt.

  3. After the backup, we re-enable the requiretty setting in the sudoers file. This is a security measure to ensure that the requiretty setting is in place for other sudo commands.

Keep in mind that changing the sudoers file needs admin rights and should be done carefully. Also, using sudo without a password should be done wisely and only for certain commands, because it can create security risks. Don't forget to change /path/to/backup/folder and modify the system_dirs array to fit your needs.