Ansible installation and configuration on Ubuntu

Ansible is a tool for managing a large number of servers centrally. With Ansible playbooks, you can create automated tasks to run against your servers remotely from a central control node. Installing Ansible on Ubuntu requires the following prerequisites and installation commands to be followed promptly.

1. Root privilege.

ansible@ansible-VirtualBox:~$ sudo -i
[sudo] password for ansible:

2. Install update packages and upgrades

root@ansible-VirtualBox:/# apt-get update && apt-get upgrade

3. One of those many ways to get Ansible running for Ubuntu is to install the project’s PPA (personal package archive), i.e the software-properties-common to your server.

root@ansible-VirtualBox:~# apt-get install software-properties-common
Reading package lists… Done
Building dependency tree
Reading state information… Done
software-properties-common is already the newest version (
software-properties-common set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.

4. After installing this package, add the Ansible PPA from the repository using this command.

root@ansible-VirtualBox:~# apt-add-repository ppa:ansible/ansible

Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications‚ automate in a language that approaches plain English, using SSH, with no agents to install on remote systems.
More info:
Press [ENTER] to continue or ctrl-c to cancel adding it

gpg: keyring `/tmp/tmpooow5ue_/secring.gpg' created
gpg: keyring `/tmp/tmpooow5ue_/pubring.gpg' created
gpg: requesting key 7BB9C367 from hkp server
gpg: /tmp/tmpooow5ue_/trustdb.gpg: trustdb created
gpg: key 7BB9C367: public key "Launchpad PPA for Ansible, Inc." imported
gpg: Total number processed: 1
gpg: imported: 1  (RSA: 1)                                  

Note: where you have to press enter to accept the PPA added process to continue.

5. Once again, run the apt-get update utility to have the system package refreshed to be aware of the newly added PPA.

root@ansible-VirtualBox:/# apt-get update

6. Now install Ansible software.

root@ansible-VirtualBox:/# apt-get install ansi
ansible ansible-fireball ansible-node-fireball ansiweather
root@ansible-VirtualBox:/# apt-get install ansible
Reading package lists… Done
Building dependency tree
Reading state information… Done
The following additional packages will be installed:
python-crypto python-ecdsa python-httplib2 python-jinja2 python-markupsafe python-paramiko
python-pkg-resources python-setuptools python-six python-yaml sshpass
Suggested packages:
python-crypto-dbg python-crypto-doc python-jinja2-doc python-setuptools-doc
The following NEW packages will be installed:
ansible python-crypto python-ecdsa python-httplib2 python-jinja2 python-markupsafe
python-paramiko python-pkg-resources python-setuptools python-six python-yaml sshpass
0 upgraded, 12 newly installed, 0 to remove and 3 not upgraded.
Need to get 2.182 kB of archives.
After this operation, 13,8 MB of additional disk space will be used.
Do you want to continue? [Y/n]

Note: Just hit enter of “y” key to continue with the installation.

7. SSH Key Setup: SSH keys allow communication (auth) between two hosts without the need for a password. SSH key authentication uses two keys, a private key, and a public key.

Ansible communicates with servers via SSH on Linux. While it certainly has the ability to handle password-based, SSH authentication keys help keep things simple. Simplay enter the following command to generate for you the keys using RSA algorithm

root@ansible-VirtualBox:~# ssh
Note: I used the tab key to display all available options

ssh               ssh-argv0         ssh-import-id     ssh-keygen        
ssh-add           ssh-copy-id       ssh-import-id-gh  ssh-keyscan       
ssh-agent         sshd              ssh-import-id-lp  sshpass   

Note: The step starts from here. During the process you will be prompted for a password, keep hitting the enter button to create the key.

root@ansible-VirtualBox:~# ssh-keygen -t rsa -K4096
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/
The key fingerprint is:
SHA256:3DLxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxE8yGA root@ansible-VirtualBox
The key's randomart image is:
+---[RSA 2048]----+
|    .oo..        |
|    .. o.o       |
|   . ..+*.       |
|    + .+==       |
|   . o .S.+ ..   |
|.Eo . =  +.o...  |
|.+ + = .  o=oB . |
|  o =      o@.=  |
|     .       =.  |

Note the following

  • Now you have the RSA key generated.
  • If you already have an SSH key pair, simply copy this to the specified path of the machine running Ansible (~/.ssh/
  • By default, the public key is saved in the file ~/.ssh/,
  • while the private key is saved in ~/.ssh/id_rsa
  • Not important for this task but vital to add more users.

    Now copy the file to the remote host and append it to ~/.ssh/authorized_keys

    This step is necessary if you wish to have needed other users to administer ansible to connect to these machines.

    Now copy the file to the remote host and append it to ~/.ssh/authorized_keys using this command:
root@ansible-VirtualBox:~# ssh-copy-id username@remotehost

where remotehost is the IP address or FQDN of the server and username is the “root” or whatsoever name you have configured for the other machine.

Finally, double-check the permissions on the authorized_keys file, only the authenticated user should have read and write permissions. If the permissions are not correct to change them by.

Now assign permission: You should now be able to SSH to the host without being prompted for a password.

root@ansible-VirtualBox:~#chmod 600 .ssh/authorized_keys
To get (view) the public key run this command
root@ansible-VirtualBox:~# cat ~/.ssh/
ssh-rsa AAAAxxxxxxxxxxxxxxxxxxxxNxfz5NxxxxxxxxxxxRUVxxxxxxxx root@ansible-VirtualBox
To view where your hidden files are kept you use
root@ansible-VirtualBox:/etc# cd ~/.ssh
root@ansible-VirtualBox:~/.ssh# ls

To view the private keys, use any of the editor

root@ansible-VirtualBox:~/.ssh# vi id_rsa

Note: Make sure that you include the first and last marker lines. They are required in order for the key file to be valid and change permission if necessary.

To view the public key, run the same command but with the .pub

root@ansible-VirtualBox:~/.ssh# vi

8. Configuring Ansible Hosts:
As we all know, Ansible keeps track of all the servers it knows via a file called “Hosts” file. This needs to be configured (entered) before it will be able to communicate with other computers.
this is how it looks.

root@ansible-VirtualBox:/etc/ansible# ls
ansible.cfg hosts roles

root@ansible-VirtualBox:/etc/ansible# vi hosts
# This is the default ansible 'hosts' file.
# It should live in /etc/ansible/hosts
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.


# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]

# If you have multiple hosts following a pattern you can specify
# them like this:

## www[001:006]

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]

Note: These are just configuration examples. None will work except they are commented out, i.e, by deleting the # symbol and adding the right devices (IP address) are added.

To do this, you have to uncomment them out and enter the idea ip address(es).


Note the following steps below.
Method 1: On how to copy the SSH public key to remote servers
Step 1: Always remember to copy the ssh public key from the ansible machine to the server you wish to manage.

root@ansible-VirtualBox:/etc# cd ~/.ssh
root@ansible-VirtualBox:~/.ssh# ls
id_rsa known_hosts
root@ansible-VirtualBox:~/.ssh# vim

And copy the key!!!

Step 2: Create a file called authorized_keys on the target machine you wish to use ansible on. the in the authorized_keys create copy and paste the public of the Ansible server in it.

Note: This has to be in the home directory of the ssh user which is without the bracket (~/.ssh). it should look this way.

Webserver@nagios:~$ vi .ssh/authorized_keys

Note 2:
Also, install the python-apt library on the target machine you wish to administer Ansible on, e.g., my Nagios server

Webserver@nagios:~$ sudo apt-get install python-apt
Webserver@nagios:~$ sudo apt-get install aptitude

or use a single command (any of these)

- Webserver@nagios:~$ sudo apt-get install python-apt; apt-get install aptitude
- Webserver@nagios:~$ sudo apt-get install python-apt && apt-get install aptitude
- Webserver@nagios:~$ sudo apt-get install python-apt || apt-get install aptitude

Note: Without this, it will fail if we want to do some package installations.

Method 2: This method seems to be the easiest way to copy the ssh public key from the ansible machine to the server you wish to manage.

root@ansible-VirtualBox:~/.ssh# ssh
ssh               ssh-argv0         ssh-import-id     ssh-keygen        
ssh-add           ssh-copy-id       ssh-import-id-gh  ssh-keyscan       
ssh-agent         sshd              ssh-import-id-lp  sshpass    

root@ansible-VirtualBox:~/.ssh# ssh-copy-id

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys's password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘'”
and check to make sure that only the key(s) you wanted were added.

Note: This method has copied the public key to the server you wish to administer. now to see the key on the other server use this command

webserver@nagios:~$ cat .ssh/authorized_keys
ssh-rsa yc2EAAxxxxxxxxxxxxxxxxxxxxxxxDJRl0Zqrxxxxxxxxxxxxxxxxxxxxxxxx

9. After defining your host file in step 8 above

root@ansible-VirtualBox:/etc/ansible# vi hosts
## ansible_user=webserver

Let’s do some ping testing

Example 1:
root@ansible-VirtualBox:/etc/ansible# ansible monitoringservers -m ping

This will display the number of servers with IP address it successfully pinged. | SUCCESS => {
"changed": false,
"ping": "pong"

Note: It shows it is using the module called ping, signified by -m to ping all the available servers in the group of monitoring servers.

root@ansible-VirtualBox:/etc/ansible# ansible -i hosts monitoringservers -m ping | SUCCESS => {
"changed": false,
"ping": "pong

Here, a hosts is added and it delivers the same output.

Useful link

Concept – Ansible on Windows

This is one of the famous configuration management (Orchestration) tools in existence today. Ansible is an agentless, powerful automation that enables you to deliver configurations, deployment across your IT environment. Configuration management systems are designed to make controlling large numbers of servers easy for administrator’s teams. They allow you to control many different systems in an automated way from one central location. Here are examples of other configuration Tools.

- Chef
- Puppet
- Salt
- CFEngine etc.

Traditionally, Ansible is more focused on Linux, but with Microsoft support of Open Source and adoption lately, Windows Support for Ansible is possible. Ansible’s native Windows support uses Windows PowerShell remoting to manage Windows in the same way that Ansible manages Linux.

Ansible allows the administration of Windows using local or domain users. Here is Ansible’s native Windows support; you can, out of the box.

- Gather facts on Windows hosts
- Manage and install Windows updates
- Fetch files from remote sites
- Push and execute any PowerShell scripts you write
- Install and uninstall MSIs
- Enable and disable Windows Features
- Start, stop, and manage Windows services
- Create and manage local users and groups
- Manage Windows packages via the Chocolatey package manager

Ansible’s easy extensibility, enables you can write your own modules in PowerShell and extend Ansible for whatever other functionality you need for your environment.

Host requirements: For Ansible to manage Windows effectively, the following has to be followed.
– Windows version: Supports Windows 10, Windows Server 2016 and 2019.
– Ansible requires PowerShell 3.0 or newer and at least .NET 4.0 to be installed on the OS.
– It requires WinRM listener be created and activated

Note: If your base image (OS images) does not meet PowerShell 3.0, this can be upgraded.

What is WinRM: Windows Remote Management (WinRM) is the Microsoft implementation of the WS-Management Protocol, a standard Simple Object Access Protocol (SOAP)-based, firewall-friendly protocol that allows hardware and operating systems, from different vendors, to interoperate. The WS-Management protocol specification provides a common way for systems to access and exchange management information across an IT infrastructure.

In other terms, WinRM is a management protocol used by Windows to remotely communicate with other servers.

Note: WinRM does everything which can be performed remotely by WMI and RPC. With this distinction that there are no proprietary RPC calls over TCP, but are handled via HTTP port 80 or 443. You can configure additional listeners, which then accept connections by default on ports 5985 HTTPS 5986. For the administration “over the Internet” exactly one port is sufficient and even via proxy server a connection is usually possible. For more information, see

Note: When running PowerShell 3.0, ensure you pay attention to the known bug, (that limits the memory available to WinRM that result in Ansible failing to execute certain code on Windows devices) by applying the hot-fix. See link to the fix

Setup the WinRM
When the PowerShell prerequisite is met; ensure to install the WinRM in order to allow Ansible to connect to it. The WinRM service has two components that enable Ansible to interface with Windows, the configuration settings are as follow;

  • Listener and
  • Service

See an example setup script to configure HTTP and HTTPs Listeners. This script as stated by Ansible uses a self-signed certificate and enables basic authentication only. Therefore it is not a good solution for a production

WinRM Listener:  This service listens to request on one or more ports.
Note: This one or more port can have the listener created and configured on them.

– This is how to view the current listeners that are running on the WinRM service, run the cmd execute the command without the quotes included. “ winrm enumerate winrm/config/Listener”

See documentation on how to create WinRM listener via PowerShell (ensure to provide the certificate thumbprint).

How does Ansible work?
Ansible works by configuring remote devices from a central device that has Ansible software installed. It has a simple architecture and communicates over normal SSH channels for Unix systems or WinRM for Windows systems in order to retrieve information from remote machines, to execute the automation tasks and YAML files to define provisioning details (issue commands) etc.

Note: Ansible does not require any additional software installed on the remote (client) devices. With the SSH or WinRM port exposed, servers (remote devices) can be configured.

Windows SSH Setup:
Install the Win32-OpenSSH service installed on your device

There are other ways such as using Chocolatey etc.

Configure the Win32-OpenSSH shell. By default Win32-OpenSSH will use cmd.exe as a shell. To configure a different shell, use an Ansible task to define the registry setting: See how this is done in the link below. The following scenarios and use the link below for configuration as well.
– The Win32-OpenSSH Authentication method
– Set the connection variable for Ansible for SSH

Setting Up Chef Automate on AWS

Navigate to the URL 
and select Create Chef Automate Server

Step 1: Now select the region and enter the Chef Server Automate Instance (server) name and
– Select the Instance type too.

Step 2: Select an SSH Key
No room to create a new key (either you select you don’t want to connect using SSH or you select an existing SSH key).

Step 3: Select the right VPC, Subnet, associate the right EIP, security group.
– Create a service role if non-exists at the moment

“AWS OpsWorks for Chef Automate needs your permission to create an IAM service role that allows us to perform actions in AWS CloudFormation, Amazon EC2, Amazon EC2 Simple Systems Manager, and Amazon S3. By continuing, you are allowing us to create a new role to work with these services.” Create an Instance Profile

“AWS OpsWorks for Chef Automate needs your permission to create an instance profile that allows us to perform actions in Amazon S3, and communicate with a Chef server by using Amazon EC2 Simple Systems Manager (SSM). By continuing, you are allowing us to create a new role to work with these services”

Select your maintenance Windows to allow AWS OpsWork to install Updates for Chef Automate minor versions or security packages.

Note: Weekends are always better to have this performed. (select whatsoever time suits you).

For AWS OpsWorks Backup: AWS OpsWorks supports two ways to back up your Chef Automate server: manual or automated. Backups are uploaded to your Amazon S3 bucket. If you ever need to restore your Chef Automate server, you can restore it by applying a backup that you choose.

When you choose yes to Enable automated backup, these options below are available

Number of generations to keep: 30 is usually okay but this depends on your organization policy.

Step 4: Review and Launch: open its Properties page in the AWS OpsWorks for Chef Automate console. The page below will be prompted to show the progress bar of the AWS OpsWork for Chef Automate creation.

Note: Make sure you download the following before your server is online. The download buttons are not available after a new server is online.

Finally, this message will appear on the dashboard stating your Chef Automate Server is successfully launched

Note: The created role will appear in the IAM section under roles as shown below

Now Access the URL (dashboard) of Chef Automate and perform all necessary configurations etc. as shown below

Note: Ensure you have the ChefDK downloaded and Installed on your local PC from

Otherwise, you cannot work with Chef Automate with Windows 10. See how to install ChefDk on Windows in the next page

Chef – Node Bootstrapping

The Chef-Client agent runs Chef recipes on both physical and virtual servers often referred to as nodes or instances.  Associating nodes with Chef ensures the chef server installs the chef-client software on the nodes.

Note: The minimum supported version of chef-client on nodes associated with OpsWorks for ChefAutomate Server is 12.16.42. We recommend running chef-client 13.6.4.

Using knife to add or bootstrap an instance (See for supported operating systems)

Example 1: Bootstrapping an instance using knife commands. 

knife bootstrap windows winrm EnterNodeIPAddress --winrm-user Administrator --winrm-password 'enterserverpasswordhere' --node-name EnterNodeNamehere --run-list 'recipe[chef-client]'

Note: You can attach any cookbooks in place of the chef-client run-list, or have a role uploaded to the chef server which in turns have many run-list attached to the role and update the node run-list to use the newly created role. This topic will be discussed in a latter stage.

Also see if you wish to add nodes automatically

Chef-Repo Setup

As discussed in 
It is recommended to placed in Git of any of the VCS your cookbooks etc.

A Chef repository contains several directories. Each directory in the StarterKit contains a README file that describes the directory’s purpose, and how to use it for managing your systems with Chef. There are two ways to get cookbooks installed on your Chef server. Either by using the,
– knife commands, or
– Berkshelf commands. 

Create a directory on your local PC for storing cookbooks similar to the Chef-repo

  • Create a directory on yourlocal computer for storing cookbooks, such as chef-repo. After you addcookbooks, roles, and other files to this repository, we recommend that youupload or store it in a secure, versioned system, such as AWS CodeCommit, Git,or Amazon S3.
  • In the chef-repo directory, create the following three directories, as shown in the Starter Kit:
    1. cookbooks/ – Stores cookbooks that you download or create.
    2. roles/ – Stores rolesin .rb or .json formats.
    3. environments/ – Stores environments in .rb or .json formats

Use-Case 1
Use Berkshelf to get Cookbooks from the Chef Supermarket:

Berkshelf is a tool for managing cookbooks and their dependencies. It downloads a specified cookbook into your local storage, which is called the Berkshelf. You can specify which cookbooks and versions to use with your Chef server and upload them.

First: Let’s try this very basic example.
Step 1: Navigate to Chef supermarket and search for google chrome and Firefox.

Then locate the Berksfile as shown below and add the Firefox and google chrome codebooks as shown below. This ensures the cookbooks are download and stored locally.

Locate the path where you have the starter kit downloaded to, mine is 


Let’s modify the Berksfile and add the cookbooks for Firefox and chrome gotten from the Chef Supermarket.

Step 2: Download and install the cookbooks on your local Computer
– Launch the Chef Dk Client (PowerShell)

Navigate to the Chef local Repository from the Chef Dk terminal otherwise this will not work if you are in a different directory. See image below and run the command. See screenshoot below for the Repo content.

Step 3: Upload this cookbook to Chef Server

This is difference on how it works on Linux than on Windows.
See link:

For Windows: Ensure the Execution Policy in PowerShell is set to RemoteSigned. The execution policy ensures you can load configuration files and determine which script if any must be digitally signed. See the image below on how to set the execution policy to RemoteSigned.

This simply restricts us from running unsigned PowerShell scripts downloaded from the Internet.

Run berksinstall

Otherwise, you wouldn’t be able upload your cookbooks. Verify if this is installed, by running the command below in the console

berks –version

Next run the command below to add the SSL Cert file.


Then run berks upload to upload to the Chef Server

'berks upload'

Finally remove the SSL Cert File

Remove-Item Env:SSL_CERT_FILE

To verify that this worked, simply run the command “knife cookbook list” as shown below

Get Started with OpsWorks for Chef Automate

Provision a Chef Automate Server in AWS. Follow this link and ‘click on get Started with OpsWorks for Chef Automate’

When setup is complete, ensure you download the Sign-in credential for the Chef Server as this is not saved by AWS OpsWork for Chef Automate and cannot be downloaded afterwards or viewed.

StarterKit: Download and Unzip the Starter Kit. TheStarter Kit contains a README file with examples, a knife.rb configuration file, and a private key for the primary or pivotal user.

Note: A new key pair is generated—and the old key is reset—each time you download the Starter Kit.

The Starter Kit .zip file includes a simple example of a Chef repository that works with any AWS OpsWorks for Chef Automate Server. In the Chef repository, you store cookbooks, roles, configuration files, and other artifacts for managing your nodes with Chef. It is recommend that you store this repository in a version control system, such as Git or AWSCodeCommit and treat it as source code.

Note: Never share the Starter Kit private key. If other users will be managing the Chef server, add them as administrators in the Chef Automate dashboard.

Chef Development Kit: Download and run on the computer that will administer the Chef Server and Nodes. The knife utility is also part of the Chef DK.

Chef Automate (AWS Opsworks For Chef Automate)

Chef Automate provides a full suite of enterprise capabilities for workflow, node visibility and compliance. Chef Automate integrates with the open-source products Chef, InSpec and Habitat. Chef Automate comes with comprehensive 24×7 support services for the entire platform, including open source components.

Chef Automate includes a pipeline for continuous delivery of infrastructure and applications. This full-stack approach, where infrastructure changes are delivered in tandem with any application changes, allows for safe deployment at high velocity.

Chef Automate gives you a data warehouse that accepts input from Chef, Habitat, and Chef Automate workflow and compliance. It provides views into operational and workflow events. There is a query language available through the UI and customisable dashboards.

Here is an example of the Chef Automate dashboard.

High Availability
Chef Automate has a high-availability Chef server option for fault tolerance, immediately consistent search results, and accurate real-time data about your infrastructure. Chef Automate also provides a graphical management console for the Chef server

Chef Automate creates customizable reports that identify compliance issues, security risks, and outdated software. You can write your own compliance rules in InSpec, or you can get started quickly by using built-in profiles, which are predefined rule sets for a variety of security frameworks, such as Center for Internet Security (CIS) benchmarks, included as part of Chef Automate.

Compliance reporting is currently done through two mechanisms: The integrated compliance reporting in Chef Automate 0.8.5 or later, and the standalone Chef Compliance server.