Shashikant shah

Thursday, 29 October 2020

Ansible terms details part-11

 

1.Ad-Hoc :- Ansible ad-hoc commands are the commands that we can directly run from the terminal on one or more managed clients.

2.playbboks:- Ansible playbook is a file that contains a set of instructions or configurations that needs to be applied on a specific server or a group of servers. It is written in YAML.

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

4.tags :- Ansible tags are another great feature which can help you execute respective tasks from the playbook.

5.apt :-  Ansible Apt is one of the modules of Ansible that is used to manage packages on Debian or Ubuntu-based OS. package installing.

6.facts :- Ansible facts are the information of remote hosts which is gathered by the Ansible controller. This information is stored in predefined variables on the controller node and the whole set of this information is prepared in JSON format.

7.anisble 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.

8.ansible Galaxy :- Ansible Galaxy is a web-based online and open-source repository for sharing and finding Ansible content mostly roles and collections.

9.handlers :- based on notify do something specified. Triggers restart service.

10.Loop :- Ansible loop is used to repeat any task or a part of code multiple times in an Ansible-playbook.

11.Block / error handling :- getting error single task then skip error task and run other task.

12.Conditional :-

13.debug :- debug module with a verbosity parameter that transforms it from a print line.

14.synchronize :- this module use for copy and update ansible server to remote node.

15.template :- In Ansible, template module is used to copy data from controller nodes to remote hosts, this data is generated based on jinja2 templates.

16.lookup:-

17.group_vars :- missing 

18.yum :- for package install (latest, present, installed, absent, removed)

19.shell :- we have a shell module that is used to run commands on /bin/shell on target remote machines.

20.lineinfile :- We can insert a line in a file using the ‘lineinfile’ module.

21.service :- service start/stop (reloaded, restarted, running, started, stopped) 

22.user :- we create a user on remote machines.

23.ansible-doc :-  we will see how to get documentation for the Ansible module.

24.filters :- 

25.Register :- These are the variables in which the output of your task will be stored on the Ansible Control Server. In simple words, when you want to run a command on a remote computer and then store the output in a variable and use a piece of information. 

26.set Fact :- The variable assignment under set_fact is done by using key-pair values where the key is the variable name and value is the assignment to it.

27.hosts file :- Ansible environment, though the default location for hosts file is /etc/ansible/hosts.

28.dynamic inventory :- Dynamic Inventory, which fetches the list of nodes from infrastructure environment in real time based on some criteria.

29.local_action :- When delegate_to is used to delegate a task on the local machine either using hostname localhost.

30.sudo :-

31.Run_once :- run_once parameter is used with a task, which you want to run once on first host.

32.unarchave :-

33.firewalld :-

Sunday, 25 October 2020

ansible create ec2 instance and remove part-10

 How to create ec2 instance from ansible server.

  • Create IAM user .


  • Give to full access Permission.

  • Download key.


# vim  ~/.boto

[Credentials]

AWS_ACCESS_KEY_ID=AKIA3V6PJVJF3DUHGPIV

AWS_SECRET_ACCESS_EY=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


# vim  aws_provisioning.yml

---

- name: create a new Demo ec2 instance

  hosts: localhost

  connection: local

  gather_facts: False

  vars:

    instance_type: t2.micro

    security_group: default

    image: ami-032930428bf1abbff

    keypair: shashi

    region: us-east-1

 

  tasks:

    - name: create an ec2 instance

      ec2:

         key_name: "{{ keypair }}"

         group: "{{ security_group }}"  # security group name

         instance_type: "{{ instance_type}}"

         image: "{{ image }}"

         wait: true

         region: "{{ region }}"

         count: 1  # default

         count_tag:

            Name: Demo

         instance_tags:

            Name: Demo

         vpc_subnet_id: subnet-fb2bf1da

         assign_public_ip: yes

 

 How to remove instance from aws.

# vim aws_delete.yml

---

- hosts: localhost

  connection: local

  tasks:

    - name: Terminate instances that were previously launched

      ec2:

        state: 'absent'

        instance_ids: i-0256423e26c55a621

        region: us-east-1

 

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