Shashikant shah

Thursday 22 October 2020

Ansible Roles and Galaxy part-9

 What is ansible Role :-

  1. Roles provide a framework for fully independent or interdependent collections of files, tasks, templates, variables, and modules. The role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks and makes them easier to reuse. The breaking of the playbook allows you to break the playbook into reusable components.
  2. This is a standardized structure for all Ansible roles, which allows Ansible playbooks to automatically load predefined variables, tasks, handlers, templates, and default values located in separate YAML files.
  3. Roles are not playbooks. Roles are small functionality that can be used within the playbooks independently. Roles have no specific setting for which hosts the role will apply.

# ansible-galaxy -h 

ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ... 

  • -h: (help) it shows this help message and exit.
  • -v: (verbose) Verbose mode (-vvv for more, -vvvv to enable connection debugging).
  • --version: it shows program version number and exit.
1. How to create a Roles.

# ansible-galaxy init nginx_role 



Defaults ==> Data about the Role/ application . default variables.

files       ==> put the static files here. Files will then be copied on remote machine.

handlers  ==> based on notify do something specified. Triggers restart service.

meta       ==> Information about the role. Author, supported platforms, dependencies, etc.

tasks       ==> List of taks to be executed by the role.

templates ==> Similar to files except that templates support dynamic files. Jinja2 -template language

                        dynamic variable use in nginx.conf file

tests        ==> if you want additional verification of your build.

vars         ==> Both vars and defaults stores variable. Variables stored under “vars” has got higher                                 priority and difficult to override.

Example.1:- This Role for first task copy script.sh file and update DNS resolv.conf file.

# ansible-galaxy init nginx_role

1.Defined tasks

# vim /etc/ansible/nginx_role/tasks/main.yml






2. Script.sh Keep in a files directory.

# cp -rf script.sh nginx_role/files

3.Create a template in a 

# vim templates/resolv.conf.j2

nameserver {{ dns }}

4.defined variable in a vars directory.

# vars/main.yml

---

# Variables

 dns: templates.8.8.8.8

5.Create playbook for run Role.

# vim /etc/ansible/role-main.yml

---

- hosts: jenkins

  gather_facts: false

  roles:

   - {role: 'nginx_role', tags: 'nginx_role'}


Check file from remote server.





Example.2 :-  Web service install and start service and copy index.html file on remote server. 

1.create a task.







2.create a index.html in files directory .






3.defined role details.









4.handlers defined.









5.Create a play-book for role.








 
# ansible-playbook web.yml













6. Multiple role running using loop. 

--- # Master playbook for webservers
- hosts: demo
  user: ansible
  become: yes
  connection: ssh
  vars:
    packages:
     - name: webserver
       required: True
     - name: newserver
       required: False
  tasks:
    - include_role:
        name: "{{ item.name }}"
      when:
        - item.required == True
      loop: "{{ packages }}"
 
 
7.Creating Role and copy my_app.conf file from ansible to client.
 
# /root/anisble_project

# site.yml

---

- hosts: client_host

  become_user: ansadm

  become: yes

  become_method: sudo

#  sudo: yes

  roles:

     - Security-Hardening

# ansible-galaxy init roles/Security-Hardening

#ls /root/anisble_project/roles/Security-Hardening

# cd vars

#cat main.yml

hardening_artefact_name: "Security_Hardening_Artifacts_{{ ansible_date_time.iso8601_basic_short }}.txt"

hardening_artefact_path: "/home/Automation/Reports/"

 

#cd tasks

#vim main.yml

---

# tasks file for Security-Hardening

- name: Check availability for Artefacts Report path "{{hardening_artefact_path}}"

  file: path="{{hardening_artefact_path}}" state=directory

  delegate_to: 127.0.0.1

- include: httpd_file_check.yml

#vim httpd_file_check.yml

- name: "httpd_file task"

  vars:

    env: staging

  block:

    - name: template file onto remote hosts

      template:

          src: my_app.conf.j2

          dest: /tmp/my_app.conf

# cd templates/

#vim my_app.conf.j2

env = {{ env }}

local_ip = {{ ansible_host }}

local_user = {{ ansible_user }}


#client side  my_app.conf file created.

#cat /tmp/my_app.conf

env = staging

local_ip = 172.31.42.127

local_user = ansadm

 
 
 
 
 8. Multiple template (j2) files copy to client.

- name: "httpd_file task"

  vars:

    env: staging

    my_app_version: v1.1

  block:

    - name: template file onto remote hosts

      #delegate_to: 127.0.0.1

      template:

          src: "{{ item }}.j2"

          dest: "/tmp/{{ item }}"

          owner: ansadm

          group: ansadm

          mode: 0600

      become: true

      loop:

        - my_app.conf

        - my_app-release

# cd templates/

# cat my_app-release.j2

MyApp tomcat {{ my_app_version }}

#cat my_app.conf.j2

env = {{ env }}

local_ip = {{ ansible_host }}

local_user = {{ ansible_user }}

configuration file create in client server on /tmp path.

9. This task for found /etc/security/limits.conf file and add parameter and generate logs in local machine.

1.       If First Task will fails, then other task will be skipped.

2.       Any tasks failed then rescue block will be executed.

3.       Any task may fail or pass, but the always block will be executed.

Some parameter add in Ansible.cfg

1.root permission          

[privilege_escalation]

become=True

2.remote user

remote_user = ansadm

# cd anisble_project


 







# vim site.yml

[root@prometheus anisble_project]# cat site.yml

---

- hosts: client_host

  #become_user: ansadm

  become: yes

  #become_method: sudo

  roles:

     - Security-Hardening

# mkdir -p roles

# ansible-galaxy init roles/Security-Hardening

# cd /roles/ Security-Hardening/tasks


# vim main.yml

---

# tasks file for Security-Hardening

- name: Check availability for Artefacts Report path "{{hardening_artefact_path}}"

  file: path="{{hardening_artefact_path}}" state=directory

  delegate_to: 127.0.0.1

- include: httpd_file_check.yml

 

 

# vim httpd_file_check.yml

- name: "3_limit_conf"

  block:

    - name: Check if limits.conf file exists

      stat: path=/etc/security/limits.conf

      register: file_path

 

    - name: Create backup of the file /etc/security/limits.conf

      shell: cp /etc/security/limits.conf /tmp/limits.conf_{{ansible_date_time.date}}.bkp

      register: backup

      when: file_path.stat.exists

 

    - name: Set maxlogin in limits.conf file

      lineinfile:

         path: /etc/security/limits.conf

         regexp: ^\*\s+\-\s+maxlogins\s.*

         line: '*                -       maxlogins       1'

      register: output

      when: file_path.stat.exists

 

    - name: Grep the final value

      shell: "cat /etc/security/limits.conf |grep maxlogins"

      register: result

 

  rescue:

    - name: "write rescue to temp file"

      delegate_to: 127.0.0.1

      template: src=log_limit.j2 dest="/tmp/shashi_log"

 

  always:

    - name: "write always to temp file"

      delegate_to: 127.0.0.1

      template: src=log_limit.j2  dest="/tmp/shashi_log"

 

# vim vars/main.yml

hardening_artefact_name: "Security_Hardening_Artifacts_{{ ansible_date_time.iso8601_basic_short }}.txt"

hardening_artefact_path: "/home/Automation/Reports/"

 

# vim templates/log_limit.j2

log file {{ ansible_date_time.date }} {{ ansible_date_time.time }} output<>

 

{% if file_path.stat.exists %}

File is found ... in {{file_path.stat. exists}}

{% else %}

File is not found..! in {{file_path.stat. exists}}

{% endif %}

 

{% if backup.failed %}

Failed to execute command. "{{backup.cmd}}"

{% else %}

Command executed Successfully. "{{backup.cmd}}"

{% endif %}

 

{% for result in backup.stdout_lines %}

{{result}}

{% endfor %}

 

Updating "maxlogins" in {{file_path.stat.path}}

 

{% if output.failed %}

Some Error!! Couldn't change the file content

{% elif output.changed %}

Value "*                -       maxlogins       1" is successfully updated in file.

{% else %}

Values "*                -       maxlogins       1" is already accurate in file.

{% endif %}

 

 

{% if result.failed %}

Failed to execute command

{% else %}

Command "{{result.cmd}}" is executed Successfully

{% endif %}

{% for result1 in result.stdout_lines %}

{{result1}}

{% endfor %}

# cat /tmp/shashi_log


################################

# check web server










1.What is Ansible Galaxy :-

Is a repository of some community-maintained roles

You can download roles or upload roles to ansible galaxy.

# ansible-galaxy –help

[root@ansible ~]# ansible-galaxy --help

# ansible-galaxy search ntp

# ansible-galaxy info bennojoy.ntp

# ansible-galaxy install bennojoy.ntp

# ansible-galaxy list

# cd /etc/ansible/roles/bennojoy.ntp/

[root@ansible ~]# vi ntpsite.yaml

---

 - name: Configure NTP on CentOS/RHEL/Debian System

   become: true

   hosts: all

   roles:

    - {role: bennojoy.ntp}

# ansible-playbook -i hosts ntpsite.yaml

2.How to upload role in galaxy .
i) role push to git repo and git portal login.
ii) login galaxy portal and show below message. 

 






my content ==> +Add content ==> Import role from Github ==> give repo name ==> ok

No comments:

Post a Comment