Skip to main content

Ansible

 What is Ansible

Ansible is a configuration management, deployment and orchestration tool.

Features of Ansible

  1. Simple: Simple to install and setup
  2. Built on top of Python: Provides lot of python functionality.
  3. SSH for Secure Connection 
  4. Agentless
  5. Platform independent 
  6. Push Based unlike Puppet and Chef

Install and Setup:

  1. Install Ansible via pip install ansible 
  2. Generate SSH-Key on Master node using ssh-keygen -t rsa
  3. Goto /root/.ssh and copy id_rsa.pub key to all other nodes and 
  4. Run ssh-copy-id <Destination IP Address>
By default, Ansible configuration file is located under /etc/ansible/ansible.cfg and inventory file is pointed to /etc/ansible/hosts

ansible --version shows the version of ansible is using and the configuration file it is pointing to.

We can create our own inventory file
filename - inventory.ini

[web_servers] 
web01
web02

[db_servers]
db01
db02

Create a ansible.cfg file under working directory or edit the default configuration under /etc/ansible and update the inventory entry under defaults.
filename - ansible.cfg

[defaults]
inventory = /root/ansible

[previlege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False 

ansible-inventory -y --list ==> Lists all the hosts specified in the inventory file.
ansible web_01 --list-hosts ==> Check whether host is present within inventory file.


Connection Settings in Configuration File
  1. remote_user specifies the user you want to use on the managed host. If you do not specify, it uses current user name.
  2. remote_port default is 22
  3. ask_pass controls whether ansible will prompt you for SSH password. By default, it is assuming you're using SSH key based authentication.
Privilege Escalation Settings in the Configuration File
  1. become controls whether you will automatically use privilege escalation. default no
  2. become_user controls what user on the managed host ansible should become. default root
  3. become_method controls how ansible will become that user. default sudo.
  4. become_ask_pass controls whether to ask for password for your become method. default is no.
Typical ansible.cfg file

[defaults]
inventory = ./inventory.ini
remote_user = ansible
ask_pass = false
[privilege_escalation]
become = true
become_user = root
become_ask_pass = false


Host Based Connection Variables

Create a file with the same name as host under host_vars directory
Following variables overrides variables under configuration file. 
filename : host_vars/db_01.ini

#connection variables for db_01
ansible_host: 127.0.0.1
ansible_port: 3456
ansible_user: root
ansible_become: false


ansible all -m ping to check all the hosts mentioned within inventory file are accessible.

ansible web_servers --limit web01 -m ping

ansible doc -l to list all the available modules.

Ansible Playbooks

A playbook is a yaml based text file containing list of one or more plays to run in a sequential order.

simple playbook example :

- name: Check daya user exists or not
  hosts: all
  become: yes
  tasks:
     - name: daya user exist or not
       user:
         name: daya
         state: present
     - name: ensure nginx is at the latest version
       apt:
         name: nginx
         state: latest
     - name: start nginx
       service:
          name: nginx
          state: started


Dry run
ansible-playbook -C playbook_name.yml

Run 
ansible-playbook playbook_name.yml

To Run on a specific host
ansible-playbook --limit hostname playbook_name.yml

variable defined in the ansible can be overridden from command line using -e argument.

---
name: New user is created
hosts: web_servers
become: true
vars:
  username: test
tasks:
  - name: User gets created.
    user:
       name: "{{ username }}"
       state: present


you can override above username test by supplying -e argument while running the playbook 
ansible-playbook -e "username=daya state=present" playbook_name

Managing variables in playbooks

There are multiple ways to user variables 
One common way is to place a variable in a vars block at the beginning of the play.

- hosts: all
   vars:
        user_name: joe
        user_state: present
It is also possible to define variables in a external file and reference it inside a play
- hosts: all
   vars_files:
        - vars/users.yml


Referencing a variable inside the play

- name: Example Play
   hosts: all
   vars:
      user_name: joe
    tasks:
        - name: Creates the user  {{ username }} 
           user:
               name: "{{ user_name }}"
               state: present

Using list to install several packages as part of the task in a play

---
- name: Install Packages
   hosts: all
   vars:
        packages:
            - nmap
            - httpd
            - php
            - mod_php
            - mod_ssl
tasks:
    - name: Install software
      yum:
         name: {{ package }}
         state: present


Ansible-Vault - Protecting Sensitive data

  1. ansible-vault create filename to create a new file 
  2. ansible-vault view filename to view encrypted file
  3. ansible-vault edit filename to edit an encrypted file
  4. ansible-vault encrypt filename to encrypt existing file
  5. ansible-vault decrypt filename to decrypt a file
  6. ansible-vault rekey filename to change the password of an encrypted file

Playbooks and Ansible-vault

ansible-playbook --vault-id @prompt filename
@prompt option will prompt the user for ansible vault password

We can set a label on encrypted files using --vault-id
example: ansible-vault encrypt filename --vault-id vars@prompt

we can run the pipeline using 
ansible-playbook --vault-id vars@prompt playbook_name 

Debugging inside a task using debug module

- name : Print Variable 
   debug: 
        msg: "{{ secret }}"


If we want to suppress output log, we can perform using no_log option 

- name : Print Variable 
   debug: 
        msg: "{{ secret }}"
    no_log: true

Running Tasks Conditionally

The when statement is used to run a task condtionally.

---
- name: Simple Boolean Task 
   hosts: all
   vars:
       run_my_task: true
   tasks:
     - name: httpd package is installed
        yum:
            name: httpd
        when: run_my_task


another example: It tests whether variable is defined.

---
- name: Test Variable is Defined Demo
   hosts: all
   vars:
       my_service: httpd
   tasks:
     - name: "{{ my_service }} package is installed"
        yum:
            name: "{{ my_service }}"
        when: my_service is defined

other examples for when condition

  1. ansible_machine == 'x86_64'
  2. max_memory == 512
  3. min_memory >= 128
  4. variable exists <variable> is defined
Another best example for checking machine is in supported OS 

- name: Demonstrate "in" in a condition
   hosts: all
   gathered_facts: yes
   become: yes
   vars:
      my_service: httpd
       supported_os:
            - RedHat
            - Fedora
    tasks:
       - name: Install "{{ my_service }}"
          yum:
             name: "{{ my_service }}"
              state: present
          when: ansible_facts['distribution'] in supported_os

The ansible_facts['distribution'] variable is a fact set when the play runs, which identifies the operating system of the currently managed host.

The supported_os variable contains a list of operating systems supported by the playbook.

Testing multiple conditions using and or keywords

example: 
  • when: ansible_distribution == "RedHat" or ansible_distribution == "Fedora"
  • when ansible_distibution_version=="7.5" and ansible_kernel =="3.10.0-327.e17.x86_64"

Ansible Handlers

Sometimes when a task does make a change to the system, a further task may need to be run.
For example, a change in service configuration file may then require that the service be reloaded so that changed configuration takes effect.
Handlers are tasks that respond to a notification triggered by other tasks.
Tasks only notify their handlers when the task changes something on managed host.
Each handler get triggered at end of a block of tasks in a playbook.

example

tasks:
   - name: copy demo.example.conf configuration template
      template: 
           src: /var/lib/templates/demo.example.conf.template
            dest: /etc/httpd/conf.d/demo.example.conf
      notify:
            - restart apache
handlers:
    - name: restart apache
       service: 
            name: httpd
            state: restarted 








Comments

Post a Comment

Popular posts from this blog

Kubernetes ETCDCTL

ETCD is a key-value data store for storing kubernetes state and objects. ETCDCTL is the tool used to back up with snapshot. ETCDCTL a command line tool for interacting with the etcd server  Key Features:  Keep the event history until compaction. access to old version of keys. user controlled key compaction. Support range query. pagination support with limit argument. support consistency guarantee across multiple queries. Replace TTL key with lease. Support watch feature. ETCDTOOL Installation: Build binary from source code  Download tool directly  Build binary from source code: Checkout the code repository git clone -b v3.4.16 https://github.com/etcd-io/etcd.git Change directory to etcd cd etcd Run build script ./build The binaries are under the bin directory. exportPATH="$PATH:`pwd`/bin" Check etcd version etcd --version Download ETCD tool directly: kubectl exec -it etcd-docker-desktop -n kube-system -- /bin/bash -c 'ETCDCTL_API=3 /usr/local/bin/etcd --version' | h

Selenium Basic Commands.

Selenium Commands, Packages and Exceptions. Here I have selected few most frequently asked commands in the interview. Recommended way of Importing webdriver from selenium package. from selenium import webdriver. Once webdriver is imported then you are able to access the classes like this webdriver.Firefox webdriver.FirefoxProfile webdriver.Chrome webdriver.ChromeOptions webdriver.Ie webdriver.Opera webdriver.PhantomJS webdriver.Remote webdriver.DesiredCapabilities webdriver.ActionChains webdriver.TouchActions webdriver.Proxy To launch the application URL: driver = webdriver.Chrome driver.get('http://youtube.com') To get URL of the currently loaded page: driver.current_url To close the current window: driver.close() Exceptions in Selenium: Base Exception class: Selenium.common.exceptions selenium.common.exceptions.WebDriverException selenium.common.exceptions.InvalidElementStateException selenium.common.exceptions

Selenium - Architecture

Selenium Architecture: Here, we will learn about the overall selenium architecture. How communication happens from client library to browser and which are all the components involved between them. Architecture compromises of major four components namely Selenium Language Binding JSON Wire Protocol Browser Drivers Real Browsers 1. Selenium Language Binding: Various programming languages provide their own Rest API support for communicating to their respective browser drivers via JSON Wire protocol. python provides 'selenium ' as a client library which has all the rest API i mplementation  for communicating with browser drivers. Selenium is a third party library which does not come in python basic installation.  You need to install it via PIP command : pip install selenium driver = selenium.webdriver.Chrome('location of the chrome driver executable')  Above line returns one chrome browser session , where rest all browser relate