Skip to content

Instantly share code, notes, and snippets.

@ccarrasc
Created January 16, 2015 15:38
Show Gist options
  • Save ccarrasc/b72d37b4ccbc1ae21fa9 to your computer and use it in GitHub Desktop.
Save ccarrasc/b72d37b4ccbc1ae21fa9 to your computer and use it in GitHub Desktop.
Untested script with commands used for installing MongoDB on CentOS 7
#! /bin/bash
APPLICATION_IP="192.168.33.1/24"
REPLICA_SET="MyReplicaSet"
KEY_FILE_PATH="/etc/mongodb/keyfiles"
KEY_FILE="mongodb-keyfile"
# Make sure this is executed on CentOS 7
OS=`cat /etc/redhat-release | awk {'print $1$4}'`
if [ "$OS" != CentOS7* ]; then
echo -e "\e[1;31mThis script is intended for CentOS 7 only\e[0m" 1>&2
exit 1
fi
# Make sure this is executed as root (for SELinux modifications)
if [[ $EUID -ne 0 ]]; then
echo -e "\e[1;31mThis script must be run as root or it will fail\e[0m" 1>&2
exit 1
fi
# Install MongoDB
# Ref: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-red-hat-centos-or-fedora-linux/
# Configure the package management system (YUM)
cat << 'EOF' > /etc/yum.repos.d/mongodb.repo
[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1
EOF
# Install the MongoDB packages and associated tools
sudo yum install mongodb-org -y
# Configure SELinux to allow MongoDB to start on Red Hat Linux-based systems
# by enabling access to the relevant ports
SELINUX_MODE=`getenforce`
if [[ $SELINUX_MODE -eq "Enforcing" ]]; then
if ! command -v semanage >/dev/null; then
sudo yum install policycoreutils-python -y
fi
semanage port -a -t mongod_port_t -p tcp 27017
fi
# Configure the firewall
iptables -A INPUT -s $APPLICATION_IP -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d $APPLICATION_IP -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT DROP
service iptables save
# Disable listening to local interfaces only
sed -i "s|^bind_ip|#bind_ip|" /etc/mongod.conf
# Generate a key file and setup config for replica set
openssl rand -base64 741 > $KEY_FILE
mkdir -p $KEY_FILE_PATH
mv $KEY_FILE $KEY_FILE_PATH
chmod 600 $KEY_FILE_PATH/$KEY_FILE
chown mongod $KEY_FILE_PATH/$KEY_FILE
sed -i "s|^#replSet=setname|replSet=$REPLICA_SET|" /etc/mongod.conf
sed -i "s|^#keyFile=/path/to/keyfile|keyFile=$KEY_FILE_PATH/$KEY_FILE|" /etc/mongod.conf
chkconfig mongod on
service mongod start
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment