Import includes, role structure, and system roles

Import includes, role structure, and system roles

1, Import and include

Although you can write a playbook in a very large file (you might start learning palybook this way), eventually you will want to reuse the file and start organizing. In Ansible, there are three ways to do this: includes, imports, and roles.

includes and imports (added in ansible version 2.4) allow users to split large playbooks into smaller files, which can be used in multiple parent playbooks or even multiple times in the same playbook.

Dynamic and static
For reusable content, Ansible has two modes of operation: dynamic and static.

In Ansible 2.0, the concept of dynamic inclusion is introduced. Due to some limitations of implementing all include in this way, Ansible 2.1 introduces the ability to set force include to static. Because the include task is overloaded and contains static and dynamic syntax, and because the default behavior of include may change according to other options set on the task, Ansible 2.4 introduces the concepts of include and import.

1. Static import

Using import_tasks module to import tasks files

Using import_role module to import roles

tasks:
  - import_tasks: tasks/foo.yml
  - import_role:
      name: example
import_tasks Variables are also allowed to be passed


- import_tasks: wordpress.yml wp_user=timmy

- import_tasks: wordpress.yml
  vars:
    wp_user: timmy
    ssh_keys:
      - keys/one.txt
      - keys/two.txt

example

[root@server ansible]# cat /etc/ansible/playbook/test/yum.yml 
---
- hosts: httpd
  tasks: 
    - name: install
      yum: 
        name: httpd
        state: present
      
[root@server ansible]# cat /etc/ansible/playbook/test/firewalld.yml 
---
- hosts: httpd
  tasks:   
    - name: stop firewalld
      service: 
        name: firewalld
        state: stopped


    - name: 
      shell: 
        setenforce 0
        
[root@server ansible]# cat /etc/ansible/playbook/test/main.yml 
- name: stop firewalld
  import_playbook: firewalld.yml   //Import firewalld

- name: install httpd
  import_playbook: yum.yml        //Import yum

implement
 
[root@server ansible]# ansible-playbook playbook/test/main.yml 

PLAY [httpd] *******************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.58.20]

TASK [stop firewalld] **********************************************************
changed: [192.168.58.20]

TASK [shell] *******************************************************************
changed: [192.168.58.20]

PLAY [httpd] *******************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.58.20]

TASK [install] *****************************************************************
ok: [192.168.58.20]

PLAY RECAP *********************************************************************
192.168.58.20              : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
// see
 [root@httpd ~]# getenforce 
Permissive

2. Dynamic inclusion

Use include_tasks module to contain tasks files

Use include_role module to contain roles

Dynamic inclusion can be used as a circular reference

- include_tasks: foo.yml param={{item}}
  with_items: # Circular reference 3 times
   - 1
   - 2
   - 3
- include_role:
    name: example
 You can also use variables to introduce task file


- include_tasks: "{{inventory_hostname}}.yml"

2.1 variables include

include_vars dynamically loads variables in yaml or json file types in task

yaml - include_vars: myvars.yml

Load the variable file according to the operating system type. If it is not found, it is the default value.

- include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution }}.yml"
    - "{{ ansible_os_family }}.yml"
    - "default.yml"

3. The difference between dynamic and static

  • Ansible preprocesses all static imports at Playbook parsing time. Importing the configuration file before execution will stop immediately if an error occurs

  • Dynamic inclusion is handled when the task is encountered during runtime. When importing the configuration file during execution, it will not stop immediately if an error occurs
    When an Ansible task option is involved, such as tags and conditional statement when:

  • For dynamic inclusion, the task option applies to a dynamic task only when it is evaluated, and is not copied to subtasks.

  • For static imports, the parent task option is copied to all subtasks included in the import.
    Using include* vs.import * has some advantages and disadvantages, which users should consider when choosing to use them

The main advantage of using the include * statement is the loop. When a loop is used with an include, the included task or role is executed once for each item in the loop.

Compared with static import, dynamic inclusion has some limitations

  • You cannot use notify to trigger handler names from dynamic inclusion.

  • You cannot use – start at task to start execution in a dynamically included task.

  • Tags that exist only within dynamic inclusions do not appear in the - list tags output.

  • Tasks that exist only in dynamic inclusion will not be displayed in the - list tasks output.
    Compared with dynamic inclusion, static import has some limitations

  • Static import cannot use a loop

  • Variables in the host manifest cannot be used when using variables with target file or role names

  • handlers imported using import will not be triggered when notified by its name, because import will overwrite the specified task of handler's with the imported task list.

2, ROLE

Role is to automatically load some vars based on a known file structure_ Files, tasks, and handlers. Content grouped by role also allows easy sharing of roles with other users.

1. Role directory structure

The file structure is as follows

The role must contain at least one such directory, but any unused directory can be excluded. When used, each directory must contain a main YML file, which contains relevant contents:

parameternotes
tasksContains a list of the main tasks to be performed by the role.
handlersContains handlers that can be used by this role or even anywhere outside this role.
defaultsDefault variables for roles
varsOther variables of the role
filesContains files that can be deployed through this role
templatesContains templates that can be deployed through this role.
metaSome metadata is defined for this role.
libraryIf there are any custom modules, put them here (optional)
filter_pluginsIf you have any custom filter plug-ins, put them here (optional)
group_var/allIf group_var/all exists, and the listed variables will be added to all host groups
group_var/groupname1If group_var/groupname1 exists, and the variables listed in it will be added to the groupname1 host group
host_vars/hostname1If host_vars/hostname1 exists, and the variables listed in it will be added to the hostname1 host group

In addition to specific files and directories, you can also include custom files and directories, such as setting a file for each operating system in the following

2. Role use

Use roles: in play to define which roles to use

The playbook specifies the following behavior for a role 'x'

  • If roles / X / tasks / main YML exists, and the tasks listed in it will be added to play

  • If roles / X / handlers / main YML exists, and the listed handlers will be added to play

  • If roles / X / vars / main YML exists, and the listed variables will be added to play

  • If roles / X / defaults / main YML exists, and the role default variables listed in it will be added to play

  • If roles / X / meta / main YML exists, and the listed "role dependencies" will be added to the roles list

  • All copy tasks can refer to the files in roles/x/files / without indicating the full path of the file.

  • All script tasks can refer to the scripts in roles/x/files / without indicating the full path of the file.

  • All template tasks can refer to the files in roles/x/templates / without indicating the full path of the file.

  • All include tasks can refer to the files in roles/x/tasks / without indicating the full path of the file. If there are files in the roles directory that do not exist, these files will be ignored.

When used in this way, the playbook is executed in the following order:

  • pre_ All tasks defined by tasks
  • handlers task triggered so far
  • Each role listed in roles will be executed in turn. Role meta / main Any role dependencies defined in YML will run first, but subject to tag filtering and criteria.
  • All tasks defined by tasks
  • handlers task triggered so far
  • post_ All tasks defined by tasks
  • handlers task triggered so far

example

vim tasks/main.yml
- debug:
    msg: "This is testing"

---
- hosts: httpd
  roles:
  - xu 

[root@server  ansible]# ansible-playbook testing.yml 

PLAY [httpd] *******************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.58.20]

TASK [xu : debug] *************************************************************
ok: [192.168.58.20] => {
    "msg": "This is testing"
}

PLAY RECAP *********************************************************************
192.168.58.20            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


3. Use of system roles

3.1 role of installing RHEL system

yum -y install rhel-system-roles

After installation, RHEL system roles are located in the * * / usr/share/ansible/roles * * Directory:

cd /usr/share/ansible/roles/
[root@server roles]# ls
linux-system-roles.certificate
linux-system-roles.crypto_policies
linux-system-roles.ha_cluster
linux-system-roles.kdump
linux-system-roles.kernel_settings
linux-system-roles.logging
linux-system-roles.metrics
linux-system-roles.nbde_client
linux-system-roles.nbde_server
linux-system-roles.network
linux-system-roles.postfix
linux-system-roles.selinux
linux-system-roles.ssh
linux-system-roles.sshd
linux-system-roles.storage
linux-system-roles.timesync
linux-system-roles.tlog
rhel-system-roles.certificate
rhel-system-roles.crypto_policies
rhel-system-roles.ha_cluster
rhel-system-roles.kdump
rhel-system-roles.kernel_settings
rhel-system-roles.logging
rhel-system-roles.metrics
rhel-system-roles.nbde_client
rhel-system-roles.nbde_server
rhel-system-roles.network
rhel-system-roles.postfix
rhel-system-roles.selinux
rhel-system-roles.ssh
rhel-system-roles.sshd
rhel-system-roles.storage
rhel-system-roles.timesync
rhel-system-roles.tlog

example

Time synchronization role synchronization

[root@server roles]# cp -a /usr/share/ansible/roles/rhel-system-roles.timesync timesync
[root@server roles]# ls
timesync  xu

---
- hosts: httpd
  vars:
    timesync_ntp_servers:
      - hostname: time2.aliyun.com
        iburst: yes
  roles:
    - timesync

selinux role

[root@server ansible]# vim testing.yml
---
- hosts: httpd
  vars:
    selinux_policy: targeted
    selinux_state: disabled
  roles:
    - selinux

Added by Viruthagiri on Mon, 03 Jan 2022 00:37:16 +0200