Ansible
ANSIBLE:
- It is a Configuration Management Tool.
- Configuration: Ram, Storage, OS, Software and IP address of device.
- Management: Update, Delete, Add.
- Ansible is simple open-source IT engine which automates application deployment.
- Orchestration, Security and compliance.
- Uses YAML Scripting language which works on KEY-VALUE PAIR
- Ansible GUI is called as Ansible Tower. It was just Drag and Drop.
- Used PYTHON for Back end.
- Michael Dehhan developed Ansible and the Ansible project began in Feb 2012.
- Ansible was taken over by Red-hat.
- Ansible is Available for RHEL, Debian, CentOS, Oracle Linux.
- Can use this tool whether your servers are in On-prem or in the Cloud.
- It turns your code into Infrastructure i.e. Your computing environment has some of the same attributes as your application.
Ansible uses plain SSH. so nothing needs to install on client machines. but other automation tools
like Chef/Puppet needs to install agent on client machine when we need to perform a task.
Ansible’s is light weight, relative easy to use and speed of deployment compared to other tools. Ansible handle either via standard SSH commands, or the Paramiko module which provides a Python interface to SSH2.
ANSIBLE WORKFLOW:
CHEF WORKFLOW:
SETUP:
ANSIBLE SERVER:
sudo -i
sudo amazon-linux-extras install ansible2 -y
yum install git python python-pip python-level openssl -y
vi /etc/ansible/hosts
vi /etc/ansible/ansible.cfg
useradd ansible
passwd ansible
visudo
vim /etc/ssh/sshd_config
ALL NODES
useradd ansible
passwd ansible
visudo
vim /etc/ssh/sshd_config
ALL SERVERS
sudo systemctl restart sshd
sudo systemctl status sshd
su - ansible
ANSIBLE SERVER:
ssh-copy-id ansible@localhost
yes & password
exit
ssh-copy-id ansible@privateip
yes & password
exit
HOST PATTREN:
‘all’ patterns refer to all the machines in an inventory.
ansible all–list-hosts ansible <groupname[remo]> --list-hosts
ansible <groupname> [remo][0] --list-hosts
groupname [0] – picks first machine of group
groupname [1] – picks second machine of group
groupname [-1] – picks last machine of group
groupname [1:4] – picks 2,3,4,5 machines in group
groupname [2:5] – picks 3 to 6 machines in the group
ansible all -m ping -v
If we want to push the code from Ansible server to nodes it can be done in 3 ways.
Ad-hoc Commands (Simple Linux) Ad-hoc means temporary & it will over-ride commands.
Modules – A Single Command.
Playbooks – More than one module is called Playbook.
Both module and Playbook is in YAML.
ADHOC COMMANDS:
These commands can be run individually to perform Quick functions.
Not used for configuration management and deployment, bcz the cmds are one time usage.
The ansible ad-hoc cmds uses /usr/bin/ansible/ command line tool to automate single task.
Go to ansible server and switch to ansible server
ansible remo -a “ls” [remo: Group name, -a: argument, ls: command]
ansible remo [0] -a “touch file1”
ansible all -a “touch file2”
ansible remo -a “sudo yum install httpd -y”
ansible remo -ba “yum install httpd -y” (b: become you will become sudo user)
ansible remo -ba “yum remove httpd -y”
MODULES:
Ansible ships with number of modules (called library modules) that can be executed directly to remote hosts or playbooks.
Your library of modules can reside on any machine, and there are no servers, daemons or database required.
The default location for the inventory file is /etc/ansible/hosts
Go to ansible server and switch to ansible server
ansible remo -b -m yum -a “pkg=httpd state=present” (install: present)
ansible remo -b -m yum -a “pkg=httpd state=latest” (update: latest)
ansible remo -b -m yum -a “pkg=httpd state=absent” (uninstall: absent)
ansible remo -b -m service -a “name=httpd state=started” (started: start)
ansible remo -b -m user -a “name=raj” (to check go to that servers and sudo cat /etc/passwd).
ansible remo -b -m copy -a “src=filename dest=/tmp” (to check go to that server and give ls /tmp).
PLAYBOOKS:
Playbooks in ansible are written in YAML language.
It is human readable & serialization language commonly used for configuration files.
You can write codes consists of vars, tasks, handlers, files, templates and roles.
Each playbook is composed of one or more modules in a list.
Module is a collection of configuration files.
Playbooks are mainly divided into sections like
TARGET SECTION: Defines host against which playbooks task has to be executed.
VARIABLE SECTION: Defines variables.
TASK SECTION: List of all modules that we need to run in an order.
YAML:
For ansible, nearly every YAML file starts with a list
Each item in the list is a list ok key-value pairs commonly called Dictionary.
All YAML files have to begin with ”---” and end with “…”
A dictionary is required in a simple key: value form (note: space before value is must)
For example:
--- # Customer details
Customer:
Name: abc
Age : 26 y
Salary: 100,000
Exp : 4 year
Extension for playbook file is .yml
BASIC POINTS:
Go to ansible server and login as ansible and create one playbook
Vi target.yml
---# Target Playbook
hosts: remo -- > remo: Groupname
user: ansible -- > ansible: You are ansible user now
become: yes -- > become: become sudo user -- > yes
connection: ssh
gather_facts: yes -- > Gives private IP of the nodes -- > yes
now save that file and execute the playbook by giving the command: ansible-playbook target.yml
Now create one more playbook in ansible server with cmd Vi task.yml
NORMAL PLAYBOOK:
TO EXECUTE: ansible-playbook playbook.yml
DRY RUN: Check whether the playbook is formatted correctly or not.
ansible-playbook playbook.yml --check
VARIABLES:
Ansible also provides various ways of setting variables. They are used to store values that can be later used in the playbook.
Variable names in Ansible should start with a letter. The variable can have letter, numbers and underscore. Invalid variable declaration comes when we use dot (.), a hyphen (-), a number or variable separated by multiple words.
other way of passing arguments is by passing them to the command line while running using the –extra-vars parameter.
Passing a Varaible file - A Varaible can be defined in a variable file and can be passed to a playbook using the include
HANDLERS:
Handler is same as task but it will run when called by another task. (OR)
It will run if the task contains a notify directive and also indicates that it changed something.
LOOPS:
Ansible loop includes changing ownership on several files & directories with file module, creating multiple users with user modules and repeating a polling step until result reached.
CONDITIONS:
If we have different scenarios, then we apply conditions according to the scenarios.
WHEN STATEMENT
Sometimes we want to skip a particular command on a particular node.
VAULT:
In ansible we can keep sensitive data like our passwords and keys in encrypted format.
ENCRYPTION TECHNIQUE: AES256 Used by Facebook.
ansible-vault create vault.yml : creating a new encrypted playbook.
ansible-vault edit vault.yml : Edit the encrypted playbook.
ansible-vault rekey vault.yml : To edit the password.
ansible-vault encrypt vault.yml : To encrypt the existing playbook.
ansible-vault decrypt vault.yml : To decrypt the encrypted playbook.
ROLES:
We can use two techniques for resulting a set of tasks they are Includes and Roles.
Roles are good for organizing tasks & encapsulating data needed to accomplish the task.
ANSIBLE ROLES: Default, Files, Handlers, Meta, Templates, Tasks, Vars.
We can organize playbooks into directory structure called Roles.
Adding more functionality to the playbooks will make it difficult to maintain in a single file.
mkdir -p playbook/roles/webserver/tasks --- > To see o/p use tree command.
Cd playbook & touch master.yml & touch roles/webserver/tasks/main.yml
vi roles/webserver/tasks/main.yml
TAGS:
If you have a large playbook, it may be useful to run only specific parts of it instead of running the entire playbook. You can do this with Ansible tags. Using tags to execute or skip selected tasks
TO EXECUTE A SINGLE TASK: ansible-playbook abc.yml --tags tagname
TO EXECUTE A MULTIPLE TASK: ansible-playbook abc.yml --tags tagname1,tagname2
TO SKIP A TASK: ansible-playbook abc.yml --skip-tags “uninstall”
GALAXY:
Ansible Galaxy is a galaxy website where users can share roles and to a command-line tool for installing, creating, and managing roles.
Ansible Galaxy gives greater visibility to one of Ansible's most exciting features, such as application installation or reusable roles for server configuration. Lots of people share roles in the Ansible Galaxy.
Ansible roles consist of many playbooks, which is a way to group multiple tasks into one container to do the automation in a very effective manner with clean, directory structures.
ansible-galaxy init raham
ansible-galaxy search elasticsearch
ansible-galaxy search elasticsearch --author alikins
ansible-galaxy install alikns.elasticsearch
cd /home/ansible/.ansible/roles/
USER INFO:
Go to the ansible galaxy website and select a username
ansible-galaxy info bonddim.linux
ansible-galaxy collection install bonddim.linux
ADVANTAGES:
Very simple to set up and use.
No special coding skills are necessary to use Ansible's playbooks.
Ansible lets you model even highly complex IT workflows.
You can orchestrate the entire application environment no matter where it's deployed.
DIS ADVANTAGES:
Ansible does not have any notion of state like other automation tools such as Puppet
Ansible does not track dependencies and simply executes sequential tasks and stops when tasks
finish, fail, or any error comes.
Ansible has external dependencies to Python modules
Windows interaction requires some scheming
Jenkins setup Uing playbook:
Playbook to create a file/folder:
TO ENTER A DATA IN A FILE:
Playbook to change permissions to a file:
playbook to deploy a webapp:
PIP MODULE:
Ansible pip module is used when you need to manage python libraries on the remote servers.
There are two prerequisites if you need to use all the features in the pip module.
The pip package should already be installed on the remote server.
Virtualenv package should be installed on the remote server already if you need to manage the packages in the python virtual environment.
RAW MODULE:
RAW module is used when there is more need than Command module or if the command module does not support the operation. This module makes a SSH to the remote machine and run the command. For the Ansible to work we need to have Python available but for this module we don’t need a Python to be available
PLAYBOOK TO GET CODE FROM GIT (public repo):
PLAYBOOK TO GET CODE FROM GIT (private repo):
Syntax: token@github.com/username/repo.git
ANSIBLE SETUP MODULES:
ansible_os_family
os name like RedHat, Debian, Ubuntu etc..
ansible_processor_cores
No of CPU cores
ansible_kernel
Based on the kernel version
ansible_devices
connected devices information
ansible_default_ipv4
IP Mac address, Gateway
ansible_architecture
64 Bit or 32 Bit
After executing a playbook, if you want to see the output in json format
ansible -m setup private_ip
if you want to apply a see particular output, you can apply filter.
ansible -m setup -a "filter=ansible_os_family" private_ip
ansible -m setup -a "filter=ansible_devices" private_ip
ansible -m setup -a "filter=ansible_kernel" private_ip
ANSIBLE DEBUG:
it can fix errors during execution instead of editing your playbook.
You can see that the task is performing on which OS.
Depends upon the memory, we can debug.
Depends upon the ip, we can debug.
- debug:
msg: "ip info of all the devices is {{ansible_all_ipv4_addresses}}"
If you run a command to check the files along with its content in a server, it will not shows us the output.
But we can debug the output.
Ansible in-out operator:
To check weather GIT is installed or not.