Ansible
Ansible - configuration management tool - ansible is agent-less system like chef no client required, its use SSH directly to communicate
Anisible is an open-source IT configuration management, deployment and orchestration tool, it aims to provide large productivity gains to a wide variety of Automation challenges
can use this tool whether your servers are in on-premises 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 server --------- node1, node2, node3
like recipe in chef, we have playbook in ansible
Resources in chef, modules in ansible
Advantages
Ansible is free to use.
Ansible is very consistent and lightweight and no constraints regarding the OS or Underlying H/W are present
It is very secure due to its agent-less capabilities and open ssh security features
Ansible does not need any special system administrator skills to install and use it (YAML)
Push mechanism
Disadvantages
Insufficient user interface, through ansible tower is GUI, but it is still in development stages
Cannot achieve full automation by ansible
New to the market, therefore limited support and document is available.
Terms used in Ansible
Ansible server - the machine where ansible is installed and from which all tasks and playbooks will be ran.
Module - Basically, a module is a cmd or set of similar cmds meant to be executed on the client-side.
Task - A task is a section that consists of a single procedure to be completed
Role - A way of organizing tasks and related files to be called is a playback.
Fact - Information fetched from the client system from the global variables with the gather-facts operation
Inventory - file containing data about the ansible client servers
Play - execution of a playbook
handler - task which is called only if a notifier is present
Playbook - It consist code in YAML format, which describes tasks to be executed
Host - Nodes, which are automated by ansible
..........................................................
Create 3 instances in same AZ
Take access of all machines, Now go inside ansible server and download ansible package
wget http://.....rpm
Now do ls
yum install epel...rpm
yum update -y
Now we have to install all the packages one by one
yum install git python python-level python-pip openssl ansible -y
Now go to hosts file inside ansible server and paste private-ip of node1 & node2
vi etc/ansible/hosts
[demo]
node1 private ip
node2 private ip
Now this hosts file is only working after updating ansible.cfg file
vi etc/ansible/ansible.cfg
uncommented
#inventory
#etc/ansible/hosts
#sudo-user
#root
Now create one user, set passwd in all the three instances
adduser ansible
passwd ansible
Now switch as Ansible user
su - ansible
This ansible user dont have sudo privilege .
visudo
Now go inside this file.
root ALL=(ALL) ALL
ansible ALL=(ALL) NOPASSWD:ALL
Now do this thing in other nodes also
Now go to ansible server and try a install httpd package as a ansible user
sudo yum install httpd -y
Now establish connection b/w server and node go to another server
ssh 172xxx
Now we have to do some changes in sshd_config file go into ansible server
vi /etc/ssh/sshd_config
Do some changes & save
Do this work in node1 & node2 also, now verify in ansible server
su - ansible
ssh 172xxxx
now it ask for passwd, enter the passwd, after that you will be inside node1
..................................................................
Now do ssh-keygen
ls -a
cd ./ssh
ls
id_rsa id_rsa_pub
copy to node1, node2
ssh-copy-id ansible@172.31.27.226
54.179.16.139 172.31.27.226
13.229.247.99 172.31.30.185
54.169.186.120 172.31.29.92
ssh -i "AWSSingaporeKey.pem" ec2-user@ec2-54-179-16-139.ap-southeast-1.compute.amazonaws.com
ssh -i "AWSSingaporeKey.pem" ec2-user@ec2-13-229-247-99.ap-southeast-1.compute.amazonaws.com
ssh -i "AWSSingaporeKey.pem" ec2-user@ec2-54-169-186-120.ap-southeast-1.compute.amazonaws.com
"all" pattern refers to all the machines in an inventory
ansible all --list-hosts
ansible <group-name> --list-hosts
ansible <group-name>[0] --list-hosts 1,2,3......-1
groupname[0] pick 1st node
groupname[-1] pick last node
groupname[1-2] pick 2st to 3rd node
groupname1,groupname2 pick multiple group
demo[0-1],test[0-1]
.........................................
1. Ad-hoc cmd simple linux cmd (temp), but no idempotency
2. Modules | yaml lang | single cmd run at a time, 1 module at a time
3. Playbooks | yaml lang. | if run more then 1 module is call playbook
Ansible modules and playbooks both have idempotency, and its use setup module, its just like ohai in chef
Ad-hoc cmds are cmds which can be run individually to perform quick functions
These ad-hoc cmds are not used for configuration managment and deployment, becz these cmd are one time usage
The ansible ad-hoc cmd uses the /usr/bin/ansible cmd line tool to automate a single task
Ad-hoc cmd
ansible demo -a "ls" -a means argument
ansible demo[0] -a "touch file"
ansible all -a "touch file1"
ansible demo -a "sudo yum install httpd -y"
ansible demo -ba "yum install httpd -y"
ansible demo -ba "yum remove httpd -y"
Ansible Modules
Ansible ships with a number of modules (called module library) that can be executed directly on remote hosts or through playbooks
your library of modules can reside on any machine, and there are no servers, daemon, or databases required
The default location for the inventory file is /etc/ansible/hosts
Ansible Modules
ansible demo -b -m yum -a "pkg=httpd state=present" install=present, uninstall=absent, update=latest
ansible demo -b -m yum -a "pkg=httpd state=latest"
ansible demo -b -m yum -a "pkg=httpd state=absent"
ansible demo -b -m service -a "name=httpd state=started"
ansible demo -b -m user -a "name=raj"
ansible demo -b -m copy -a "src=file1 dest=/tmp"
copy, command, user, package, service, file, unarchive, lineinfile, firewalld, template
Setup Module
ansible demo -m setup
ansible demo -m setup -a "filter=*ipv4*"
.....................................................
Playbook
playbook is ansible are written in YAML format
It is human readable data serialzation lang. it is commonly used for configuration files.
Playbook is like a file where you write codes. consist 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 divided into many sections like
Target section - hosts or nodes, defines the host against which playbooks task has to be executed
variables section - define variable
Task section - list of all modules that we need to run in order
YAML
for ansible, nearly every YAML files starts with a list.
Each item in the list is a list of key-value pairs commonly called a directory.
All YAML files have to begin "..."
All members of a list lines must begin with same indentation level starting with "_"
for eg
--- # a list of fruits
fruits:
-mango
-strawberry
-banana
-grapes
-apple
...
a dictionary is represented in a simple key: value form
for eg
--- # detail of customer
customer:
name: _rajput
job: _dob
...........................
playbook
vi target.yml
--- # Target playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
gather_facts: yes
Now to execute this playbook
ansible-playbook target.yml
................................
Now create one more playbook in ansible server
vi target.yml
--- # Target playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
tasks:
- name: install httpd on linux
action: yum name=httpd state=installed
.....................................................
Variable
Ansible uses variables which are defined previously to enable more flexibility in playbooks and roles
They can be used to loop through a set of given values, access various information likes the host name of a system and replaces certain strings in templates with specific values.
put variable section above task so that we define it first & use it later
now
vi vars.yml
--- # my variable playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
vars:
pkgname: httpd
tasks:
- name: install httpd on linux
action: yum name='{{pkgname}}' state=installed
...........................
Handler Section
A handle is exactly the same as a task, but it will run when called by another task
OR
handler are just liker regular tasks in an ansible playbook, but are only run if the task contains a notify directive and also indicates that it changed something
handler use where we have dependency, eg task have httpd service install and start, but in case httpd service did nt install, then no point to start service, so there is dependency, so 1st task need to perform 1st
vi handler.yml
--- # handler playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
tasks:
- name: install httpd on linux
action: yum name=httpd state=installed
notify: restart HTTPD
handlers:
- name: restart HTTPD
action: service name=httpd state=restarted
.........................................................
Dry run
check whether the playbook is formatted correctly
ansible-playbook handler.yml --check
Loops
sometimes you want to repeat a task multiple times, in computer programming, this is called loops, common ansible include changing Ownership on several files and/or directives with the files module, creating multiple, users with the user module , and repeating a polling step until certain result is reached.
vi loops.yml
--- # loops playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
tasks:
- name: add a list of users
user: name='{{item}}' state=present
with_items:
- manjeet
- yadav
- rohit
- sonam
- suresh
..................................
Conditions
Whenever we have diff diff scenarios,
we put conditions according to the scenario
when statement
sometimes you want to skip a particular cmd in a particular node
vi condition.yml
--- # loops playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
tasks:
- name: install httpd service centos
command: yum -y install httpd
when: ansible_os_family == "RedHat"
- name: install apach service on ubuntu
command: apt-get -y install apache2
when: ansible_os_family == "Debian"
.....................................
Vault - passwd protected
Ansible allows keeping sensitive data such as passwords on keys in encrypted files, rather than a plaintext in your playbook
creating a new encrypted playbook
ansible-vault create vault.yml
editing the encrypted playbook
ansible-vault edit vault.yml
To change the password
ansible-vault rekey vault.yml
To encrypt an existing playbook
ansible-vault encrypt target.yml
To decrypt an encrypt playbook
ansible-vault decrypt target.yml
Run vault playbook
ansible-playbook vault.yml --ask-vault-pass
.............................................
ansible-galaxy init rolename
Roles structure
dummy/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml
Default: Contains the default variables that are going to be used by this role.
Files: Contains files that can be deployed by this role. It contains files that need to be send to the hosts while configuring the role
Handlers: Contains handlers which may be used by this role or even anywhere outside this role.
Meta: Defines metadata for this role. Basically, it contains files that establish role dependencies.
Tasks: Contains the main list of tasks that are to be executed by the role. It contains the main.yml file for that particular role.
Templates: Templates contains files which can be modified and added to the host being provisioned Jinja2(template lang) is used to achieve the modifications
Test: This directory is used to integrate testing with Ansible Playbooks.
Var: This directory consists of other variables that are going to be used by the role. These variables can be defined in your playbook, but it's a good habit to define them in this section.
Roles
We can use two techniques for recurring a set of tasks: includes, and roles
Roles are good for organizing tasks and encapsulating data needed to accomplish those tasks
we can organize playbooks into a directory structure called roles
Ansible Roles
adding more and more functionality to the playbook will make it difficult to maintain in a single file.
Roles
Default: It store the data about role/application default variables e.g. - if you want to run to port 80 or 8080 then variable needs to define in this path.
Files: it contains files need to be transferred to the remote VM (state files)
Handler: they are trigger or task we can segregate all the handler required in playbook
Meta: this directory contain files that establish roles dependencies eg. auther name, supported platform, dependencies if any
Tasks: it contains all the tasks that is normally in the playbook, eg installing packages and copies files also.
Vars: Variables for the role can be specified in this directory and used in your configuration files both vars and default store variables
.............................
| |
master.yml roles(dir)
| |
target myroles(sub dir)
| |
roles task(again sub dir)(main.yml)
| |
myroles var(again sub dir)(main.yml)
|
handler(again sub dir)(main.yml)
Roles
mkdir -p playbook/roles/webserver/tasks
tree
touch playbook/roles/webserver/tasks/main.yml
touch playbook/master.yml
vi playbook/roles/webserver/tasks/main.yml
- name: install httpd
yum: pkg=httpd state=latest
vi master.yml
--- # master playbook
- hosts: demo
user: ansible
become: yes
connection: ssh
roles:
- webserver
Ansible modules:
1. copy
The copy module allows you to copy a file from the Ansible control node to the target hosts. In addition to copying the file, it allows you to set ownership, permissions, and SELinux labels to the destination file. Here's an example of using the copy module to copy a "message of the day" configuration file to the target hosts:
- name: Ensure MOTD file is in place
copy:
src: files/motd
dest: /etc/motd
owner: root
group: root
mode: 0644
2. template
The template module works similarly to the copy module, but it processes content dynamically using the Jinja2 templating language before copying it to the target hosts.
- name: Ensure MOTD file is in place
template:
src: templates/motd.j2
dest: /etc/motd
owner: root
group: root
mode: 0644
3. user
The user module allows you to create and manage Linux users in your target system. This module has many different parameters, but in its most basic form, you can use it to create a new user.
- name: Ensure user ricardo exists
user:
name: ricardo
group: users
groups: wheel
uid: 2001
password: "{{ 'mypassword' | password_hash('sha512') }}"
state: present
4. package
The package module allows you to install, update, or remove software packages from your target system using the operating system standard package manager.
- name: Ensure Apache package is installed
package:
name: httpd
state: present
5. service
Use the firewalld module to control the system firewall with the firewalld daemon on systems that support it, such as Red Hat-based distributions.
- name: Ensure SSHD is started
service:
name: sshd
state: started
6. firewalld
Use the firewalld module to control the system firewall with the firewalld daemon on systems that support it, such as Red Hat-based distributions.
- name: Ensure port 80 (http) is open
firewalld:
service: http
state: enabled
permanent: yes
immediate: yes
7. file
The file module allows you to control the state of files and directories—setting permissions, ownership, and SELinux labels.
- name: Ensure directory /app exists
file:
path: /app
state: directory
owner: ricardo
group: users
mode: 0770
8. lineinfile
The lineinfile module allows you to manage single lines on existing files. It's useful to update targeted configuration on existing files without changing the rest of the file or copying the entire configuration file.
- name: Ensure host rh8-vm03 in hosts file
lineinfile:
path: /etc/hosts
line: 192.168.122.236 rh8-vm03
state: present
9. unarchive
Use the unarchive module to extract the contents of archive files such as tar or zip files. By default, it copies the archive file from the control node to the target machine before extracting it. Change this behavior by providing the parameter remote_src: yes.
- name: Extract contents of app.tar.gz
unarchive:
src: /tmp/app.tar.gz
dest: /app
remote_src: yes
10. command
The command module is a flexible one that allows you to execute arbitrary commands on the target system. Using this module, you can do almost anything on the target system as long as there's a command for it.
- name: Run the app installer
command: "/app/install.sh"
Placing the task on ServerB
- hosts: ServerB
tasks:
- name: Transfer file from ServerA to ServerB
synchronize:
src: /path/on/server_a
dest: /path/on/server_b
delegate_to: ServerA
This uses the default mode: push, so the file gets transferred from the delegate (ServerA) to the current remote (ServerB).
Placing the task on ServerA
- hosts: ServerA
tasks:
- name: Transfer file from ServerA to ServerB
synchronize:
src: /path/on/server_a
dest: /path/on/server_b
mode: pull
delegate_to: ServerB
This uses mode: pull to invert the transfer direction.What is configuration management?
Do you think ansible is better than other configuration management tools? If yes, why ?
Can you write an ansible playbook to install httpd service and get it running?
How ansible helped your organization?
what is ansible dynamic inventory?
what is ansible tower and have you used it ? if yes, whay?
How do you manage the RBAC of users for ansible tower?
what is ansible galaxy command and why is it used for ?
can you explain me structure of Ansible playbook using roles?
what are handlers in ansible and why are they used?
i would like to run a specific set of tasks only on windows vms and not linux vms is it possible?
Does ansible support parallel execution of tasks?
what is the protocol that Ansible use to connect to windows vms?
Can you place them in the order of precedence?
playbook group_vars, role vars and extra vars
How do you handle secrets in Ansible?
Can we use ansible for IaC ? Infrastructure as code? If yes, can you compare it with any other Iac tools like terraform?
Can you talk about a ansible playbook, how it helped your company?
what do you think that Ansible can improve?

No comments:
Post a Comment