Roles in Ansible
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have discussed modules in Ansible.
https://cloudaffaire.com/modules-in-ansible/
In this blog post, we will discuss modules in Ansible.
Roles in Ansible:
Roles are ways of automatically loading certain vars_files, tasks, and handlers based on a known file structure. Grouping content by roles also allows easy sharing of roles with other users. Roles expect files to be in certain directory names.
Roles must include at least one of these directories, however it is perfectly fine to exclude any which are not being used. When in use, each directory must contain a main.yml file, which contains the relevant content.
Roles directory structure:
- tasks: contains the main list of tasks to be executed by the role.
- handlers: contains handlers, which may be used by this role or even anywhere outside the role.
- defaults: default variables for the role and configurations for deployment.
- vars: other variables for the role.
- files: contains files which can be deployed via the role.
- templates – contains templates which can be deployed via the role.
- meta: defines some meta data for the role.
Role order of execution:
- Any pre_tasks defined in the play.
- Any handlers triggered so far will be run.
- Each role listed in roles will execute in turn. Any role dependencies defined in the roles meta/main.yml will be run first, subject to tag filtering and conditionals.
- Any tasks defined in the play.
- Any handlers triggered so far will be run.
- Any post_tasks defined in the play.
- Any handlers triggered so far will be run.
Note: We have already covered the order of execution in https://cloudaffaire.com/ansible-playbook-components/
Role Search Path: Ansible will search for roles in the following way
- A roles/ directory, relative to the playbook file.
- By default, in /etc/ansible/roles
Ansible Galaxy:
Ansible Galaxy is a free site for finding, downloading, rating, and reviewing all kinds of community developed Ansible roles and can be a great way to get a jumpstart on your automation projects. The client ansible-galaxy is included in Ansible. The Galaxy client allows you to download roles from Ansible Galaxy, and also provides an excellent default framework for creating your own roles.
Next, we will create a role to deploy apache webserver in Centos 7.
Role Demo:
Create your role directory structure using ansible-galaxy command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
##--------------------- ## Ansible : Roles ## ##--------------------- ## Systems used for this demo ## hostnames ip os role ## --------- ------------ -------- ------------ ## system1 192.168.0.10 Centos 7 Control Node ## Create your role directory and files mkdir roles && cd roles ansible-galaxy init apache ## Role directory structure ## apache ## ├── defaults ## │ └── main.yml ## ├── files ## ├── handlers ## │ └── main.yml ## ├── meta ## │ └── main.yml ## ├── README.md ## ├── tasks ## │ └── main.yml ## ├── templates ## ├── tests ## │ ├── inventory ## │ └── test.yml ## └── vars ## └── main.yml |
Note: You can also create the files manually without using ansible-galaxy.
Define your httpd configuration settings using role default variables. This will be imported in your httpd.conf file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
## defaults - default variables for the role. vi apache/defaults/main.yml --------------------- --- httpd_document_root: '/var/www/html' httpd_access_log: logs/access_log httpd_error_log: logs/error_log httpd_listen: 80 httpd_log_level: warn httpd_server_admin: root@localhost httpd_server_root: '/etc/httpd' httpd_server_tokens: Prod httpd_index_file: '/var/www/html/index.html' --------------------- :wq |
Create configuration file for your httpd server using role template, this imports the default variable in the httpd.conf file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
## templates - contains templates which can be deployed via this role. vi apache/templates/httpd.conf.j2 --------------------- ## General configuration ServerRoot {{ httpd_server_root }} Listen {{ httpd_listen }} Include conf.modules.d/*.conf User apache Group apache ## 'Main' server configuration ServerAdmin {{ httpd_server_admin }} {% if httpd_server_name is defined %} ServerName {{ httpd_server_name }} {% endif %} ServerTokens {{ httpd_server_tokens }} # Deny access to the entirety of your server's filesystem. AllowOverride none Require all denied DocumentRoot {{ httpd_document_root }} # Relax access to content within /var/www. AllowOverride None Require all granted # Further relax access to the default document root: Options Indexes FollowSymLinks AllowOverride None Require all granted # Load index.html if directory is requested DirectoryIndex index.html # Prevent .htaccess and .htpasswd files from being viewed by Web clients. Require all denied # Logging ErrorLog "{{ httpd_error_log }}" LogLevel {{ httpd_log_level }} LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio CustomLog "{{ httpd_access_log }}" combined # CGI ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" AllowOverride None Options None Require all granted TypesConfig /etc/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddType text/html .shtml AddOutputFilter INCLUDES .shtml AddDefaultCharset UTF-8 MIMEMagicFile conf/magic EnableSendfile on # Supplemental configuration IncludeOptional conf.d/*.conf # vim: ft=apache --------------------- :wq |
Declare variables for your role. We are defining the package that will be installed through this role and the httpd.conf file location.
1 2 3 4 5 6 7 8 |
## vars - other variables for the role. vi apache/vars/main.yml --------------------- --- httpd_packages: httpd httpd_config: /etc/httpd/conf/httpd.conf --------------------- :wq |
Define the main task for your role. This will install and configure httpd in your server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
## tasks - contains the main list of tasks to be executed by the role. vi apache/tasks/main.yml --------------------- --- - name: Include vars include_vars: dir: vars - name: Install httpd package: name: "{{ item }}" state: present with_items: "{{ httpd_packages }}" - name: Configure httpd template: src: httpd.conf.j2 dest: "{{ httpd_config }}" owner: root group: root setype: httpd_config_t mode: '0644' notify: restart httpd - name: Run httpd service: name: httpd state: started enabled: true - name: copy index.html file copy: src: index.html dest: "{{ httpd_index_file }}" --------------------- :wq |
Define handlers for your role. This will restart your httpd service post configuration.
1 2 3 4 5 6 7 8 9 10 |
## handlers - contains handlers, which may be used by this role or even anywhere outside this role. vi apache/handlers/main.yml --------------------- --- - name: restart httpd service: name: httpd state: restarted --------------------- :wq |
Define meta for your role. This is optional if you are planning to upload your role in ansible galaxy you can define this.
1 2 3 4 5 6 7 8 9 10 |
## meta - defines some meta data for this role. See below for more details. vi apache/meta/main.yml --------------------- --- galaxy_info: role_name: apache author: Debjeet company: CloudAffaire --------------------- :wq |
Create files for your role usage. We are creating index.html file for our webserver.
1 2 3 4 5 6 |
## files - contains files which can be deployed via this role. vi apache/files/index.html --------------------- Hello world --------------------- :wq |
Create playbook for your role execution.
1 2 3 4 5 6 7 8 9 10 11 |
## Create the playbook cd .. vi myplaybook.yml --------------------- --- - hosts: localhost become: true roles: - apache --------------------- :wq |
Execute the playbook
1 2 3 4 5 |
## Check playbook syntax ansible-playbook myplaybook.yml --syntax-check ## Execute the playbook ansible-playbook myplaybook.yml |
Check if your web server is working.
1 2 |
## Check your webserver is working curl 192.168.0.10 |
Hope you have enjoyed this article.
To get more details on Ansible, please refer below Ansible documentation.