How to work with modules in Ansible?

0
79
Spread the love
  • 28
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    137
    Shares

Ansible
Ansible

Ansible modules takes argument as key value pair (key=value)to perform a task in the remote machine.The response comes in JSON format.

Ansible modules do not do any changes if they are not required.This makes ansible very fast in execution It will simply say skipped about the command,otherwise it will say success.

How to get help about a module?

Ansible provides a command called ansible-doc which is the help file about the module we want to inspect.

To get a list of all modules along with a short description of each module.

>ansible-doc-l

To see help file for a particular module

>ansible-doc modulename/file

Setup Module:

One of the important module of Ansible is setup module.Setup module connects to the clients and gathers data about the system and then returns those values.
To run any ansible module,we need to pass two/three parameters-

  • Host Pattern -> Host pattern to match the machine.(client)
  • Module name -> Which module we want to use.

Host pattern supports group name, a machine name,a glob,a tilde(~) with regular expression. We can select all or * to select all machines.

>ansible<hostname>-u root -k -m setup
>ansible<hostname>-m setup
Field Example Details
ansible_architecture x86_64 The client machine’s architecture
ansible_distribution REHL The client machine’s Linux or Unix distribution.
ansible_distribution_version 8.0 The client machine’s Linux or Unix distribution version.
ansible_domain techtravelhub.com The domain name part of server’s hostname.
ansible_fqdn webserver.techtravelhub.com fully qualified domain name of the client machine.
ansible_interfaces [“lo”,”etho”] A list of all the interfaces including loopback interfaces of the client machine.
ansible_kernal 2.9.32_842.el6.X86_64 The kernel version of the client machine.
ansible_memtotal_mb 10000 The total memory in MB available in client machine.
ansible_processor_count 2 The client machines CPU available.
ansible_virtualization_role guest if the client machine is a guest or a host machine.
ansible_virtualization_type kvm The client machines virtualization setup.

If you have installed tractor or Ohai installed on the client machine,the servers Python automatically fetch these information.

Command module

Command module allows us to write and execute any arbitrary command on the managed machine.

The arbitrary command can be

  • Pre Provided installer.
  • Self written custom script.
  • rebooting of machine.

Command module does not run the command within shell, so redirection is not possible (Like pipe,expand shell,background command).

How to work with modules in Ansible?

Ansible modules

>ansible-doc-l|more
>ansible-doc-l|wc-l =>1378
>ansible-doc-s file (attribute)

These commands are used to list the modules and check its functionalities.

Playbook Modules

The command line usage of module is different than playbook module as many facts may come from another modules.Apart from these few modules just do not work in ansible command line as the required access may not be obtained.

The popular modules for playbook are-

  • The template module
  • The set-fact module
  • The pause module
  • The wait-for module
  • The assemble module
  • The add_host module
  • The group_by module

The template module

The template module allows us to design an outline of a configuration file.The actual values can be inserted later.The template is predefined set of contents where we just need to put data as per requirements and situations.Whenever,there is a need for dynamic change in the content,we use template in ansible.Templates are written in Jinja2 format.

>ansible-doc-s template

will show the details of template.Destination and source are two required parameter for ansible.Jinja2 format template can hold conditions,for loops,and other macro.

The template creation-
>vi index.j2(jinja2 file)
<html>
<head>
<body>
The host is {{ansible_hostname}}
The page is copied at {{ansible_date_time.time}}
//These two variables are coming from facts
Please contact system admin{{name}}for any issue.
//variable coming from playbook .
</body>
</html>

Lets create a playbook

- - -
  -hosts:all
    user:ansadmin
    become:true
    become_method:sudo
   vars:
    name:"techtravelhub"
   tasks:
    -name:copy the jinja2 template on the client machine
   -template:
     src:"/etc/ansible/index.j2"
     dest:"temp/index.html"
…

Note-Since the content is dynamic inture,copy module does not work. Copy module only works on static content.So, in this condition we need to use template module.

Loop in jinja2 file
Options{
listen_on port 80{
127.0.0.1
{% for ip in ansible_all_ipv4_addresses%}
{{ip}}
{%endfor%}
};
Comments in Jinja2 file:

Anything in between {# and #} is ignored by jinjaz processor.Comments are not required but best practice to include what we are trying to do.Jinja2 supports if and end if.To enable if loop,we need to put if tag as true.Otherwise anything between {% if %} and { % endif %} is ignored.

{#variables for zone config#}
{% if 'authorative names' in group_names%}
{%set zone_type='test'%}
{%set zone_dir='testdir'%}
{%else%}
{%set zone_type='actual'%}
{%set zone_dir='actualdir'%}
{%endif%}

The set_fact module:

The set_fact module allows us to build our facts on an ansible play.These facts can be used inside templates or variables in the playbook.Facts may come from setup module.

This helps to avoid complex logic inside template.

Example of set_fact module
- - -
   -name:configure DB server
    hosts:db
    tasks:
     -name:install mysql
       Yum:
        name:"mysql_server"
        state:"installed"
      -name:Calculating InnoDB buffer pool size
        set_fact:innodb-buffer-pool-size-mb={{ansible_memtotal_mb/3}}

This will calculate the memory and ensures 1/3 memory is empty.

pause module

The pause module acts as a synchronization point and halts the execution of a playbook for a certain period of time.This pause or wait can be configured.This pause module is very effective while using with playbook but not much of useful when run via command prompt.

Pause module  is useful when we want users to provide input like confirmation.It is also useful when manual intervention is required.It is like through automation we installed something and manually check if everything is working fine.Playbook will wait for an ‘enter’ key from user as a confirmation to proceed.

Example of pause module
- - -
  -hosts:web
    tasks:
     -name:wait for user input
      pause:
        prompt="Enter to continue and ctrl+c to quit"
      -name:timed wait
        pause:
            seconds:60
…

This module can wait for an indefinite time which may delay the execution.

The wait-for module

The wait-for module helps to poll a particular/predefined TCP port.It will halt until that port accepts a remote connection.The polling operation is done with the remote client machines.This module is mostly applicable to the processes or service that takes long time to start or for processes that we want to run in the backend.For such services we need to use wait-for module.

- - -
   -hosts:web
     tasks:
       -name:Install tomcat
          yum:
            name:tomcat 7.1
            state:"installed"
       -name:start tomcat
          service:
            name:tomcat 7.1
            state:"started"
      -name:wait to start tomcat
          wait_for:
            port:"9999"
            state:"started"
…

The Assemble module:

This module helps us to assemble several files that are combined on client machine.This is applicable when config file does not allow includes,globbing.This is also helpful for the authorized_key file.

- - -
   hosts:all
     tasks:
       -name:Build the authorized_key file
         assemble:
           src:"/opt/sshkeys"
           dest:"/root/.ssh/authorized_keys"
           owner:"root"
           group:"root"
           mode:"0700"
…

The add_host module:

This module allows us to dynamically add new client machines into a play.Add_host module adds our host to a group dynamically by creating a non existent group.The module takes hostname and groupname as an argument primarily.But it can accept other arguments like ansible_ssh_user,ansible_ssh_port etc.

The group_by module:

This module creates groups depending upon the facts available about the machine.The group_by module accepts one argument called key.(Key is the group name where the client machine will be added).

- - -
    -name:create operating system group
      hosts:all
      tasks:
       -group_by:
          Key:"os_{{ansible_distribution}}"

The debug module

Please refer the ansible playbook debug section to get the details.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 28
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    137
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here