Saturday, September 24, 2022

Ansible Variable, Condition, Loops,

 Variables in Ansible are nothing but similar to the variables in a programming language. Ansible makes use of variables to better customize the execution of tasks and playbooks. Using variables it’s possible to use the same playbook with different targets and environments. 


You can assign a value to the variable and use it anywhere in the playbook. You can define these variables in your playbooks, in the inventory file, or at the command line. You can also create them during runtime by assigning a return value to the new variable. Once created, you can use them in conditional statements, in loops, or as arguments. 


Define Variable:

A variable name can only include letters, numbers, and underscores and it cannot begin with a number. You can define a variable using standard YAML syntax. For example:


- hosts : web

  vars:

    servicename: apache2



Reference Variable:

{{ servicename }}

In Ansible, a variable is referenced using Jinja2 syntax. Jinja2 variables use double curly braces. Like, the expression servicename is referenced as



- name: using  variable in playbook

  hosts: webserver1

  vars:

     servicename: apache2

  tasks:

  - name: 'creating file using variable'

   service: name={{ servicename }} state=started


===================


Condition:


In an ansible playbook, we sometimes need to execute different tasks depending on the value of a variable or the value of the return variable of a previous task. You may want to perform a certain set of tasks if the value of the variable is less than a value and a different set of tasks if the value of the variable is greater. You can achieve this with Ansible conditions


- name: Install Apache on CentOS Server yum: name=httpd state=present become: yes when: ansible_os_family == "RedHat"


- 
  name: this is our first play.
  hosts: webserver1
  vars: 
    age: 19
  tasks: 
    - 
      name: 'creating file using variable'
      command: touch /tmp/18.txt
      when: age == 18
    - 
      name: 'creating file using variable'
      command: touch /tmp/grater_then_18.txt
      when: age > 18



Loops:

While configuring servers and performing various tasks, you may sometimes need to repeat the execution of the same task using different values. For this purpose we have loops. If when the statement is combined with a loop, Ansible processes the condition separately for each item. Suppose you want to create 50 users at a time. One will have to define a task fifty times for each user. It would be a very inefficient approac

[ansadmin@ip-172-31-45-242 ~]$ cat loop.yml

-

  name: this is our first play.

  hosts: localhost

  become: true

  tasks:

    -

      name: 'installing'

      yum:  name="{{ item }}" state=present

      with_items:

        - vsftpd

        - tree







In any scripting language, we organize our code using classes, methods, variables, etc. and we reference them as required. In the same way, we can modularize the Ansible playbooks to use them efficiently and in an organized manner. We can store the repeated tasks or variables in some other file and reference them in our main playbook. 



- 
  name: this is our first play.
  hosts: webserver1
  vars: 
    var1: var1
    var2: var2
    var3: var3
    var4: var4
    var5: var5
    var6: var6
    var7: var7
    var8: var8
    var9: var9
    var10: var10
  tasks: 
    - 
      name: 'task 1'
      command: touch /tmp/large/{{ var1 }}.txt
    - 
      name: 'task 2'
      command: touch /tmp/large/{{ var2 }}.txt
    - 
      name: 'task 3'
      command: touch /tmp/large/{{ var3 }}.txt
    - 
      name: 'task 4'
      command: touch /tmp/large/{{ var4 }}.txt
    - 
      name: 'task 5'
      command: touch /tmp/large/{{ var5 }}.txt
    - 
      name: 'task 6'
      command: touch /tmp/large/{{ var6 }}.txt
    - 
      name: 'task 7'
      command: touch /tmp/large/{{ var7 }}.txt
    - 
      name: 'task 8'
      command: touch /tmp/large/{{ var8 }}.txt
    - 
      name: 'task 9'
      command: touch /tmp/large/{{ var9 }}.txt
    - 
      name: 'task 10'
      command: touch /tmp/large/{{ var10 }}.txt


In this playbook, there are nearly 10 variables and 10 tasks. This makes our playbook inefficient and unnecessarily huge.


We can store these vars in a separate file variable.yml as follows:

var1: var1
var2: var2
var3: var3
var4: var4
var5: var5
var6: var6
var7: var7
var8: var8
var9: var9
var10: var10

And, in the same way we can store the tasks also in different file tasks.yml:

- 
 name: 'task 1'
 command: touch /tmp/task/{{ var1 }}.txt
- 
 name: 'task 2'
 command: touch /tmp/task/{{ var2 }}.txt
- 
 name: 'task 3'
 command: touch /tmp/task/{{ var3 }}.txt
- 
 name: 'task 4'
 command: touch /tmp/task/{{ var4 }}.txt
- 
 name: 'task 5'
 command: touch /tmp/task/{{ var5 }}.txt
- 
 name: 'task 6'
 command: touch /tmp/task/{{ var6 }}.txt
- 
 name: 'task 7'
 command: touch /tmp/task/{{ var7 }}.txt
- 
 name: 'task 8'
 command: touch /tmp/task/{{ var8 }}.txt
- 
 name: 'task 9'
 command: touch /tmp/task/{{ var9 }}.txt
- 
 name: 'task 10'
 command: touch /tmp/task/{{ var10 }}.txt






Thursday, September 22, 2022

Ansible Roles

 

Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules.

In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of playbook allows you to logically break the playbook into reusable components.


[ansadmin@controller myroles]$ ansible-galaxy init webserver

- Role webserver was created successfully


[ansadmin@controller webserver]$ pwd

/home/ansadmin/myroles/webserver

[ansadmin@controller webserver]$ ls -l

total 4

drwxrwxr-x 2 ansadmin ansadmin   22 Sep 22 18:21 defaults

drwxrwxr-x 2 ansadmin ansadmin    6 Sep 22 18:21 files

drwxrwxr-x 2 ansadmin ansadmin   22 Sep 22 18:21 handlers

drwxrwxr-x 2 ansadmin ansadmin   22 Sep 22 18:21 meta

-rw-rw-r-- 1 ansadmin ansadmin 1328 Sep 22 18:21 README.md

drwxrwxr-x 2 ansadmin ansadmin   22 Sep 22 18:22 tasks

drwxrwxr-x 2 ansadmin ansadmin    6 Sep 22 18:21 templates

drwxrwxr-x 2 ansadmin ansadmin   39 Sep 22 18:21 tests

drwxrwxr-x 2 ansadmin ansadmin   22 Sep 22 18:21 vars





Ansible Sample Playbook

First Playbook:

---
  - name: Playbook
    hosts: webservers
    become: yes
    become_user: root
    tasks:
      - name: ensure apache is at the latest version
        yum:
          name: httpd
          state: latest
      - name: ensure apache is running
        service:
          name: httpd
          state: started



name Name of the playbook


hosts A set of hosts usually grouped together as a host group and defined in inventory file


become To tell ansible this play has to be executed with elevated privileges


become_user the user name that we want to switch to like compare it with sudo su - user


tasks set of tasks to execute, All tasks would be defined below this


and then we have two tasks with two modules, the first module is yum and the second module is service


 become_user is something similar to su , and become means something like sudo su or "perform all commands as a sudo user".



Ansible Playbook examples


  1. Write a Ansible Playbook to create a group called “deploy”
- name: Create a group
  hosts: group
  tasks:
   - name: Add group "deploy"
     group:
       name: deploy
       state: present

2.Write a Ansible Playbook to create a user called “deploy-user” which is part of group called “deploy” and with /bin/bash shell.

- name: Create a user
  hosts: user
  tasks:
    - name: Add user "deploy-user"
      user: 
        name=deploy-user groups=deploy password="" shell=/bin/bash 
        append=yes 
        state=present

3. Write a Ansible Playbook to install package named “httpd” in RHEL/centos.

- name: To install  an httpd webserver
  hosts: web
  tasks:
  - name: Install httpd packages 
    yum:
      name: httpd
      state: present

4. Write a Ansible Playbook to start and enable the service named “httpd”

- name: To start and enable an httpd webserver
  hosts: web
  tasks
    - name: start httpd
    service:
      name: httpd 
      state: started


  - name: enable httpd
    service:
      name: httpd 
      enabled: yes

5. Write a Ansible Playbook to create a file called “index.html” in /var/www/html with some dummy html contents.

- name: creating a file
  hosts: all
    tasks:
    - name: create a file index.html
      file:
        path: "/var/www/htmlindex.html"
        state: touch

    - name: adding contents to indexfile
    blockinfile:
      dest: /var/www/html/index.html
      block: |
        <html>
        <h1> Welcome to HP Ansible class </h1>
        </html>

6. Write a Ansible Playbook to reboot a self machine.

- name: rebooting self machine
  hosts: web
    task:
    - name: Reboot a Linux machine 
        reboot:
        reboot_timeout: 1800

7. Write a Ansible Playbook to install a package called “git”, “wget”.

- name: To install a package "git" and "wget"
  hosts: web
  tasks:
  - name: Install git packages 
    yum:
      name: git
      state: present
 
  - name: Install wget packages 
    yum:
      name: wget
      state: present

8. Write a Ansible Playbook to clone git repo. thttps://github.com/scmgalaxy/ansible-role-template

- name: Cloning git repo
  hosts: web
  environment:
      http_proxy: 'http://web-proxy:8080'
      https_proxy: 'http://web-proxy:8080'
  tasks:
  - name: cloning....
    git: 
      repo=https://github.com/scmgalaxy/ansible-role-template
      clone=yes 
      dest=./ansible-role-template

Ansible Tower

 Ansible Tower is an enterprise solution for Ansible by RedHat.

 It has a web console and REST API to operate Ansible across our team, organization, and enterprise. 

It also provides role-based access control,  job scheduling, integrated notification, and graphical inventory management. 

It is a centralized hub for all our automation tasks. 

It can be easily integrated with third-party tools and processes using the REST API and CLI.





YAML

 YAML

As mentioned earlier, YAML (Yet Another Markup Language) is a human-readable programming language. YAML syntax is used to express the Ansible playbooks.

Here are some basic concepts of YAML.

  • Key/Value pair:

Dictionary is represented in key/value pairs.

    • Example:
james:
name: james john
rollNo: 34
div: B
sex: male
  • Representing lists:

Each element in a list has to be written in a new line with ‘-‘ as a prefix.

    • Example:
countries:
- America
- China
- Canada
- Iceland
  • Lists inside a dictionary:

We can have lists inside a dictionary.

    • Example
james:
name: james john
rollNo: 34
div: B
sex: male
likes:
- maths
- physics
- english

Wednesday, September 21, 2022

Ansible Introduction

Ansible

Ansible refers to an open-source automation platform or tool that is useful for different IT tasks like configuration management, intra-service orchestration, application deployment, and provisioning. Automation is vital for managing complex IT environments and simplifying the complex tasks of the developers. Ansible is a top automation tool that helps in overcoming the challenges of automation and ensures better productivity gains.

It is simple, powerful and agentless. The biggest differentiator between Ansible and other tools lies in the architecture; it works on the “Push” model, i.e. no additional software is required to be installed in the server. By default it manages remote connections over SSH (Linux & Unix) or WinRM (windows).

Some of the top benefits of Ansible are:

Free – Ansible is an open-source tool that is available to the users for free.

Simple – Most users might worry about how Ansible works. But in reality, the setting up process, as well as the use, is very simple. The use of ansible software requires no exceptional skills in coding.

Efficient – Ansible is an efficient software. It requires no additional software for installation but offers room for the application resources on the server of the user.

Powerful – Ansible is a powerful tool that helps the users to model the highly complex workflows of the IT industry efficiently.

Agentless – The main benefit of using Ansible is that it is agentless. Without the use of any additional software, the clients can easily automate their systems.

Flexible – Irrespective of where the software is deployed, it allows the users to orchestrate the whole environment of the application.

Extensible – Depending on the networking and automation needs of the users, Ansible can easily offer extensions.





Simple Ansible Architecture



Is Ansible Free?

Yes, Ansible is an absolutely free and open source tool that is used for the above-mentioned purposes. Because Ansible adopts the standard GNU (General Public License), it can be used for commercial purposes as well as long as one respects the policies of GNU.


Why Ansible?

A single bash script would be great if you have to manage and configure a single system, you are the single user and yours is a single machine. But when you scale up across more number of computers, multiple tasks, more users and more admins, you will discover that the bash scripts are not enough and efficient. This exactly where Ansible comes into the picture. Ansible can be treated as nurtured bash or shell scripting that can configure your huge infrastructure topology in one go.

Plus, Ansible uses a very simple language called YAML (YAML Ain’t Markup Language) in the form of Ansible playbooks that allows you to describe your automation task in a way that is as good as colloquial language.


Ansible Components:

Master: This is the main machine that takes care of the configuration of machines with Ansible.
Inventory: An inventory is a file that describes the nodes that are accessible by Ansible. 
The nodes can be grouped in the inventory file and named accordingly
Playbook: YAML files that describe the automation tasks to be done by Ansible.

Simple Playbook:
---
hosts: localhost
- name: install python
  yum: name=python state=installed

Task: This is the block that describes the action to be taken by Ansible in statements. Ex: Install httpd.
Module: These are the executable plugins that do the task for us. There are many inbuilt modules which Ansible provides us. We can write our own custom-modules too.
Role: An Ansible playbook can get really huge in size over time and maintaining it would be really tough. Hence with roles, one can group the tasks into subsets and manage the content efficiently. These roles (groups of tasks) can be reused accordingly.
Play: Execution of a playbook is called a play.
Facts: These are the global variables that will be referred across Ansible playbooks.
Handlers: Used to invoke service status changes, like restarting or stopping a service or install or uninstall a package.

Following are the advantages mentioned below:

Ansible manages the machines in an agentless You do not have to install any Ansible agents/service software on the client machine.

Both push and pull of files/commands/codes are supported in Ansible.

Ansible is a security-focused tool. And it uses OpenSSH as the secure transport protocol.

Ansible scripts (popularly called as playbooks) are written in YAML and hence they are very easy to read.

Ansible is The core idea here is that you only do things if they are needed and things that are repeated without side effects.

If needed, then Ansible can easily connect with Kerberos, LDAP (Lightweight Directory Access Protocol) and other centralized authentication management systems.

An advantage of higher order significance is that one need not be an expert in bash or shell scripting.
 Ansible has it handled by itself. So, the working becomes quite easy and straight forward with Ansible.

One doesn’t really need to be a root user to run the Ansible playbook tasks on the nodes. It can acquire root privileges.

Adhoc Command:
Verify connectivity of host:  # ansible  <group> -m -ping
Rebooting host systems:  #ansible <group> -a “/sbin/reboot”
Creating a new user: # ansible <group> -m user -a “name=ansible password=<encrypted password>”
User Deletion: # ansible <group> -m user -a “name=ansible state=absent”
Permissions changing:  # ansible <group> -m file -a “dest=/home/ansible/file1.txt mode=777”
Verify package installation  with update: # ansible <group> -m yum -a “name=httpd state=latest”
Verify package installation without an update: # ansible <group> -m yum -a “name= httpd state=present”
Verify package version: # ansible <group> -m yum -a “name= httpd-1.8 state=present”
Verify package installation: # ansible <group> -m yum -a “name= httpd state=absent”
Display host information:  # ansible <group> -m setup | less

=========================================================================
Ansible Playbook:

Ansible Roles:

Ansible Galaxy:



How Ansible Works:



Ansible Adhoc Command

 Ansible Modules:

-------------------------

Ping Module:

ansible testservers -m ping


File module: Creating and deleting directory


ansible testservers -m file -a "dest=/root/file state=directory"

ansible testservers -m file -a "dest=/root/file mode=755 owner=root group=root state=directory"

ansible testservers -m file -a "dest=/root/file state=absent"


Copy Module:


ansible testservers -m copy -a "src=/root/file/text.txt dest=/root/"


Shell Module:


ansible testservers -m shell -a "mkdir test"


Yum Module:


ansible testservers -m yum -a "name=wget state=present"

ansible testservers -m yum -a "name=httpd state=present"



Service Module:


ansible testservers -m service -a "name=httpd state=restarted"

ansible testservers -m service -a "name=httpd state=started"

ansible testservers -m service -a "name=httpd state=stopped"


Restarting the servers:


ansible testservers -a "/sbin/reboot"



ansible all -m ping -- > Check connectivity between master and worker nodes

ansible all -m setup -- > collect ansible facts of worker nodes

ansible all -m file -a "dest=/home/ansadmin/test-file state=directory"  -- > Create new directory on worker machine

ansible all -m file -a "dest=/home/ansadmin/test-file state=absent" -- > Delete the directory from worker machine

ansible all -m shell -a "uptime"

ansible all -m shell -a "df -h "

ansible all -m shell -a "mkdir test-server"

ansible all -m shell -a "rmdir test-server"

ansible all -m copy -a "src=/etc/ansible/sample.txt dest=/home/ansadmin" --> copy file from source to destination(remote server)

ansible all -m yum -a "name=httpd state=present" -b -- > Install a software (httpd) on remote machine

ansible all -m service -a "name=httpd state=started" -b -- > start the service on worker node

ansible all -m user -a "name=vikas" -b --> Create a new user

ansible all -m user -a "name=vikas state=absent" -b --> delete the user

ansible all -a "/sbin/reboot" -b  --> reboot command

ansible all -a "free -m" all

ansible all  -a "df -hT -m" all

ansible all  -m command  -a "uptime" all

ansible all -m shell  -a "free -m" all

ansible all -m shell  -a "cat /etc/passwd" all

ansible all  -m apt  -a "name=nginx  state=present" --become  all

ansible all -m apt  -a "name=nginx  state=absent" --become  all

ansible all  -m service -a "name=nginx  state=started" --become  all

ansible all  -m service -a "name=nginx  state=stopped" --become  all

ansible all  -m service -a "name=nginx  state=restarted" --become  all

ansible all -m file -a "path=/home/ubuntu/ansible state=directory" all

ansible all -m file -a "path=/home/ubuntu/sample.txt  state=touch" all

ansible all -m copy -a "src=/etc/hosts dest=/opt/hosts" all --become

ansible all -m group -a "name=unix state=present" all --become

ansible all -m group -a "name=unix state=absent" all --become

ansible all -m user -a "name=kajal state=present" all --become

ansible all -m user -a "name=kajal state=absent" all --become

ansible all   -m user -a "name=archana group=unix" all --become

ansible all -m shell -a "touch /home/ubuntu/file1.txt" all  --become

ansible all   -m user -a "name=archana password=unix@123" all --become

ansible allt -m shell -a "systemctl status sshd" all  --become

Sample Game App Deployment on EKS cluster

 https://padmakshi.medium.com/setting-up-an-eks-cluster-and-deploying-a-game-application-a-step-by-step-guide-08790e0be117