One place for hosting & domains

      October 2022

      How to Install Chef on Ubuntu 20.04

      Chef is a free and open source Infrastructure as Code (IaC) application. It’s a configuration management system that allows administrators to provision and manage infrastructure using automation. A complete Chef workflow includes one or more Chef Workstations, a Chef Server, and a set of nodes. This guide provides some background on how Chef works, and explains how to install and configure Chef on Ubuntu 20.04.

      What is Chef?

      Chef is a IaC application for automating and streamlining the process of provisioning, configuring, deploying, and managing network nodes. It allows for continuous deployment and an automated environment. Chef can manage many types of components including servers, containers, and networking infrastructure.

      Chef operates using a hub-and-spoke architecture, with the master Chef Server at the center. One or more Chef Workstations interact with the Server, which automates the configuration of one or more Chef nodes. Configuration assets move from the workstation to the server and finally to the nodes. Workstations cannot interact with the nodes directly. The Chef infrastructure consists of the following components.

      • Chef Workstation: A workstation is a server for creating and testing configuration code. The code is then pushed to the Chef Server. Several workstations can interact with the same server, but each workstation only links to one server. The
        Chef Workstation documentation contains more information on how to use the workstation.
      • Chef Server: The Chef Server is the “command center” for the entire system. It stores and maintains all the configuration files, code, and scripts. A Chef Server includes many components, including a web server and PostgreSQL database. It is responsible for pushing the relevant assets to the various nodes and keeping track of the nodes under its management. Each server is highly capable, efficient, and robust, and is capable of managing a large number of nodes.
      • Chef Node: The Chef Server deploys and manages a node using assets developed on the Chef Workstation. Each node is administered by a single Chef Server. Although it is dependent on the server, a Chef Node contains a Chef client. The client queries the server for updates and keeps the node up to date.

      The following illustration indicates the relationship between the three parts of the Chef system.

      The workstations use Chef commands, such as the knife directive, to interact with the server. Chef incorporates extra security and authentication into all of its operations, using public key encryption. However, the Chef system is complex and has a high learning curve.

      Chef uses an idiosyncratic terminology based on cooking vocabulary. Some of the more important terms include the following:

      • Attribute: Specifies a value for an item on a node.
      • Bookshelf: Stores the various cookbooks and assets on a Chef Server using versioning control.
      • Chef-client: Runs on the node, and is responsible for verifying whether the node is up-to-date with the assets stored on the server.
      • Chef-repo: A directory on the Chef Workstation that contains the local cookbooks and configuration files.
      • Cookbook: The primary method of managing nodes. It contains information describing the final state of a node. The Chef server and node use the cookbook to guide configuration. Cookbooks contain recipes, along with attributes, libraries, templates, and scripts. These cookbooks can be developed on the workstation or downloaded from the
        Chef Supermarket.
      • Environment: Collects nodes into groups to better organize them. Similar configurations and scripts can be applied to the entire group.
      • Knife: A Chef Workstation uses the knife tool to correspond with the Chef Server. A knife command usually takes the format knife subcommand [ARGUMENT] (options).
      • Recipe: A recipe is contained within a cookbook. It explains the resources to add, change, or run on the node. Recipes are written in Ruby.
      • Resource: A resource is part of a recipe. It contains a type, name, and list of key-value pairs for a component.
      • Test Kitchen: This is a workstation module to help users test recipes before deployment.

      Linode has a helpful
      Beginner’s Guide to Chef. For detailed information about Chef, see the
      Chef documentation. Chef also makes the
      Learn Chef training resource available.

      Before You Begin

      1. If you have not already done so, create a Linode account and Compute Instance. See our
        Getting Started with Linode and
        Creating a Compute Instance guides.

      2. Follow our
        Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

      3. At least three Linode systems running Ubuntu 20.04 are required to implement a Chef system. One server is for the Chef Workstation, the second for the Chef Server, while a third represents a node under administration. Due to Chef’s memory demands, the Chef Server requires a 8GB Linode. The other two servers can be 2GB Linodes. Both the Chef Server and Chef Workstation should be configured using the previous instructions. Chef is used to set up the target node.

      4. Ensure all Linode servers are updated using the following command.

        sudo apt update && sudo apt upgrade
      5. Assign a domain name to the Chef Server. For information on domain names and pointing the domain name to a Linode, see the
        Linode DNS Manager guide.

      6. Configure the host name of the Chef Server so it matches the domain name. This allows SSL certificate allocation to proceed normally. To set the host name of a Ubuntu server, use the command sudo hostnamectl set-hostname <hostname>, replacing <hostname> with the actual name of your domain.


      This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you are not familiar with the sudo command, see the
      Users and Groups guide.

      How to Install and Configure the Chef Server

      Because the Chef Server operates as a hub for the entire system, it is best to install and configure it first. The Chef Server uses a high amount of resources, so it is important to use a dedicated Linode with at least 8GB of memory.

      How to Install the Chef Server

      The Chef Server Core can be downloaded using wget. The following steps demonstrate how to download the latest release of Chef for the Ubuntu 20.04 release. For other releases of Ubuntu, see the
      Chef download page. For more detailed instructions, see the
      Chef Server installation page. To install the Chef Server, follow these steps.

      1. Download the Chef Server core using wget.

      2. Install the server core.

        sudo dpkg -i chef-server-core_*.deb
        Selecting previously unselected package chef-server-core.
        (Reading database ... 108635 files and directories currently installed.)
        Preparing to unpack chef-server-core_15.1.7-1_amd64.deb ...
        Unpacking chef-server-core (15.1.7-1) ...
        Setting up chef-server-core (15.1.7-1) ...
        Thank you for installing Chef Infra Server!
      3. For better security and to preserve server space, remove the downloaded .deb file.

        rm chef-server-core_*.deb
      4. Start the Chef server. Answer yes when prompted to accept the product licenses.


        The installation process takes several minutes to complete. Upon a successful installation, the message Chef Infra Server Reconfigured! is displayed.

        sudo chef-server-ctl reconfigure

      How to Configure a Chef User and Organization

      To use Chef, configure an organization and at least one user on the Chef Server. This enables server access for workstations and nodes. To create these accounts, follow these steps.

      1. Create a .chef directory to store the keys. This should be a subdirectory located inside the home directory.

      2. Use the chef-server-ctl command to create a user account for the Chef administrator. Additional user accounts can be created later. Replace the USER_NAME, FIRST_NAME, LAST_NAME, EMAIL, and PASSWORD fields with the relevant information. For the --filename argument, replace USER_NAME.pem with the user name used earlier in the command.

        sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename ~/.chef/USER_NAME.pem
      3. Review the user list and confirm the account now exists.

        sudo chef-server-ctl user-list
      4. Create a new organization, also using the chef-server-ctl command. Replace ORG_NAME and ORG_FULL_NAME with the actual name of the organization. The ORG_NAME field must be all lower case. The value for USER_NAME must be the same name used in the user-create command. For the --filename argument, in ORG_NAME.pem, replace ORG_NAME with the organization name used elsewhere in the command.

        sudo chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" --association_user USER_NAME --filename ~/.chef/ORG_NAME.pem
      5. List the organizations to confirm the new organization is successfully created.

        sudo chef-server-ctl org-list

      How to Install and Configure a Chef Workstation

      A Chef Workstation is for users to create and test recipes. Any Linode with at least 2GB of memory can be used for this task. Unlike the Chef Server, a workstation can also be used for other tasks. However, in a larger organization hosting many users, it is often efficient to centralize workstation activities on one server hosting multiple accounts.

      How to Install a Chef Workstation

      The steps for installing a Chef Workstation are similar to those for installing the Server. Download the correct file using wget, then install it. To install a Chef Workstation, follow these steps.

      1. Download the source files for the Chef Workstation. For different releases of the Workstation, or downloads for earlier releases, see the
        Chef Workstation Downloads page. For more information on the installation process, see the
        Chef Workstation Installation Documentation.

      2. Install the Chef Workstation.

        sudo dpkg -i chef-workstation_*.deb
        Thank you for installing Chef Workstation!
      3. Remove the source file.

        rm chef-workstation_*.deb
      4. Confirm the correct release of the Chef Workstation is installed.

        Chef Workstation version: 22.10.1013
        Chef Infra Client version: 17.10.0
        Chef InSpec version: 4.56.20
        Chef CLI version: 5.6.1
        Chef Habitat version: 1.6.521
        Test Kitchen version: 3.3.2
        Cookstyle version: 7.32.1

      How to Configure a Chef Workstation

      A few more items must be configured before the Workstation is operational. Tasks include generating a repository, editing the hosts file, and creating a subdirectory. To fully configure the workstation, follow these steps.

      1. Generate the chef-repo repository. This directory stores the Chef cookbooks and recipes. Enter yes when asked whether to accept the product licenses.

        chef generate repo chef-repo
        Your new Chef Infra repo is ready! Type `cd chef-repo` to enter it.
      2. Edit the /etc/hosts file. This file contains mappings between host names and their IP addresses. Add an entry for the Chef Server, containing the name of the server, which is also the domain name, and its IP address. In this example, this is indicated in the line There must also be an entry for the local server. This is the chefworkstation line in the example. This entry must contain the local IP address and the hostname of the server hosting the Chef Workstation. The file should resemble the following example.

        File: /etc/hosts
        localhost chefworkstation
      3. Create a .chef subdirectory. This is where the knife file is stored, along with files for encryption and security.

        mkdir ~/chef-repo/.chef
        cd chef-repo

      How to Add RSA Private Keys

      RSA private keys enable better security between the Chef Server and associated workstations through the use of encryption. Earlier, RSA private keys were created on the Chef Server. Copying these keys to a workstation allows it to communicate with the server. To enable encryption using RSA private keys, follow these steps.


      SSH password authentication must be enabled on the Chef Server to complete the key exchange. If SSH password authentication has been disabled for better security, enable it again before proceeding. After the keys have been retrieved and added to the workstation, SSH password authentication can be disabled again. See the Linode guide to
      How to Secure Your Server for more information.
      1. On the workstation, generate an RSA key pair. This key can be used to initially access the Chef server to copy over the private encryption files.

        Generating public/private rsa key pair.
        Enter file in which to save the key (/home/username/.ssh/id_rsa):
      2. Hit the Enter key to accept the default file names id_rsa and Ubuntu stores these files in the /home/username/.ssh directory.

        Created directory '/home/username/.ssh'.
        Enter passphrase (empty for no passphrase):
      3. Enter a password when prompted, then enter it again. An identifier and public key are saved to the directory.

        Your identification has been saved in /home/username/.ssh/id_rsa
        Your public key has been saved in /home/username/.ssh/
      4. Copy the new public key from the workstation to the Chef Server. In the following command, use the account name for the Chef Server along with its IP address.

        ssh-copy-id username@
      5. Use the scp command to copy the .pem files from the Chef Server to the workstation. In the following example, replace username with the user account for the Chef Server and with the actual Chef Server IP address.

        scp username@*.pem ~/chef-repo/.chef/
        Enter passphrase for key '/home/username/.ssh/id_rsa':
        username.pem                                                                       100% 1674     1.7MB/s   00:00
        testcompany.pem                                                                 100% 1678     4.7MB/s   00:00
      6. List the contents of the .chef subdirectory to ensure the .pem files were successfully copied.

        username.pem  testcompany.pem

      How to Configure Git on a Chef Workstation

      A version control system helps the Chef Workstation track any changes to the cookbooks and restore earlier versions if necessary. This example uses Git, which is compatible with the Chef system. The following steps explain how to configure Git, initialize a Git repository, add new files, and commit them.

      1. Configure Git using the git config command. Replace username and with your own values.

        git config --global username
        git config --global
      2. Add the .chef directory to the .gitignore file. This ensures system and auto-generated files are not shown in the output of git status and other Git commands.

        echo ".chef" > ~/chef-repo/.gitignore
      3. Ensure the chef-repo directory is the current working directory. Add and commit the existing files using git add and git commit.

        cd ~/chef-repo
        git add .
        git commit -m "initial commit"
        [master (root-commit) a3208a3] initial commit
        13 files changed, 343 insertions(+)
        create mode 100644 .chef-repo.txt
        create mode 100644 policyfiles/
      4. Run the git status command to ensure all files have been committed.

        On branch master
        nothing to commit, working tree clean

      How to Generate a Chef Cookbook

      To generate a new Chef cookbook, use the chef generate command.

      chef generate cookbook my_cookbook

      How to Configure the Knife Utility

      The Chef Knife utility helps a Chef workstation communicate with the server. It provides a method of managing cookbooks, nodes, and the Chef environment. Chef uses the config.rb file in the .chef subdirectory to store the Knife configuration. To configure Knife, follow these steps.

      1. Create a config.rb file in the ~/chef-repo/.chef directory. This example uses vi, but any text editor can be used.

        cd ~/chef-repo/.chef
        vi config.rb
      2. Use the following config.rb file as an example of how to configure Knife. Copy this sample configuration to the file.

        File: ~/chef-repo/.chef/config.rb
        current_dir = File.dirname(__FILE__)
        log_level                :info
        log_location             STDOUT
        node_name                'node_name'
        client_key               "USER.pem"
        validation_client_name   'ORG_NAME-validator'
        validation_key           "ORG_NAME-validator.pem"
        chef_server_url          ''
        cache_type               'BasicFile'
        cache_options( :path => "#{ENV['HOME']}/.chef/checksums" )
        cookbook_path            ["#{current_dir}/../cookbooks"]
      3. Make the following changes:

        • node_name must be the name of the user account created when configuring the Chef Server.
        • For client_key, replace USER with the user name associated with the .pem file, followed by .pem.
        • validation_client_name requires the same ORG_NAME used when creating the organization followed by -validator.
        • the validation_key field must contain the name used for ORG_NAME when the organization was created, followed by -validator.pem.
        • For chef_server_url, change to the name of the domain. Follow the domain name with /organizations/ and the ORG_NAME used when creating the organization.
        • Leave the remaining fields unchanged.
      4. Move back to the chef-repo directory and fetch the necessary SSL certificates from the server using the knife fetch command.


        The SSL certificates were generated when the Chef server was installed. The certificates are self-signed. This means a certificate authority has not verified them. Before fetching the certificates, log in to the Chef server and ensure the hostname and fully qualified domain name (FQDN) are the same. These values can be confirmed using the commands hostname and hostname -f.

        Knife has no means to verify these are the correct certificates. You should verify the authenticity of these certificates after downloading.
        Adding certificate for in /home/username/chef-repo/.chef/trusted_certs/
      5. To confirm the config.rb file is correct, run the knife client list command. The relevant validator name should be displayed.


      How to Bootstrap a Node

      At this point, both the Chef Server and Chef Workstation are configured. They can now be used to bootstrap the node. The bootstrap process installs the chef client on the node and performs validation. The node can then retrieve any necessary updates from the Chef Server. To bootstrap the node, follow these steps.

      1. Log in to the target node, which is the node to be bootstrapped, and edit the /etc/hosts file. Add entries for the node, the Chef server domain name, and the workstation. The file should resemble the following example, using the actual names of the Chef Server, workstation, and the target node, along with their IP addresses.

        File: /etc/hosts
        localhost targetnode chefworkstation
      2. Return to the Linode hosting the Chef Workstation and change the working directory to ~/chef-repo/.chef.

      3. Bootstrap the node using the knife bootstrap command. Specify the IP address of the target node for node_ip_address. This is the address of the node to bootstrap. In the following example, use the actual user name and password for the account in place of username and password. Enter the name of the node in place of nodename. Answer Y when asked “Are you sure you want to continue connecting”.


        The option to bootstrap using key-pair authentication no longer appears to be supported.

        knife bootstrap node_ip_address -U username -P password --sudo --use-sudo-password --node-name nodename
      4. Confirm the node has been successfully bootstrapped. List the client nodes using the knife client list command. All bootstrapped nodes should be listed.

      5. Add the bootstrapped node to the workstation /etc/hosts file as follows. Replace targetnode with the IP address and name of the bootstrapped node.

        File: /etc/hosts
        localhost chefworkstation targetnode

      How to Download and Apply a Cookbook (Optional)

      A cookbook is the most efficient way of keeping target nodes up to date. In addition, a cookbook can delete the validation.pem file that was created on the node when it was bootstrapped. It is important to delete this file for security reasons.

      It is not mandatory to download or create cookbooks to use Chef. But this section provides a brief example of how to download a cookbook and apply it to a node.

      1. On the Chef workstation, change to the ~/chef-repo/.chef directory.

      2. Download the cron-delvalidate cookbook from the Chef Supermarket. For more information on the supermarket command see the
        Chef supermarket documentation.

        knife supermarket download cron-delvalidate
        Downloading cron-delvalidate from Supermarket at version 0.1.3 to /home/username/chef-repo/.chef/cron-delvalidate-0.1.3.tar.gz
        Cookbook saved: /home/username/chef-repo/.chef/cron-delvalidate-0.1.3.tar.gz
      3. If the cookbook is downloaded as a .tar.gz file, use the tar command to extract it. Move the extracted directory to the cookbooks directory.

        tar -xf cron-delvalidate-0.1.3.tar.gz
        cp -r  cron-delvalidate ~/chef-repo/cookbooks/
      4. Review the cookbook’s default.rb file to see the recipe. This recipe is written in Ruby and demonstrates how a typical recipe is structured. It contains a cron job named clientrun. This job instantiates a new cron job to run the chef-client command on an hourly basis. It also removes the extraneous validation.pem file.

        File: ~/chef-repo/cookbooks/cron-delvalidate/recipes/default.rb
        # Cookbook Name:: cron-delvalidate
        # Recipe:: Chef-Client Cron & Delete Validation.pem
        cron "clientrun" do
          minute '0'
          hour '*/1'
          command "/usr/bin/chef-client"
          action :create
        file "/etc/chef/validation.pem" do
          action :delete
      5. Add the recipe to the run list for the node. In the following command, replace nodename with the name of the node.

        knife node run_list add nodename 'recipe[cron-delvalidate::default]'
          run_list: recipe[cron-delvalidate::default]
      6. Upload the cookbook and its recipes to the Chef Server.

        knife cookbook upload cron-delvalidate
        Uploading cron-delvalidate [0.1.3]
        Uploaded 1 cookbook.
      7. Run the chef-client command on the node using the knife ssh utility. This command causes the node to pull the recipes in its run list from the server. It also determines whether there are any updates. The Chef Server transmits the recipes to the target node. When the recipe runs, it deletes the file and installs a cron job to keep the node up to date in the future. In the following command, replace nodename with the actual name of the target node. Replace username with the name of a user account with sudo access. Enter the password for the account when prompted to do so.

        knife ssh 'name:nodename' 'sudo chef-client' -x username
        nodename Chef Infra Client, version 17.10.3
        nodename Patents:
        nodename Infra Phase starting
        nodename Resolving cookbooks for run list: ["cron-delvalidate::default"]
        nodename Synchronizing cookbooks:
        nodename   - cron-delvalidate (0.1.3)
        nodename Installing cookbook gem dependencies:
        nodename Compiling cookbooks...
        nodename Loading Chef InSpec profile files:
        nodename Loading Chef InSpec input files:
        nodename Loading Chef InSpec waiver files:
        nodename Converging 2 resources
        nodename Recipe: cron-delvalidate::default
        nodename   * cron[clientrun] action create
        nodename     - add crontab entry for cron[clientrun]
        nodename   * file[/etc/chef/validation.pem] action delete (up to date)
        nodename Running handlers:
        nodename Running handlers complete
        nodename Infra Phase complete, 1/2 resources updated in 03 seconds


      Chef is an infrastructure as code (IaC) application for automating the deployment and management of infrastructure nodes. The Chef architecture consists of the Chef Server, which stores all the procedures, and a Chef Workstation, where the infrastructure code is developed. The managed nodes communicate with the server to receive updates. To use Chef, install the Chef Server and Chef Workstation software. Share RSA keys between the server and workstation, and install version control and the Chef Knife utility on the workstation. Bootstrap the target nodes using the knife bootstrap utility. After a node is bootstrapped, it is possible to download cookbooks and recipes using the node’s run list. For more information, see the
      Chef documentation.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.

      Source link

      Use Keepalived Health Checks with BGP-based Failover

      Keepalived is one of the most commonly used applications that implements VRRP, a networking protocol that manages IP address assignment and ARP-based failover. It can be configured with additional health checks, such as checking the status of a service or running a custom script. When one of these health checks detects an issue, the instance changes to a fault state and failover is triggered. During these state transitions, additional task can be performed through custom scripts.

      The Linode platform is currently undergoing
      network infrastructure upgrades, which affects IP address assignment and failover. Once this upgrade occurs for the data center and hardware that your Compute Instances reside on, VRRP software like Keepalived can no longer directly manage failover. However, other features of Keepalived can still be used. For instance, Keepalived can continue to run health checks or VRRP scripts. It can then be configured to interact with whichever BGP daemon your system is using to manage IP address assignment and failover.

      This guide covers how to configure Keepalived with a simple health check and enable it to control
      lelastic, a BGP daemon created for the Linode platform.


      If you are migrating to BGP-based failover and currently have health checks configured with Keepalived, you can modify the steps in this guide to include your own settings.

      Configure IP Sharing and BGP Failover

      Before continuing, IP Sharing and BGP failover must be properly configured on both Compute Instances. To do this, follow the
      Configuring Failover on a Compute Instance guide, which walks you through the process of configuring failover with lelastic. If you decide to use a tool other than lelastic, you will need to make modifications to some of the commands or code examples provided in some of the following sections.

      Install and Configure Keepalived

      This section covers installing the keepalived software from your distribution’s repository. See
      Installing Keepalived on the official documentation if you prefer to install it from source.

      1. Log in to your Compute Instance over SSH. See
        Connecting to a Remote Server Over SSH for assistance.

      2. Install keepalived by following the instructions for your system’s distribution.

        Ubuntu and Debian:

        sudo apt update && sudo apt upgrade
        sudo apt install keepalived

        CentOS 8 Stream, CentOS/RHL 8 (including derivatives such as AlmaLinux 8 and Rocky Linux 8), Fedora:

        sudo dnf upgrade
        sudo dnf install keepalived

        CentOS 7:

        sudo yum update
        sudo yum install keepalived
      3. Create and edit a new keepalived configuration file.

        sudo nano /etc/keepalived/keepalived.conf
      4. Enter the following settings for your configuration into this file. Use the example below as a starting point, replacing each item below with the appropriate values for your Compute Instance. For more configuration options, see
        Configuration Options.

        • $password: A secure password to use for this keepalived configuration instance. The same password must be used for each Compute Instance you configure.

        • $ip-a: The IP address of this Compute Instance.

        • $ip-b: The IP address of the other Compute Instance.

        • $ip-shared: The Shared IP address.

        File: /etc/keepalived/keepalived.conf
        vrrp_instance example_instance {
            state BACKUP
            interface eth0
            virtual_router_id 10
            priority 100
            advert_int 1
            authentication {
                auth_type PASS
                auth_pass $password
            unicast_src_ip $ip-a
            unicast_peer {
            virtual_ipaddress {

        In the above configuration file, the state is set to BACKUP and the parameter nopreempt is included. When each Compute Instance uses these settings, failover is sticky. This means the Shared IP address remains routed to a Compute Instance until it enters a FAULT state, even if it is lower priority than the other Compute Instance. If you wish to prioritize one instance over the other, remove the nopreempt parameter, set one of the Compute Instances to a MASTER state, and adjust the PRIORITY parameter as desired.

      5. Enable and start the keepalived service.

        sudo systemctl enable keepalived
        sudo systemctl start keepalived
      6. Perform these steps again on the other Compute Instance you would like to configure.

      Create the Notify Script

      Keepalived can be configured to run notification scripts when the instance changes state (such as when entering a MASTER, BACKUP ,or FAULT state). These scripts can perform any action and are commonly used to interact with a service or modify network configuration files. For this guide, the scripts are used to update a log file and start or stop the BGP daemon that controls BGP failover on your Compute Instance.

      1. Create and edit the notify script.

        sudo nano /etc/keepalived/
      2. Copy and paste the following bash script into the newly created file. If you wish to control a BGP daemon other than lelastic, replace sudo systemctl restart lelastic and sudo systemctl stop lelastic with the appropriate commands for your service.

        File: /etc/keepalived/
        function check_state {
                local state=$1
                cat << EOF >> $keepalived_log
        Date:  $(date +'%d-%b-%Y %H:%M:%S')
        [INFO] Now $state
                if [[ "$state" == "Master" ]]; then
                        sudo systemctl restart lelastic
                        sudo systemctl stop lelastic
        function main {
                local state=$1
                case $state in
                        check_state Master;;
                        check_state Backup;;
                        check_state Fault;;
                        echo "[ERR] Provided arguement is invalid"
        main $1
      3. Make the file executable.

        sudo chmod +x /etc/keepalived/
      4. Modify the keepalived configuration files so that the notify script is used for each state change.

        File: /etc/keepalived/keepalived.conf
        vrrp_instance example_instance {
            notify_master "/etc/keepalived/ Master"
            notify_backup "/etc/keepalived/ Backup"
            notify_fault "/etc/keepalived/ Fault"
      5. Restart your BGP daemon and keepalived.

        sudo systemctl restart lelastic
        sudo systemctl restart keepalived
      6. View the log file to see if it was properly created and updated. If the notification script was successfully used, this log file should have an accurate timestamp and the current state of the instance.

        cat /tmp/keepalived.state
        Date:  14-Oct-2022 14:30:54
        [INFO] Now Master

      Configure the Health Check (VRRP Script)

      The next step is to configure Keepalived with a health check so that it can failover if it ever detects an issue. This is the primary reason you may want to use Keepalived alongside a BGP daemon. Keepalived can be configured to track a file (track_file), track a process (track_process), or run a custom script so that you can preform more complex health checks. When using a script, like is shown in this example, the script should return a 0 to indicate success and return any other value to indicate a failure. When a failure is detected, the state is changed to FAULT and the notify script runs.

      This guide helps you configure a custom script that detects if a file is present or not. If the file is present, the script returns a 1 to indicate a failure.

      1. Create and edit the health check script.

        sudo nano /etc/keepalived/
      2. Copy the following script and paste it into the file.

        File: /etc/keepalived/
        if [ -f $trigger ]; then
          exit 1
          exit 0
      3. Make the file executable.

        sudo chmod +x /etc/keepalived/
      4. Update the keepalived configuration file to define the VRRP script and enable your VRRP instance to use the script. The interval determines how often the script is run, fall determines how many times the script must return a failure before the state is changed to FAULT, and rise determines how many times a success is returned before the instance goes back to a BACKUP or MASTER state.

        File: /etc/keepalived/keepalived.conf
        vrrp_script check_for_file {
            script "/etc/keepalived/"
            interval 5
            fall 2
            rise 2
        vrrp_instance example_instance {
            track_script {
      5. Restart your BGP daemon and keepalived.

        sudo systemctl restart lelastic
        sudo systemctl restart keepalived
      6. To test this health check, create the trigger file on whichever Compute Instance is in a MASTER state.

        touch /etc/keepalived/trigger.file
      7. Check the log file on that Compute Instance to make sure it enters a FAULT state. Once it does, check the log file on the other Compute Instance to verify that it enters a MASTER state.

        tail -F /tmp/keepalived.state
        Date:  14-Oct-2022 14:30:54
        [INFO] Now Master

      By default, Keepalived attempts to run the scripts using a keepalived_script user. If that doesn’t exist, it uses the root user. Since running these scripts as the root user introduces many security concerns, this section discusses creating the keepalived_script user.

      1. Create a limited user account called keepalived_script. Since it is never used to log in, that feature can be disabled.

        sudo useradd -r -s /sbin/nologin -M keepalived_script
      2. Edit the sudoers file.

      3. Within this file, grant permission for the new user to restart and stop the BGP daemon. The example below uses lelastic.

        File: /etc/sudoers
        # User privilege specification
        root    ALL=(ALL:ALL) ALL
        keepalived_script ALL=(ALL:ALL) NOPASSWD: /usr/bin/systemctl restart lelastic, /usr/bin/systemctl stop lelastic
      4. Update the ownership of the /etc/keepalived directory (and all of the files within it).

        sudo chown -R keepalived_script:keepalived_script /etc/keepalived
      5. Once again, edit the Keepalived configuration file and paste the following snippet to the top of that file.

        File: /etc/keepalived/keepalived.conf
        global_defs {

      Example Configuration Files

      The links below contain complete working configuration files along with the specified example IP addresses. Please review them if you would like to see all of the recommended settings for each Compute Instance combined into a single file.

      • Shared IP: (configured on the loopback interface)
      • Compute Instance A: (
      • Compute Instance B: (

      Source link

      Beginner’s Guide to the WordPress .htaccess File

      Keeping your site safe should be a top priority for every administrator. WordPress is a secure platform out of the box, but that doesn’t mean it’s impervious to attacks. Fortunately, even if you aren’t a security expert, you can use a file called .htaccess to harden your site’s security policies.

      .htaccess is a configuration file for the Apache web server, which serves many WordPress sites. It’s a powerful tool that helps safeguard your site and boost its performance through some minor tweaks to its code. By editing this file, you can ban users, create redirects, prevent attacks, and even deny access to specific parts of your site.

      An Introduction to the .htaccess File

      .htaccess is short for “HyperText Access.” It’s a configuration file that determines how Apache-based servers interact with your site. In simpler terms, .htaccess controls how files in a directory can be accessed. You can think of it as a guard for your site because it decides who to let in and what they’re allowed to do.

      By default, an .htaccess file is typically included in your WordPress installation. The main purpose of this file is to improve security and performance. Plus, it also enables you to override your web server’s settings.

      You’ll most likely find your .htaccess file in your site’s root directory. Since .htaccess applies to both its own directory and any subdirectories within that main folder, it impacts your entire WordPress site.

      It’s also worth noting that the .htaccess file does not have a file extension. The period at the start simply makes sure the file remains hidden.

      How to Edit Your WordPress .htaccess File

      Editing the .htaccess file is, in practice, as simple as editing any other text file. However, because this is a core file, making changes to it can have unintended consequences.

      For this reason, it’s vitally important that you back up your site before you begin, regardless of whether you’re a beginner or an experienced developer.

      When you’re ready to edit your .htaccess file, you can access it using Secure File Transfer Protocol (SFTP) or Secure Shell (SSH). You will find .htaccess in your site’s root directory:

      WordPress .htaccess file

      Open the file using your preferred text editor, such as TextEdit or Notepad. If the file hasn’t been edited before, you’ll see the following default information:

      WordPress .htaccess file

      It’s important not to add or change anything between the # BEGIN and # END tags. Instead, all new code should be added after this block.

      At this point, all you need to do is add your code and save the file. When you’re including multiple new functions, it’s best to save and test each one separately. If an error occurs, this will make it much easier to troubleshoot which change caused the problem.

      While almost all WordPress installations will already contain an .htaccess file, in some cases, you may need to create one. You can do this using a text editor of your choice, as long as you save it with the right file name: .htaccess with no extension.

      It’s also important to configure the file’s permission settings correctly. You can then upload .htaccess to your site’s root directory.

      9 Things You Can Do With Your WordPress .htaccess File

      Now that you’re familiar with the .htaccess file, it’s time to get up close and personal. We’re going to introduce a number of ways you can easily boost your site’s security and performance by editing this file.

      Simply use the code snippets we’ve provided below, and remember to create a backup before you start!

      1. Deny Access to Parts of Your Site

      One of the most useful things you can do with .htaccess is deny access to certain pages and files. There are a few files you should consider hiding in this way for security reasons, such as your wp-config.php file.

      You can do this by adding the following code, which will cause a 404 error to appear if anybody attempts to view the file:

      <Files ~ "/wp-config.php">
      Order Allow,Deny
      Deny from All

      In cases where sensitive data should be hidden, it can be useful to restrict access to the corresponding directory. Since many WordPress sites use the same folder structure, this setup can leave your site vulnerable. If you add the following line, it will disable the default directory listing functionality:

      Options -Indexes

      This will stop users and robots from viewing your folder structure. If anybody tries to access it, they’ll be shown a 403 error page instead.

      2. Redirect and Rewrite URLs

      Creating redirects enables you to automatically send users to a specific page. Redirects can be particularly useful if a page has moved or been deleted, and you want users who attempt to access that page to be taken somewhere else.

      You can accomplish this with a plugin such as Redirection, but it’s also possible to do it by editing the .htaccess file. To create a redirect, use the following code:

      Redirect /oldfile.html

      You can probably see what’s going on here. The first part is the path to the old file, while the second part is the URL you want visitors to be redirected to.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      3. Force Your Site to Load Securely With HTTPS

      <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class=’embed-container’><iframe src=’’ frameborder=’0′ allowfullscreen></iframe></div>

      If you have added an SSL certificate to your domain, such as DreamHost’s free Let’s Encrypt certificate, it’s a good idea to force your site to load using HTTPS. This will ensure that your site is safer for both you and your visitors.

      You can make it happen by adding the following code:

      RewriteEngine On
      RewriteCond %{HTTPS} !=on
      RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

      Your site will now automatically redirect any HTTP requests and direct them to use HTTPS instead. For example, if a user tries to access, they will be automatically redirected to

      4. Change Caching Settings

      Browser caching is a process where certain website files are temporarily saved on a visitor’s local device to enable pages to load faster. Using .htaccess, you can change the amount of time that your files are stored in the browser cache until they are updated with new versions.

      There are a few different ways to do this, but for this example, we’ll use a function called mod_headers. The following code will change the maximum caching time for all jpg, jpeg, png, and gif files:

      <ifModule mod_headers.c>
      <filesMatch "\\.(jpg|jpeg|png|gif)$">
      Header set Cache-Control "max-age=2592000, public"

      We’ve set the maximum time to 2,592,000 seconds, which equates to 30 days. You can change this amount if you want, as well as the file extensions that will be affected. If you want to add different settings for different extensions, simply add more mod_header functions.

      5. Prevent Certain Script Injection Attacks

      Script injection (or ‘code injection’) attacks attempt to change how a site or application executes by adding invalid code. For example, someone might add a script to a text field on your site and then submit it, which could cause your site to actually run the script.

      You can add the following code to protect against certain types of script injection:

      Options +FollowSymLinks
      RewriteEngine On
      RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
      RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
      RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
      RewriteRule ^(.*)$ index.php [F,L]

      Your site should now be able to detect and stop script injection attempts and redirect the culprit to your index.php page.

      However, it’s important to note that this example will not protect against all types of injection attacks. While this particular code can certainly be useful, you should not use it as your only protection against this type of attack.

      6. Stop Username Enumeration Attacks

      Username enumeration is a process where usernames from your site are harvested by looking at each user’s author page. This is particularly problematic if someone manages to find your admin username, which makes it much easier for bots to gain access to your site.

      You can help prevent username enumeration by adding the following code:

      RewriteCond %{REQUEST_URI} !^/wp-admin [NC]
      RewriteCond %{QUERY_STRING} author=\d
      RewriteRule .* - [R=403,L]

      This will stop certain attempts to enumerate usernames and throw up a 403 error page instead. Bear in mind that this will not prevent all enumeration, and you should test your security thoroughly. We also recommend strengthening your login page further by implementing Multifactor Authentication.

      7. Prevent Image Hotlinking

      Image hotlinking is a common problem that happens when images on your server are being displayed on another site. You can stop this by adding the following code to .htaccess:

      RewriteEngine On
      RewriteCond %{HTTP_REFERER} !^$
      RewriteCond %{HTTP_REFERER} !^https://(www\.)?*$ [NC]
      RewriteRule \.(png|gif|jpg|jpeg)$ [R,L]

      Replace with your own domain, and this code will prevent images from loading on all other sites. Instead, the picture you specify on the last line will load. You can use this to send an alternative image to sites that try to display graphics from your server.

      Beware that this may cause issues when you might want images to appear externally, such as on search engines. You might also consider linking to a script instead of a static image, then respond with a watermarked image or an image containing an ad.

      8. Control Your File Extensions

      By using .htaccess, you can control how files of different extensions are loaded by your site. There’s a lot you can do with this feature, such as running files as PHP, but we’re just going to look at a basic example for now.

      The following code will remove the file extension from PHP files when they’re loaded. You can use this with any file type, as long as you replace all instances of “php” with the extension you want:

      RewriteEngine On
      RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\ HTTP/
      RewriteRule ^(.*)index$$1 [L,R=301]
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^([^/]+)/$$1 [L,R=301]
      RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)\.php\ HTTP/
      RewriteRule ^(.+)\.php$$1 [L,R=301]
      RewriteRule ^([a-z]+)$ /$1.php [L]

      This will cause all PHP files to load without displaying their extension in the URL. For example, the index.php file will appear as just index.

      9. Force Files to Download

      Finally, when a file is requested on your site, the default behavior is to display it in the browser. For example, if you’re hosting an audio file, it will start to play in the browser rather than being saved to the visitor’s computer.

      You can change this by forcing the site to download the file instead. This can be done with the following code:

      AddType application/octet-stream mp3

      In this example, we’ve used mp3 files, but you can use the same function for txt, mov, or any other relevant extension.

      Improve Your Site’s Security and Performance

      The .htaccess file provides flexibility for controlling how your web server behaves. You can also use it to increase your site’s performance and get more control over exactly who can access what information.

      With .htaccess, you can deny access to particular parts of your website. Additionally, it allows you to redirect URLs, force your site to load over HTTPS, and prevent some script injection attacks.

      Editing your .htaccess file is just one way to improve your site’s security. Choosing a secure WordPress hosting provider is another. Check out our DreamPress managed hosting plans to see how we can boost your website’s security and performance!

      Do More with DreamPress

      DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

      Managed WordPress Hosting - DreamPress

      Source link