Ansible Roles

Ansible Roles

Roles give a structure to completely free or associated assortments of documents, errands, templates, variables, and modules.

The role is the essential component for breaking a playbook into distinct files or records. This rearranges composing complex playbooks and makes them simpler to reuse. By breaking the playbook into divisions, it permits you to break the whole playbook into reusable segments.  Segments can be used more efficiently rather than the whole thing.

Every role is restricted to a particular usage or expected result, with all the vital strides to give that outcome either inside a similar job itself or in different roles recorded as conditions.

These are not playbooks. In general, these are little features that can be utilized inside the playbooks without any restrictions. Roles have no particular setting or configuration for which hosts the role will enforce.

High-level playbooks are the extension holding the hosts from your stock record to roles that must be imposed on the hosts.

Making a Role

The directory structure for the role is important for making another role, for example, 

Structure of role

The roles have an organized format on the record framework. Additionally, you can change the default framework of the roles. Ansible role contains seven main standard directories. You have to add at least one of these directories in every role. You can drop out that directories which have no use for the role.

For instance, let us follow the default structure of roles. Every job is a catalog tree in itself. So, the role name is the directory name inside the/roles catalog.

$ ansible-galaxy - h

Utilization

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

Choices

  • -h: (help) it indicates the help message and exit.
  • -v: (verbose) Verbose mode (- vvv for additional, - vvvv to empower association troubleshooting).
  • --version: it shows the program version, which represents the age of the program and exit.

Roles are put away in independent catalogs and have a specific index structure.

 [root@ansible-server test2]# tree
 .
 '- - role1
 |- - defaults
 | '- - main.yml
 |- - handlers
 | '- - main.yml
 |- - meta
 | '- - main.yml
 |- - README.md
 |- - tasks
 | '- - main.yml
 |- - tests
 |- - inventory
 | '- - test.yml
 '- - vars
 '- - main.yml 

Clarification

  • The YAML record in the default catalog contains a rundown of default factors to be utilized alongside the playbook. These factors or variables are at the end of the priority order list, whereas others are considered before using them.
  • The handler's catalog is utilized to store controllers.
  • The meta-directory should have data about the creator and job conditions.
  • The tasks catalog is the principal YAML record for the role.
  • The tests registry/directory contains an example YAML playbook document and an example stock record and is generally utilized for testing purposes before making the real role. 
  • The vars registry contains the YAML document in which all the factors utilized by the job will be characterized. The directory layouts and the directory records should comprise of documents and formats or templates that will be utilized by the assignments in the role.

Similarly, there are other directories like file/main.yml and template/main.yml, which contain files and templates, respectively, that the role deploys.

Managing storage of roles

        By default, Ansible search for roles in two areas:

  • In the directory called roles/,  which is related to the playbook file
  • And in /etc/ansible/roles

If you manage your roles in different areas, then set roles_path configuration so that Ansible can find quite comfortably. Putting these shared roles in the similar area makes it easier to use them for multiple playbooks.

Or you can see a role with the following path:

 ---
                -hosts: webservers 
                  roles:
                        -role: ‘/path/to/my/roles/common’ 

Utilizing Roles

You can utilize functions in three different ways:

  • At the assumed level with the roles option: This is the exemplary method of utilizing parts in a play.
  • At the task level with include_role: You can reuse jobs powerfully at anyplace in the assignments segment of a play utilizing include_role.
  • At the task level with import_role: You can reuse jobs statically in the assignments segment of a play utilizing import_role.

Utilizing roles at the play level

       For a particular play we can use the original way of using roles through roles option:

          ---
             -hosts: webservers
               roles:
                      -common
                      -webservers 

At the point when you utilize the roles alternative at the play level, for every role 'x':

  • In the event that roles/x/tasks/main.yml exists, Ansible includes the assignments in that record to the play.
  • In the event that roles/x/handlers/main.yml exists, Ansible includes the controllers in that document to the play.
  • In the event that roles/x/vars/main.yml exists, Ansible includes the variables in that record to the play.
  • In the event that roles/x/defaults/main.yml exists, Ansible includes the variables in that record to the play.
  • In the event that jobs/x/meta/main.yml exists, Ansible includes any role conditions in that record to the rundown of jobs.
  • Any duplicate, content, layout, or incorporate assignments (in the job) can reference documents in roles/x/{files, templates, tasks}/(dir relies upon task) without having to way them generally or totally.

At the point when you utilize the roles choice at the play level, Ansible treats the functions as static imports and cycles them during playbook parsing. Ansible executes your playbook in a specific order:

  • Any pre_tasks are characterized in the play. 
  • Any controllers or handlers set off by pre_tasks.
  • Every role is recorded in roles: which means roles are recorded in a sequence. Any role conditions characterized in the role's meta/main.yml run first, subject to tag sifting and conditionals.
  • Any tasks characterized in the play.
  • Any handlers set off by the roles or tasks.
  • Any post_tasks characterized in the play.
  • Any handlers set off by post_tasks.

You can add different keywords into the roles alternative:

 ---
 - hosts: webservers
 role:
          - common
          - role: foo_app_example
          vars:
               dir: '/choose/1'
               app_port: 5000
           labels: typeA1
         - role: foo_app_example
           vars:
                dir: '/choose/2'
                 app_port: 5001
            labels: typeA2 

At the point when you add a tag to the role choice, Ansible applies the tag to ALL assignments inside the role.

When utilizing vars: inside the roles: division of the playbook, the variables are merged to the play variables, making them accessible to all errands inside the play before and after the utilization of the role.

Including roles: Dynamic Reuse

You can reuse roles instantly anyplace in the tasks segment of a play utilizing include_role. While roles included a role, segment executes before some other tasks inside the playbook, included roles executes in a fixed order as they are characterized. Assume there are different errands before an include_role task than other tasks will run first.

To incorporate a role:

 ---
       - hosts: webservers
         tasks:
              - name: Print the message
                ansible.builtin.debug:
                    msg: "this task executes before the instance role"
              - name: Include the instance role
                 include_role:
                      name: instance
 - name: Print the message
                   ansible.builtin.debug:
                         msg: "this task follows the instance role" 

Bringing in roles: Static Reuse

You can reuse roles statically at anyplace in the tasks division of a play by utilizing import_role. The conduct is equivalent to utilizing the roles keyword. For instance:

 ---
 - hosts: webservers
    tasks:
          - name: Print the message
            ansible.builtin.debug:
               msg: "before we run the role"
           - name: Import the instance role
              import_role:
                    name: instance
             - name: Print the message
               ansible.builtin.debug:
                   msg: "after we execute our role" 

Running a role on numerous occasions in a single playbook.

Ansible executes every role once, regardless of whether you characterize it on numerous occasions, except if the boundaries characterized on the role are distinctive for every definition. For instance, Ansible executes the role foo only once in a play like the following method:

 ---
 - hosts: webservers
      roles:
            - foo
            - bar
            - foo 

You have two choices to compel Ansible to run a role more than once.

Passing various arguments

You can pass various arguments in every role definition as:

 ---
 - hosts: webservers
        roles:
               - { role: foo, vars: { message: "first" }
               - { role: foo, vars: { message: "second" } 

Utilizing role conditions

Role conditions let you naturally pull in different roles when utilizing a role. Ansible doesn't execute role conditions when you incorporate or import a role. You should utilize the roles keyword on the off chance that you need Ansible to execute role conditions.

Role conditions are put away in the meta/main.yml record inside the job index. This record ought to contain a rundown of roles and parameters to embed before the predefined role. For instance:

 # roles/myapp/meta/main.yml
 ---
 conditions:
      - role: common
        vars:
                some_para: 3
       - role: apache
         vars:
                apache_port: 80
         - role: postgres
            vars:
                   dbname: blarg
                   other_para: 12 

Ansible continuously runs role conditions before the role that comprises them. Ansible runs repetitive role conditions too. In the event that one role relies upon a subsequent role, and the subsequent role relies upon a third role, Ansible executes the third role, at that point the subsequent role, at that point the principal role.

Running role conditions on different occasions in a single playbook.

Ansible treats copy role conditions like copy jobs recorded under roles:: Ansible executes role conditions once, regardless of whether characterized on numerous occasions, except if the boundaries, labels, or when provision characterized on the role are diverse for every definition. On the off chance that two parts in a playbook both rundown the third function as a reliance, Ansible just runs that role reliance once, except if you pass various parameters, labels, when a condition, or use allow_duplicates: true in the needy (third) role. 

For instance, a role named vehicle relies upon a role named engine as follows:

 ---
 conditions:
 - role: engine
 vars:
 n: 1
 - role: engine
 vars:
 n: 2
 - role: engine
 vars:
 n: 3
 - role: engine
 vars:
 n: 4 

Furthermore, the engine role relies on two roles: on and off. The meta/main.yml for wheel would then contain the accompanying:

 ---
 conditions:
           -  role: on
          -  role: off 

Furthermore, the meta/main.yml for on and off would contain the accompanying:

 ---
      allow_duplicates: role 

The subsequent request of execution would be as per the following:

 on(n=1)
 off(n=1)
 engine(n=1)
 on(n=2)
 off(n=2)
 engine(n=2)
 ...
 vehicle 

To utilize allow_duplicates: true with role conditions, you should indicate it for the reliant role, not for the parent role. In the model above, allow_duplicates: true shows up in the meta/main.yml of the tire and brake roles. The wheel role doesn't need allow_duplicates: true, in light of the fact that each occasion characterized via vehicle utilizes diverse parameter esteems.

Installing modules and plugins in roles

On the off chance that you compose a custom module or a module, you may wish to disperse it as a feature of a job. For instance, in the event that you compose a module that designs your organization's inner programming, and you need others in your association to utilize this module, yet you would prefer not to advise everybody how to arrange their Ansible library way, you can remember the module for your internal_config job.

To add on a module or a module to a division: And side by side the 'tasks' and 'handlers' structure of a role, put a directory named 'library' and after that merge the module legitimately inside the 'library' index.

Expecting you owns this:

 roles/
                   my_custom_modules/
                                      library/
                                               module1
                                               module2 

The module will be usable in the role itself, just as any roles that are called after this part, as follows:

 ---
 - hosts: webservers
 roles:
       - my_custom_modules
       - some_other_role_using_my_custom_modules
       - yet_another_role_using_my_custom_modules 

We will know how to share roles in an ansible-galaxy. There we will be discovering, downloading, rating, and investigating a wide range of networks created by Ansible jobs, which will work as a head start for your automation projects.