Installing openssl in ubuntu

Installing OpenSSL on Ubuntu Linux

Category:

 Tutorials > Libraries > OpenSSL > Installation
This short tutorial shows you how to install OpenSSL on Ubuntu 12.04. The process is very simple. For this tutorial, I'll be installing openssl version 1.0.1g (released Apr 07, 2014). Linux kernel is 3.2.0-23-powerpc-smp. I have used a Mac Mini (powerpc/ppc architecture). GCC version number is 4.6.3. Your configuration may be different from mine but the installation steps below should work fine for most configurations.

OpenSSL:

According to openssl.org,
"The OpenSSL Project is a collaborative effort to develop a robust, commercial–grade, full–featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as a full-strength general purpose cryptography library. The project is managed by a worldwide community of volunteers that use the Internet to communicate, plan, and develop the OpenSSL toolkit and its related documentation.
Before starting, please check to see if there is a latest version available to download. Visit http://www.openssl.org/source/ to find out about the available versions. IMPORTANT: See Configuring Ubuntu Linux After Installation to install the development tools required to compile and install openssl from source code.
Steps to download, compile, and install are as follows. Note: Replace 1.0.1g with your version number:
  • Downloading OpenSSL:

    Run the command below,
    wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz
    Also, download the MD5 hash to verify the integrity of the downloaded file. In the same folder, where you downloaded the OpenSSL file, do the following:
    wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.md5
    
    md5sum openssl-1.0.1g.tar.gz
    
    cat openssl-1.0.1g.tar.gz.md5
    
    The last two commands (above) generate two strings of alpha-numeric characters. Check to see if both strings are identical or not. If not, repeat the steps above from "Downloading OpenSSL". If yes, your file has been downloaded properly. Please notethat if you are using openssl for a highly secure/critical setup (or for any other reason) then you should also check the PGP signatures (not covered in this tutorial for simplicity).
  • Extracting files from the downloaded package:

    tar -xvzf openssl-1.0.1g.tar.gz
    Now, enter the directory where the package is extracted.
    cd openssl-1.0.1g
  • Configuring OpenSSL:

    ./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl
    Replace "/usr/local/openssl" above with the directory path where you want to copy the files and folders. Note: check for any error message.
  • Compiling OpenSSL:

    make
    Note: check for any error message.
  • Installing OpenSSL:

    As root (for privileges on destination directory), run the following.
    With sudo,
    sudo make install
    Without sudo,
    make install
    Note: check for any error messages.
Thats it. OpenSSL has been successfully installed. You can run the version command to see if it worked or not.
/usr/local/openssl/bin/openssl version
OpenSSL 1.0.1g 7 Apr 2014

linux sysadmin tutorial for beginners

50 UNIX / Linux Sysadmin Tutorials

Merry Christmas and Happy Holidays to all TGS Readers.
To wrap this year, I’ve collected 50 UNIX / Linux sysadmin related tutorials that we’ve posted so far. This is lot of reading. Bookmark this article for your future reference and read it whenever you get free time.
  1. Disk to disk backup using dd command: dd is a powerful UNIX utility, which is used by the Linux kernel makefiles to make boot images. It can also be used to copy data. This article explains how to backup entire hard disk and create an image of a hard disk using dd command.
  2. 15 rsync command examples: Every sysadmin should master the usage of rsync. rsync utility is used to synchronize the files and directories from one location to another. First time, rsync replicates the whole content between the source and destination directories. Next time, rsync transfers only the changed blocks or bytes to the destination location, which makes the transfer really fast.
  3. Three sysadmin rules: If you are a sysadmin, you can’t (and shouldn’t) break these three sysadmin rules.
  4. User and group disk quota: This article explains how to setup user and group quote with soft limit, hard limit and grace period. For example, if you specify 2GB as hard limit, user will not be able to create new files after 2GB.
  5. Troubleshoot using dmesg: Using dmesg you can view boot up messages that displays information about the hardware devices that the kernel detects during boot process. This can be helpful during troubleshooting process.
  6. RPM package management examples: 15 examples provided in this article explains everything you need to know about managing RPM packages on redhat based system (including CentOS).
  7. 10 netstat examples: Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc.,
  8. Manage packages using apt-* commands: These 13 practical examples explains how to manage packages using apt-get, apt-cache, apt-file and dpkg commands.
  9. Modprobe command examples: modprobe utility is used to add loadable modules to the Linux kernel. You can also view and remove modules using modprobe command.
  10. Ethtool examples: Ethtool utility is used to view and change the ethernet device parameters. These examples will explain how you can manipulate your ethernet NIC card using ethtool.
  11. NFS mount using exportfs: This is a linux beginners guide to NFS mount using exportfs. This explains how to export a file system to a remote machine and mount it both temporarily and permanently.
  12. Change timezone: Depending on your Linux distribution, use one of the methods explained in this article to change the timezone on your system.
  13. Install phpMyAdmin: phpMyAdmin is a web-based tool written in PHP to manage the MySQL database. Apart from viewing the tables (and other db objects), you can perform lot of DBA functions through the web based interface. You can also execute any SQL query from the UI.
  14. Setup squid to control internet access: Squid is a proxy caching server. You can use squid to control internet access at work. This guide will give a jump-start on how to setup squid on Linux to restrict internet access in an network.
  15. Add new swap space: Use dd, mkswap and swapon commands to add swap space. You can either use a dedicated hard drive partition to add new swap space, or create a swap file on an existing filesystem and use it as swap space.
  16. Install and configure snort: Snort is a free lightweight network intrusion detection system for both UNIX and Windows. This article explains how to install snort from source, write rules, and perform basic testing.
  17. Register RHEL/OEL linux to support: If you have purchased support from Oracle for your Linux, you can register to oracle support network (ULN) using up2date as explained here.
  18. tftpboot setup: You can install Linux from network using PXE by installing and configuring tftpboot server as explained here.
  19. Delete all iptables rules: When you are starting to setup iptables, you might want to delete (flush) all the existing iptables as shown here.
  20. Disable ping replies: Someone can flood the network with ping -f. If ping reply is disabled as explained here we can avoid this flooding.
  21. Block ip address using fail2ban: Fail2ban is a intrusion preventon framework that scans log files for various services ( SSH, FTP, SMTP, Apache, etc., ) and bans the IP that makes too many password failures. It also updates iptles firewall rules to reject these ip addresses.
  22. Package management using dpkg: On debian, you can install or remove deb packages using dpkg utility.
  23. Alfresco content management system: Alfresco is the best open source content management system. Everything you need to know to install and configure Alfresco is explained here.
  24. Bugzilla bug tracking system: Bugzilla is the best open source bug tracking system. Everything you need to know to install and configure Bugzilla is explained here.
  25. Rpm, deb, dpot and msi packages: This article explains how to view and extract files from various package types used by different Linux / UNIX distributions.
  26. Backup using rsnapshot: You can backup either a local host or remote host using rsnapshot rsync utility. rsnapshot uses the combination of rsync and hard links to maintain full-backup and incremental backups. Once you’ve setup and configured rsnapshot, there is absolutely no maintenance involved in it. rsnapshot will automatically take care of deleting and rotating the old backups.
  27. Create Linux user: This article explains how to create users with default configuration, create users with custom configuration, create users interactively, and creating users in bulk.
  28. Mount and view ISO file: ISO files are typically used to distribute the operating system. Most of the linux operating system that you download will be on ISO format. This explains how to view and mount any ISO file both as regular use and as root user.
  29. Manage password expiration and aging: Linux chage command can be used to perform several practical password aging activities including how-to force users to change their password.
  30. ifconfig examples: Interface configurator command ifconfig is used to initialize the network interface and to enable or disable the interfaces as shown in these 7 examples.
  31. Oracle db startup an sthudown: Every sysadmin should know some basic DBA operations. This explains how to shutdown and start the oracle database.
  32. PostgreSQL install and configure: Similar to mySQL, postgreSQL is very famous and feature packed free and open source database. This is a jumpstart guide to install and configure postgresql from source on Linux.
  33. Magic SysRq key: Have you wondered what the SysRq key on your keyboard does. Here is one use for it. You can safely reboot Linux using the magic SysRq key as explained here.
  34. Wakeonlan Tutorial: Using Wakeonlan WOL, you can turn on the remote servers where you don’t have physical access to press the power button.
  35. List hardware spec using lshw: ls+hw = lshw, which lists the hardware specs of your system.
  36. View hardware spec using dmidecode: dmidecode command reads the system DMI table to display hardware and BIOS information of the server. Apart from getting current configuration of the system, you can also get information about maximum supported configuration of the system using dmidecode. For example, dmidecode gives both the current RAM on the system and the maximum RAM supported by the system.
  37. Use the support effectively: Companies spend lot of cash on support mainly for two reasons: 1) To get help from vendors to fix critical production issues 2) To keep up-to-date with the latest version of the software and security patches released by the vendors. In this article, I’ve given 10 practical tips for DBAs, sysadmins and developers to use their hardware and software support effectively.
  38. Install/Upgrade LAMP using Yum: Installing LAMP stack using yum is a good option for beginners who don’t feel comfortable installing from source. Also, Installing LAMP stack using yum is a good choice, if you want to keep things simple and just use the default configuration.
  39. Template to track your hardware assests: If you are managing more than one equipment in your organization, it is very important to document and track ALL information about the servers effectively. In this article, I have listed 36 attributes that needs to be tracked for your equipments, with an explanation on why it needs to be tracked. I have also provided a spreadsheet template with these fields that will give you a jumpstart.
  40. Disable SELinux: If you don’t understand how SELinux works and the fundamental details on how to configure it, keeping it enabled will cause lot of issues. Until you understand the implementation details of SELinux you may want to disable it to avoid some unnecessary issues as explained here.
  41. Install PHP5 from source: This is a step-by-step guide to install PHP5 from source on UNIX environment.
  42. Install MySQL from source: This is a step-by-step guide to install MySQL from source on UNIX environment.
  43. Launch Linux clients on windows: If you are using SSH client to connect to Linux server from your Windows laptop, sometimes it may be necessary to launch UI application on the remote Linux server, but to display the UI on the windows laptop. Cygwin can be used to install software on Linux from Windows and launch Linux X client software on Windows.
  44. IPCS: IPC allows the processes to communicate with each another. The process can also communicate by having a file accessible to both the processes. Processes can open, and read/write the file, which requires lot of I/O operation that consumes time. This explains different types of IPCS and provides 10 IPCS command examples.
  45. Logical Volume Manager: Using LVM we can create logical partitions that can span across one or more physical hard drives.You can create and manage LVM using vgcreate, lvcreate, and lvextend lvm2 commands as shown here.
  46. 15 Tcpdump examples: tcpdump is a network packet analyzer. tcpdump allows us to save the packets that are captured, so that we can use it for future analysis. The saved file can be viewed by the same tcpdump command. We can also use open source software like wireshark to read the tcpdump pcap files.
  47. Manage partition using fdisk: Using fdisk you can create a maximum of four primary partition, delete an existing partition, or change existing partition. Using fidsk you are allowed to create a maximum of four primary partition, and any number of logical partitions, based on the size of the disk.
  48. VMWare fundamentals: At some point every sysadmin should deal with virtualization. VMWare is a very popular choise to virtualize your server environment. This article will provide the fundamental information for you to get a jumpstart on VMWare.
  49. Rotate the logs automatically: Manging log files is an importat part of sysadmin life. logrotate make it easy by allowing you to setup automatica log rotation based on several configurations. Using logrotate you can also configure it to execute custom shell scripts immediately after log rotation.
  50. Passwordless SSH login setup: Using ssh-keygen and ssh-copy-id you can setup passwordless login to remote Linux server. ssh-keygen creates the public and private keys. ssh-copy-id copies the local-host’s public key to the remote-host’s authorized_keys file.

reference:click here

Nginx installation by binary



Learn Nginx configuration during run time
compile time option for nginx installation
Confguring nginx

Some Quick steps
Before we understand what is nginx, we should know how to pronounce nginx.
Its not N G I N X. nginx is pronounced as “Engine X”.
nginx is short form after you remove both the e’s from “Engine X”.
nginx is an open source web server that is similar to Apache, but very light weight. nginx is both web server and reverse proxy server.

The following are some of the features of nginx:
  • It serves static and index files
  • Reverse proxy with caching
  • Supports SSL
  • Simple load balancing with fault tolerance
  • Both name-based and ip-based virtual server can be configured
  • HTTP basic authentication
  • Supports rewrite module
  • Supports gzip, XSLT, SSI and image resizing filters
  • All the main mail proxy server features are supported
  • and lot more..
This is part of an ongoing series of articles on nginx.
Let us get started by installing nginx and get it up and running, which takes only 5 minutes.

1. Download nginx

Download nginx from here, or use wget as shown below. The current stable version is nginx 1.0.5
cd
wget http://nginx.org/download/nginx-1.0.5.tar.gz
tar xvfz nginx-1.0.5.tar.gz
cd nginx-1.0.5

2. Install nginx

There are lot of options that you can pass to ./configure. To identify list of all the configuration options do the following.
./configure --help
The following are some of the http modules that are automatically enabled. If you need to disable them, yo should pass “–without-http_[module_name]” to the ./configure option. For example, to disable “proxy_module”, you should do ./configure –without-http_proxy_module.
  • charset_module – HTTP Character set module
  • gzip_module – HTTP gzip module for compression
  • ssi_module – Server side include modules
  • auth_basic_module – HTTP Basic authentication modules.
  • autoindex_module – Auto index
  • rewrite_module – HTTP rewrite that supports rewrite rules
  • proxy_module – HTTP reverse proxy module
  • fastcgi_module – Support for fastcgi
  • memcached_module – Memcached module for nginx
  • ..
Following are some of the httpd modules that are not automatically enabled. If you need to enable them, you should pass “–with-http_[module_name]” to the ./configure option. For example, to enable SSL in nginx, you should do “./configure –with-http_ssl_module”.
  • ssl_module – Support for Secure Socket Layer (SSL) module
  • xslt_module – Support for Extensible Stylesheet Language Transformations (XSLT) module
  • perl_module – Support for Perl
  • ..
To begin with, install nginx with the default configuration options by doing ./configure as shown below.
./configure
make
make install
During ./configure, you might get the “./configure: error: the HTTP rewrite module requires the PCRE library.” error message about missing PCRE library that is required by nginx http rewrite module.
To solve the problem, either install “pcre” and “pcre-devel” packages on your Linux, or disable the rewrite module by doing “./configure –without-http_rewrite_module”
nginx will be installed under /usr/local/nginx as shown by the ./configure output.
Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + md5: using system crypto library
  + sha1: using system crypto library
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

3. Change the Default nginx Listen Port

Nginx is configured to listen by default on port 80. If you are installing this on a machine for testing purpose, that already has an apache server running, you should change the nginx listen port.
Similar to apache’s httpd.conf file, nginx has nginx.conf file located under /usr/local/nginx/conf.
In the server section of nginx.conf, change the port 80 to 8081.
# vi /usr/local/nginx/conf/nginx.conf
    server {
        listen       8081;
        server_name  localhost;

4. Start Nginx Server

nginx executable is located under /usr/local/nginx/sbin directory. Just call this executable to start the nginx server.
cd /usr/local/nginx/sbin
./nginx
Once you start this, you’ll see the nginx “master process” and “worker process” if you do ps.
# ps -ef | grep -i nginx
root     18596 13:16 nginx: master process ./nginx
nobody   18597 13:16 nginx: worker process
After you start the nginx server, go to http://your-ip-address/ (or http://your-ip-address:8081, if you changed the listen directive in nginx.conf), you should see the default nginx index.html, which should say “Welcome to nginx!”

5. Stop Nginx Server

To stop the nginx server, do the following.
cd /usr/local/nginx/sbin
./nginx -s stop
To view the current version of nginx, do the following:
# ./nginx -v
nginx: nginx version: nginx/1.0.5
To debug issues, view the error.log and access.log files located under /usr/local/nginx/logs
# ls /usr/local/nginx/logs/
access.log
error.log
nginx.pid

Ansible playbook

Ansible is a configuration management and provisioning tool, similar to Chef, Puppet or Salt.
I've found it to be one of the simplest and the easiest to get started with. A lot of this is because it's "just SSH"; It uses SSH to connect to servers and run the configured Tasks.
One nice thing about Ansible is that it's very easy to convert bash scripts (still a popular way to accomplish configuration management) into Ansible Tasks. Since it's primarily SSH based, it's not hard to see why this might be the case - Ansible ends up running the same commands.
We could just script our own provisioners, but Ansible is much cleaner because it automates the process of getting contextbefore running Tasks. With this context, Ansible is able to handle most edge cases - the kind we usually take care of with longer and increasingly complex scripts.
Ansible Tasks are idempotent. Without a lot of extra coding, bash scripts are usually not safety run again and again. Ansible uses "Facts", which is system and environment information it gathers ("context") before running Tasks.
Ansible uses these facts to check state and see if it needs to change anything in order to get the desired outcome. This makes it safe to run Ansible Tasks against a server over and over again.
Here I'll show how easy it is to get started with Anible. We'll start basic and then add in more features as we improve upon our configurations.

Install

Of course we need to start by installing Ansible. Tasks can be run off of any machine Ansible is installed on.
This means there's usually a "central" server running Ansible commands, although there's nothing particularly special about what server Ansible is installed on. Ansible is "agentless" - there's no central agent(s) running. We can even run Ansible from any server; I often run Tasks from my laptop.
Here's how to install Ansible on Ubuntu 14.04. We'll use the easy-to-remember ppa:ansible/ansible repository as per the official docs.
sudo apt-add-repository -y ppa:ansible/ansible
sudo apt-get update
sudo apt-get install -y ansible

Managing Servers

Ansible has a default inventory file used to define which servers it will be managing. After installation, there's an example one you can reference at /etc/ansible/hosts.
I usually copy and move the default one so I can reference it later:
sudo mv /etc/ansible/hosts /etc/ansible/hosts.orig
Then I create my own inventory file from scratch. After moving the example inventory file, create a new /etc/ansible/hostsfile, and define some servers to manage. Here's we'll define two servers under the "web" label:
[web]
192.168.22.10
192.168.22.11
That's good enough for now. If needed, we can define ranges of hosts, multiple groups, reusable variables, and use other fancy setups, including creating a dynamic inventory.
For testing this article, I created a virtual machine, installed Ansible, and then ran Ansible Tasks directly on that server. To do this, my hosts inventory file simply looked like this:
[local]
127.0.0.1
This makes testing pretty easy - I don't need to setup multiple servers or virtual machines. A consequence of this is that I need to tell Ansible to run Tasks as user "vagrant" and use password-based (rather than key-based) authentication.

Basic: Running Commands

Once we have an inventory configured, we can start running Tasks against the defined servers.
Ansible will assume you have SSH access available to your servers, usually based on SSH-Key. Because Ansible uses SSH, the server it's on needs to be able to SSH into the inventory servers. It will attempt to connect as the current user it is being run as. If I'm running Ansible as user vagrant, it will attempt to connect as user vagrant on the other servers.
If Ansible can directly SSH into the managed servers, we can run commands without too much fuss:
$ ansible all -m ping
127.0.0.1 | success >> {
    "changed": false,
    "ping": "pong"
}
We can see the output we get from Ansible is some JSON which tells us if the Task made any changes and the result.
If we need to define the user and perhaps some other settings in order to connect to our server, we can. When testing locally on Vagrant, I use the following:
ansible all -m ping -s -k -u vagrant
Let's cover these commands:
  • all - Use all defined servers from the inventory file
  • -m ping - Use the "ping" module, which simply runs the ping command and returns the results
  • -s - Use "sudo" to run the commands
  • -k - Ask for a password rather than use key-based authentication
  • -u vagrant - Log into servers using user vagrant

Modules

Ansible uses "modules" to accomplish most of its Tasks. Modules can do things like install software, copy files, use templates and much more.
Modules are the way to use Ansible, as they can use available context ("Facts") in order to determine what actions, if any need to be done to accomplish a Task.
If we didn't have modules, we'd be left running arbitrary shell commands like this:
ansible all -s -m shell -a 'apt-get install nginx'
Here, the sudo apt-get install nginx command will be run using the "shell" module. The -a flag is used to pass any arguments to the module. I use -s to run this command using sudo.
However this isn't particularly powerful. While it's handy to be able to run these commands on all of our servers at once, we still only accomplish what any bash script might do.
If we used a more appropriate module instead, we can run commands with an assurance of the result. Ansible modules ensure indempotence - we can run the same Tasks over and over without affecting the final result.
For installing software on Debian/Ubuntu servers, the "apt" module will run the same command, but ensure idempotence.
ansible all -s -m apt -a 'pkg=nginx state=installed update_cache=true'
127.0.0.1 | success >> {
    "changed": false
}
This will use the apt module to update the repository cache and install Nginx (if not installed).
The result of running the Task was "changed": false. This shows that there were no changes; I had already installed Nginx. I can run this command over and over without worrying about it affecting the desired result.
Going over the command:
  • all - Run on all defined hosts from the inventory file
  • -s - Run using sudo
  • -m apt - Use the apt module
  • -a 'pkg=nginx state=installed update_cache=true' - Provide the arguments for the apt module, including the package name, our desired end state and whether to update the package repository cache or not
We can run all of our needed Tasks (via modules) in this ad-hoc way, but let's make this more managable. We'll move this Task into a Playbook, which can run and coordinate multiple Tasks.

Basic Playbook

Playbooks can run multiple Tasks and provide some more advanced functionality that we would miss out on using ad-hoc commands. Let's move the above Task into a playbook.
Playbooks and Roles in Ansible all use Yaml.
Create file nginx.yml:
---
- hosts: local
  tasks:
   - name: Install Nginx
     apt: pkg=nginx state=installed update_cache=true
This Task does exactly the same as our ad-hoc command, however I chose to specify my "local" group of servers rather than "all". We can run it with the ansible-playbook command:
$ ansible-playbook -s nginx.yml

PLAY [local] ******************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [Install Nginx] *********************************************************
ok: [127.0.0.1]

PLAY RECAP ********************************************************************
127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0
Use use -s to tell Ansible to use sudo again, and then pass the Playbook file.
We get some useful feedback while this runs, including the Tasks Ansible runs and their result. Here we see all ran OK, but nothing was changed. I have Nginx installed already.
I used the command $ ansible-playbook -s -k -u vagrant nginx.yml to run this playbook locally on my Vagrant installation.

Handlers

A Handler is exactly the same as a Task (it can do anything a Task can), but it will run when called by another Task. You can think of it as part of an Event system; A Handler will take an action when called by an event it listens for.
This is useful for "secondary" actions that might be required after running a Task, such as starting a new service after installation or reloading a service after a configuration change.
---
- hosts: local
  tasks:
   - name: Install Nginx
     apt: pkg=nginx state=installed update_cache=true
     notify:
      - Start Nginx

  handlers:
   - name: Start Nginx
     service: name=nginx state=started
We can add a notify directive to the installation Task. This notifies any Handler named "Start Nginx" after the Task is run.
Then we can create the Handler called "Start Nginx". This Handler is the Task called when "Start Nginx" is notified.
This particular Handler uses the Service module, which can start, stop, restart, reload (and so on) system services. Here we simply tell Ansible that we want Nginx to be started.
Note that Ansible has us define the state you wish the service to be in, rather than defining the change you want. Ansible will decide if a change is needed, we just tell it the desired result.
Let's run this Playbook again:
$ ansible-playbook -s nginx.yml

PLAY [local] ******************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [Install Nginx] *********************************************************
ok: [127.0.0.1]

NOTIFIED: [nginx | Start Nginx] ***********************************************
ok: [127.0.0.1]

PLAY RECAP ********************************************************************
127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0
We get the similar output, but this time the Handler was run.
Notifiers are only run if the Task is run. If I already had Nginx installed, the Install Nginx Task would not be run and the notifier would not be called.
We can use Playbooks to run multiple Tasks, add in variables, define other settings and even include other playbooks.

More Tasks

Next we can add a few more Tasks to this Playbook and explore some other functionality.
---
- hosts: local
  vars:
   - docroot: /var/www/serversforhackers.com/public
  tasks:
   - name: Add Nginx Repository
     apt_repository: repo='ppa:nginx/stable' state=present
     register: ppastable

   - name: Install Nginx
     apt: pkg=nginx state=installed update_cache=true
     when: ppastable|success
     register: nginxinstalled
     notify:
      - Start Nginx

   - name: Create Web Root
     when: nginxinstalled|success
     file: dest={{ '{{' }} docroot {{ '}}' }} mode=775 state=directory owner=www-data group=www-data
     notify:
      - Reload Nginx

  handlers:
   - name: Start Nginx
     service: name=nginx state=started

    - name: Reload Nginx
      service: name=nginx state=reloaded
There are now three Tasks:
  • Add Nginx Repository - Add the Nginx stable PPA to get the latest stable version of Nginx, using the apt_repository module.
  • Install Nginx - Installs Nginx using the Apt module.
  • Create Web Root - Finally, create a web root directory.
Also new here are the register and when directives. These tell Ansible to run a Task when something else happens.
The "Add Nginx Repository" Task registers "ppastable". Then we use that to inform the Install Nginx Task to only run when the registered "ppastable" Task is successful. This allows us to conditionally stop Ansible from running a Task.
We also use a variable. The docroot variable is defined in the var section. It's then used as the destination argument of the file module which creates the defined directory.
This playbook can be run with the usual command:
ansible-playbook -s nginx.yml

# Or, as I ran on my Vagrant machine:
ansible-playbook -s -k -u vagrant nginx.yml
Next we'll take Ansible further and by organizing the Playbook into a Role while also showing some more functionality.

Roles

Roles are good for organizing multiple, related Tasks and encapsulating data needed to accomplish those Tasks. For example, installing Nginx may involve adding a package repository, installing the package and setting up configuration. We've seen installation in action in a Playbook, but once we start configuring our installations, the Playbooks tend to get a little more busy.
The configuration portion often requires extra data such as variables, files, dynamic templates and more. These tools can be used with Playbooks, but we can do better immediately by organizing related Tasks and data into one coherent structure: a Role.
Roles have a directory structure like this:
rolename
 - files
 - handlers
 - meta
 - templates
 - tasks
 - vars
Within each directory, Ansible will search for and read any Yaml file called main.yml automatically.
We'll break apart our nginx.yml file and put each component within the corresponding directory to create a cleaner and more complete provisioning toolset.

Files

First, within the files directory, we can add files that we'll want copied into our servers. For Nginx, I often copy H5BP's Nginx component configurations. I simply download the latest from Github, make any tweaks I want, and put them into the filesdirectory.
nginx
 - files
 - - h5bp
As we'll see, these configurations will be added via the copy module.

Handlers

Inside of the handlers directory, we can put all of our Handlers that were once within the nginx.yml Playbook.
Inside of handlers/main.yml:
---
- name: Start Nginx
  service: name=nginx state=started

- name: Reload Nginx
  service: name=nginx state=reloaded
Once these are in place, we can reference them from other files freely.

Meta

The main.yml file within the meta directory contains Role meta data, including dependencies.
If this Role depended on another Role, we could define that here. For example, I have the Nginx Role depend on the SSL Role, which installs SSL certificates.
---
dependencies:
  - { role: ssl }
If I called the "nginx" Role, it would attempt to first run the "ssl" Role.
Otherwise we can omit this file, or define the Role as having no dependencies:
---
dependencies: []

Template

Template files can contain template variables, based on Python's Jinja2 template engine. Files in here should end in .j2, but can otherwise have any name. Similar to files, we won't find a main.yml file within the templates directory.
Here's an example Nginx virtual host configuration. Note that it uses some variables which we'll define later in thevars/main.yml file.
Nginx virtual host file found at templates/serversforhackers.com.conf:
server {
    # Enforce the use of HTTPS
    listen 80 default_server;
    server_name *.{{ '{{' }} domain {{ '}}'  }};
    return 301 https://{{ '{{' }} domain {{ '}}'  }}$request_uri;
}

server {
    listen 443 default_server ssl;

    root /var/www/{{ '{{' }} domain {{ '}}'  }}/public;
    index index.html index.htm index.php;

    access_log /var/log/nginx/{{ '{{' }} domain {{ '}}'  }}.log;
    error_log  /var/log/nginx/{{ '{{' }} domain {{ '}}'  }}-error.log error;

    server_name {{ '{{' }} domain {{ '}}'  }};

    charset utf-8;

    include h5bp/basic.conf;

    ssl_certificate           {{ '{{' }} ssl_crt {{ '}}' }};
    ssl_certificate_key       {{ '{{' }} ssl_key {{ '}}' }};
    include h5bp/directive-only/ssl.conf;

    location /book {
        return 301 http://book.{{ '{{' }} domain {{ '}}'  }};
    }

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt  { log_not_found off; access_log off; }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;

        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;

        include fastcgi_params; # fastcgi.conf for version 1.6.1+
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param ENV production;
    }

    # Nginx status
    # Nginx Plus only
    #location /status {
    #    status;
    #    status_format json;
    #    allow 127.0.0.1;
    #    deny all;
    #}

    location ~ ^/(fpmstatus|fpmping)$ {
        access_log off;
        allow 127.0.0.1;
        deny all;
        include fastcgi_params; # fastcgi.conf for version 1.6.1+
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }
}
This is a fairly standard Nginx configuration for a PHP application. There are three variables used here:
  • domain
  • ssl_crt
  • ssl_key
These three will be defined in the variables section.

Variables

Before we look at the Tasks, let's look at variables. The vars directory contains a main.yml file which simply lists variables we'll use. This provides a convenient place for us to change configuration-wide settings.
Here's what the vars/main.yml file might look like:
---
domain: serversforhackers.com
ssl_key: /etc/ssl/sfh/sfh.key
ssl_crt: /etc/ssl/sfh/sfh.crt
These are three variables which we can use elsewhere in this Role. We saw them used in the template above, but we'll see them in our defined Tasks as well.

Tasks

Let's finally see this all put together into a series of Tasks.
Inside of tasks/main.yml:
---
- name: Add Nginx Repository
  apt_repository: repo='ppa:nginx/stable' state=present
  register: ppastable

- name: Install Nginx
  apt: pkg=nginx state=installed update_cache=true
  when: ppastable|success
  register: nginxinstalled
  notify:
    - Start Nginx

- name: Add H5BP Config
  when: nginxinstalled|success
  copy: src=h5bp dest=/etc/nginx owner=root group=root

- name: Disable Default Site
  when: nginxinstalled|success
  file: dest=/etc/nginx/sites-enabled/default state=absent

- name: Add SFH Site Config
  when: nginxinstalled|success
  register: sfhconfig
  template: src=serversforhackers.com.j2 dest=/etc/nginx/sites-available/{{ '{{' }} domain {{ '}}'  }}.conf owner=root group=root

- name: Enable SFH Site Config
  when: sfhconfig|success
  file: src=/etc/nginx/sites-available/{{ '{{' }} domain {{ '}}'  }}.conf dest=/etc/nginx/sites-enabled/{{ '{{' }} domain {{ '}}'  }}.conf state=link


- name: Create Web root
  when: nginxinstalled|success
  file: dest=/var/www/{{ '{{' }} domain {{ '}}'  }}/public mode=775 state=directory owner=www-data group=www-data
  notify:
    - Reload Nginx

- name: Web Root Permissions
  when: nginxinstalled|success
  file: dest=/var/www/{{ '{{' }} domain {{ '}}'  }} mode=775 state=directory owner=www-data group=www-data recurse=yes
  notify:
    - Reload Nginx
This is a longer series of Tasks, which makes for a more complete installation of Nginx. The Tasks, in order of appearance, accomplish the following:
  • Add the nginx/stable repository
  • Install & start Nginx, register successful installation to trigger remaining Tasks
  • Add H5BP configuration
  • Disable the default virtual host by removing the symlink to the default file from the sites-enabled directory
  • Copy the serversforhackers.com.conf.j2 virtual host template into the Nginx configuration
  • Enable the virtual host configuration by symlinking it to the sites-enabled directory
  • Create the web root
  • Change permission for the project root directory, which is one level above the web root created previously
There's some new modules (and new uses of some we've covered), including copytemplate, & file. By setting the arguments for each module, we can do some interesting things such as ensuring files are "absent" (delete them if they exist) viastate=absent, or create a file as a symlink via state=link. You should check the docs for each module to see what interesting and useful things you can accomplish with them.

Running the Role

Before running the Role, we need to tell Ansible where our Roles are located. In my Vagrant server, they are located within/vagrant/ansible/roles. We can add this file path to the /etc/ansible/ansible.cfg file:
roles_path    = /vagrant/ansible/roles
Assuming our nginx Role is located at /vagrant/ansible/roles/nginx, we'll be all set to run this Role!
Remove the ssl dependency from meta/main.yml before running this Role if you are following along.
Let's create a "master" yaml file which defines the Roles to use and what hosts to run them on:
File server.yml:
---
- hosts: all
  roles:
    - nginx
In my Vagrant example, I use the host "local" rather than "all".
Then we can run the Role(s):
ansible-playbook -s server.yml

# Or as I do with my Vagrant VM:
ansible-playbook -s -k -u vagrant server.yml
Here's the output from the run of the Nginx Role:
PLAY [all] ********************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [nginx | Add Nginx Repository] ******************************************
changed: [127.0.0.1]

TASK: [nginx | Install Nginx] *************************************************
changed: [127.0.0.1]

TASK: [nginx | Add H5BP Config] ***********************************************
changed: [127.0.0.1]

TASK: [nginx | Disable Default Site] ******************************************
changed: [127.0.0.1]

TASK: [nginx | Add SFH Site Config] *******************************************
changed: [127.0.0.1]

TASK: [nginx | Enable SFH Site Config] ****************************************
changed: [127.0.0.1]

TASK: [nginx | Create Web root] ***********************************************
changed: [127.0.0.1]

TASK: [nginx | Web Root Permissions] ******************************************
ok: [127.0.0.1]

NOTIFIED: [nginx | Start Nginx] ***********************************************
ok: [127.0.0.1]

NOTIFIED: [nginx | Reload Nginx] **********************************************
changed: [127.0.0.1]

PLAY RECAP ********************************************************************
127.0.0.1                  : ok=8   changed=7   unreachable=0    failed=0
Awesome, we put all the various components together into a coherent Role and now have Nginx installed and configured!