Share this page : facebooktwitterlinkedinmailfacebooktwitterlinkedinmail
Step 1: Installing Ansible

You can install Ansible with:

apt-get install ansible

You need to put all the servers that you want to manage with Ansible in the /etc/ansible/hosts file. Actually you can setup the hosts file in the same location as the playbook file.

Configuration file:

We can use the default configuration file, if you like you can configure it according to your need. Ansible looks for an ansible.cfg file in the following places, in this order:

1. File specified by the ANSIBLE_CONFIG environment variable
2.
./ansible.cfg (ansible.cfg in the current directory)
3.
~/.ansible.cfg (.ansible.cfg in your home directory)
4.
/etc/ansible/ansible.cfg

 

Step 2: Setting up SSH keys

Ansible works with SSH keys. If your SSH key on nodes isn’t the same as on your Ansible server, it will give you an error. Therefore, we need to generate an SSH key.

If you need openssh installed, use apt-get install openssh-server

Then create a key pair:

ssh-keygen

This create a private key ~/.ssh/id_rsa and a public key ~/.ssh/id_rsa.pub

Now add your SSH key to your nodes. It can be found here:

cat ~/.ssh/id_rsa.pub

Copy the content , on the target server, also make sure openssh is installed, then make sure folder .ssh exist in your home folder,  create a file ~/.ssh/authorized_keys

Then append the public key content to it.

If you are managing AWS VMs, you can also use the private key provided by Amazon and then specify the private key in the command in step 5 or 6 by switch –private-key.

Step 3: make sure Python is installed on the target servers

To install Python, use apt-get install python

Step 4: Add host to the host file

In the hosts file or /etc/ansible/hosts

add lines:

[test]
192.168.10.73

192.168.10.73 is the IP address is target server.

Step 5: test
ansible -m ping all

For the AWS, you need to type like this with the private key ( in my case, I used the red hat Linux, you may have to change the user name according to your OS):

ansible test -m ping -a uptime --private-key=/home/ec2-user/openshift-aws-installer-image/ck_workshop.pem -u ec2-user

If you want to execute sudo command, you need to add -su --su-user=ec2-user

Note, the -su --su-user=ec2-user -u ec2-user must in this particular order.

Step 6: create a playbook

You can create a playbook in ymal format, we will try to install nmap on a target machine:

---

- hosts: test
  tasks:
    - name: Setup nmap
       apt: pkg=nmap state=installed update_cache=true

 

If you want to add password use --extra-vars "ansible_sudo_pass=yourPassword"

ansible-playbook playbook.yml -i /etc/ansible/hosts -u username --extra-vars "ansible_sudo_pass=yourPassword"
  • -i is the host file
  • -u username : this may useful if you want to use sudo command.