Concrete Classes

General Metrics

LinesBlank

class ansiblemetrics.general.lines_blank.LinesBlank(script: str)

This class measures the blank lines in a playbook

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

count()

Return the number of blank lines

Example

from ansiblemetrics.general.lines_blank import LinesBlank

playbook = '''
---
- hosts: localhost

  tasks:
  - name: task 1
    debug:
      msg: 'Hello'

  - name: task 2
    debug:
      msg: 'World'
'''

LinesBlank(playbook).count()

>> 2
Returns

Number of blank lines

Return type

int

LinesCode

class ansiblemetrics.general.lines_code.LinesCode(script: str)

This class measures the number of executable lines of code in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

count()

Return the number of executable lines of code.

Example

from ansiblemetrics.general.lines_code import LinesCode

playbook = '''
---
- hosts: localhost

  tasks:
  - name: task 1
    debug:
      msg: 'Hello'

  - name: task 2
    debug:
      msg: 'World'
'''

LinesCode(playbook).count()

>> 8
Returns

Number of lines of code

Return type

int

LinesComments

class ansiblemetrics.general.lines_comment.LinesComment(script: str)

This class measures the number of comments in a playbook

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

count()

Return the number of commented lines

Example

from ansiblemetrics.general.lines_comments import LinesComments

playbook = '''
---
- hosts: localhost

  tasks:

  # A task to say Hello World!
  - name: task 1
    debug:
      msg: 'Hello World!'
'''

LinesComments(playbook).count()

>> 1
Returns

Number of commented lines

Return type

int

NumConditions

class ansiblemetrics.general.num_conditions.NumConditions(script: str)

This class measures the number of conditions in a playbook

A condition is a Boolean expression containing no Boolean operators. Conditions are identified by the following comparison operators: is, in, ==, !=, >, >=, <, <=.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of conditions.

Example

from ansiblemetrics.general.num_conditions import NumConditions

playbook = '''
- hosts: all
  vars:
  - hello_msg: "Hello World"

  tasks:
  - debug:
      msg: "Equals"
      when:
        - "Hello" in hello_msg    # 1st condition
        - "World" in hello_msg    # 2nd condition
'''

NumConditions(playbook).count()

>> 2
Returns

Number of conditions

Return type

int

NumDecisions

class ansiblemetrics.general.num_decisions.NumDecisions(script: str)

This class implements the metric ‘Number of decisions’ in an Ansible script.

A decision is a Boolean expression composed of conditions and one or more Boolean operators. Decisions are identified by the following logical operators: `and, or, not`.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of decisions.

Example

from ansiblemetrics.general.num_decisions import NumDecisions

playbook = '''
- hosts: all
  vars:
  - hello_msg: "Hello World"

  tasks:
  - debug:
      msg: "{{ hello_msg }}"
    when: "Hello" in hello_msg and "World" in hello_msg   # 1st decision

  - debug:
      msg: "Goodbye World"
    when:
        - "World" in hello_msg and not "Hello" in hello_msg    # 2nd (and) and 3rd (not) decision
'''

NumDecisions(playbook).count()

>> 3
Returns

Number of decisions

Return type

int

NumDeprecatedKeywords

class ansiblemetrics.general.num_deprecated_keywords.NumDeprecatedKeywords(script: str)

This class measures the number of deprecated keywords in a playbook

More info about Ansible deprecated keywords can be found at: https://docs.ansible.com/ansible/latest/reference_appendices/playbooks_keywords.html

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of Ansible deprecated keywords.

Example

from ansiblemetrics.general.num_deprecated_keywords import NumDeprecatedKeywords

playbook = '''
- hosts: localhost

  tasks:
  - name: Hello, Ansible!
    action: rust_helloworld
    args:   # Deprecated keyword
      name: Ansible
'''

NumDeprecatedKeywords(playbook).count()

>> 1
Returns

Number of deprecated keywords

Return type

int

NumKeys

class ansiblemetrics.general.num_keys.NumKeys(script: str)

A playbook is YAML-based, and is treated as a dictionary. This class measures the number of keys in the dictionary representing the playbook

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of keys of the dictionary representing the playbook.

Example

from ansiblemetrics.general.num_keys import NumKeys

playbook = '''
- hosts: all

  tasks:
  - debug:
      msg: "Hello World"
'''

NumKeys(playbook).count()

>> 4
Returns

Number of keys

Return type

int

NumMathOperations

class ansiblemetrics.general.num_math_operations.NumMathOperations(script: str)

This class measures the number of math operations in a playbook. The following operators are considered for the calculation: +, -, /, //, %, , *.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of mathematical operations.

Example

from ansiblemetrics.general.num_math_operations import NumMathOperations

playbook = '''
- hosts: localhost

  tasks:
  - debug:
      msg: "addition: {{ 4 + 3 }}"  # 1st operation
  - debug:
      msg: "subtraction: {{ 4 - 3 }}"   # 2nd operation
  - debug:
      msg: "multiplication: {{ 4 * 3 }}"    # 3rd operation
  - debug:
      msg: "Modulo operation: {{ 7 % 4}}"   # 4th operation
  - debug:
      msg: "floating division: {{ 4 / 3}}"  # 5th operation
'''

NumMathOperations(playbook).count()

>> 5
Returns

Number of math operations

Return type

int

NumSuspiciousComments

class ansiblemetrics.general.num_suspicious_comments.NumSuspiciousComments(script: str)

This class measures the number of suspicious comments in a playbook.

Suspicious comments contain at least one of the following keywords: TODO, FIXME, HACK, XXX, CHECKME, DOCME, TESTME, PENDING.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

count()

Return the number of suspicious comments.

Example

from ansiblemetrics.general.num_suspicious_comments import NumSuspiciousComments

playbook = '''
---
# TODO: Remove this task after Ansible 2.x npm module bug is fixed. See:
# https://github.com/ansible/ansible-modules-extras/issues/1375
- name: Ensure forever is installed (to run Node.js apps).
  npm: name=forever global=yes state=present
  become: yes
  become_user: "{{ nodejs_install_npm_user }}"
  when: nodejs_forever
'''

NumSuspiciousComments(playbook).count()

>> 1
Returns

Number of suspicious comments

Return type

int

NumTokens

class ansiblemetrics.general.num_tokens.NumTokens(script: str)

This class measures the number of tokens (separated by blank spaces) in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of tokens.

Example

from ansiblemetrics.general.num_tokens import NumTokens

playbook = '''
- hosts: all

  tasks:
  - debug:
      msg: "Hello World"
'''

NumTokens(playbook).count()

>> 7
Returns

Number of tokens

Return type

int

TextEntropy

class ansiblemetrics.general.text_entropy.TextEntropy(script: str)

This class measure the Shannon entropy of a playbook’s text. The entropy is computed considering the tokens as symbols, rather than the letters.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the playbook’s text entropy.

Example

from ansiblemetrics.general.text_entropy import TextEntropy

playbook = '''
---
- hosts: all
  roles:
  - common

- hosts: dbservers
  roles:
  - db
  - web
'''

TextEntropy(playbook).count()

>> 4.89
Returns

Text entropy

Return type

float

Playbook Metrics

AvgPlaySize

class ansiblemetrics.playbook.avg_play_size.AvgPlaySize(script: str)

This class measures a play’s average number of lines of code.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the average play size.

Example

from ansiblemetrics.general.avg_play_size import AvgPlaySize

playbook = '''
---
# 1st play
- hosts: all
  roles:
  - common

# 2nd play
- hosts: monitoring
  roles:
  - base-apache
  - nagios
'''

AvgPlaySize(playbook).count()

>> 4
Returns

Average play size, rounded to the nearest unit

Return type

int

AvgTaskSize

class ansiblemetrics.playbook.avg_task_size.AvgTaskSize(script: str)

This class measures a task’s average number of lines of code.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the average task size.

Example

from ansiblemetrics.general.avg_task_size import AvgTaskSize

playbook = '''
---
- name: 1st task
  include_vars:
    file: username_info.yml

- name: 2nd task
  uri:
    url: "http://{{ip_address}}/api/{{username}}"
    method: GET
    body: '{{body_info|to_json}}'
  register: light_info

- name: 3rd task
  debug:
    var: light_info.json.lights
'''

AvgTaskSize(playbook).count()

>> 4
Returns

Average task size, rounded to the nearest unit

Return type

int

NumAuthorizedKey

class ansiblemetrics.playbook.num_authorized_key.NumAuthorizedKey(script: str)

This class measures the number of times a SSH key is set and/or updated in a playbook.

The authorized_key property is used to add or remove SSH authorized keys for particular user accounts.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the occurrences of the authorized_key keyword.

Example

from ansiblemetrics.general.num_authorized_key import NumAuthorizedKey

playbook = '''
---
- name: Set authorized key taken from file
  authorized_key:
    user: charlie
    state: present
    key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
'''

NumAuthorizedKey(playbook).count()

>> 1
Returns

authorized_key occurrences

Return type

int

NumBlocks

class ansiblemetrics.playbook.num_blocks.NumBlocks(script: str)

This class measures the number of block sections in a playbook.

Blocks allow for logical grouping of tasks and in play error handling. Most of what you can apply to a single task (with the exception of loops) can be applied at the block level, which also makes it much easier to set data or directives common to the tasks. This does not mean the directive affects the block itself, but is inherited by the tasks enclosed by a block, i.e. a when will be applied to the tasks, not the block itself.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of block sections.

Example

from ansiblemetrics.general.num_blocks import NumBlocks

playbook = '''
---
- name: Install, configure, and start Apache
  block:
  - name: install httpd and memcached
    yum:
      name: "{{ item }}"
      state: present
    loop:
      - httpd
      - memcached
  - name: start service bar and enable it
    service:
      name: bar
      state: started
      enabled: True
  when: ansible_facts["distribution"] == "CentOS"
'''

NumBlocks(playbook).count()

>> 1
Returns

block occurrences

Return type

int

NumBlocksErrorHandling

class ansiblemetrics.playbook.num_blocks_error_handling.NumBlocksErrorHandling(script: str)

This class measures the number of times errors are handled within the blocks tasks.

Blocks introduce the ability to handle errors in a way similar to exceptions in most programming languages. The tasks in the block would execute normally, if there is any error the rescue section would get executed with whatever you need to do to recover from the previous error. The always section runs no matter what previous error did or did not occur in the block and rescue sections.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of blocks error handling.

Example

from ansiblemetrics.general.num_blocks_error_handling import NumBlocksErrorHandling

playbook = '''
- name: Attempt and graceful roll back demo
  block:    # This block handle errors with rescue and always
    - debug:
        msg: 'I execute normally'
    - name: i force a failure
      command: /bin/false
    - debug:
        msg: 'I never execute, due to the above task failing, :-('
  rescue:
    - debug:
        msg: 'I caught an error'
    - name: i force a failure in middle of recovery! >:-)
      command: /bin/false
    - debug:
        msg: 'I also never execute :-('
  always:
    - debug:
        msg: "This always executes"

- name: A task with a block that does not handle errors
  block:    # This block does not
    - debug:
        msg: 'I execute normally'
    - name: i force a failure
      command: /bin/false
    - debug:
        msg: 'I never execute, due to the above task failing, :-('
'''

NumBlocksErrorHandling(playbook).count()

>> 1
Returns

number of times blocks are used to handle errors

Return type

int

NumCommands

class ansiblemetrics.playbook.num_commands.NumCommands(script: str)

This class measures the occurrences of the following modules in a playbook:

  • command: execute commands on targets;

  • expect: executes a command and responds to prompts;

  • psexec: runs commands on a remote Windows host based on the PsExec model;

  • raw: executes a low-down and dirty command;

  • script: runs a local script on a remote node after transferring it;

  • shell: execute shell commands on targets;

  • telnet: executes a low-down and dirty telnet command.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of commands.

Example

from ansiblemetrics.general.num_commands import NumCommands

playbook = '''
---
- name: return motd to registered var
  command: cat /etc/motd
  register: mymotd

- name: List user accounts on a Windows system
  raw: Get-WmiObject -Class Win32_UserAccount
'''

NumCommands(playbook).count()

>> 2
Returns

number of commands

Return type

int

NumDeprecatedModules

class ansiblemetrics.playbook.num_deprecated_modules.NumDeprecatedModules(script: str)

This class measures the number of times tasks use deprecated modules.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the deprecated modules occurrence.

Example

from ansiblemetrics.general.num_deprecated_modules import NumDeprecatedModules

playbook = '''
- name: Include unique username from register.yml
  include_vars:   # non deprecated module
    file: username_info.yml

- name: Create a service
  oc:   # deprecated module
    state: present
    name: myservice
    namespace: mynamespace
    kind: Service
'''

NumDeprecatedModules(playbook).count()

>> 1
Returns

deprecated modules occurrence

Return type

int

NumDistinctModules

class ansiblemetrics.playbook.num_distinct_modules.NumDistinctModules(script: str)

This class measures the number of distinct modules in the script.

It differs from ansiblemetrics.playbook.NumTasks as it counts the number of distinct modules in the script without duplicates. If a module occurs twice or more among tasks it is counted only once. Recall that the goal of a task is to execute a module, so the total number of modules (with duplicates) equals the number of tasks.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of distinct modules.

Example

from ansiblemetrics.general.num_distinct_modules import NumDistinctModules

playbook = '''
- name: Include username_info
  include_vars:  # module
    file: username_info.yml

- name: Include settings_info
  include_vars:  # module
    file: settings_info.yml

- name: Grab HUE light info
  uri:  # module
    url: "http://{{ip_address}}/api/{{username}}"
    method: GET
    body: '{{body_info|to_json}}'
'''

NumDistinctModules(playbook).count()

>> 2
Returns

number of distinct modules

Return type

int

NumExternalModules

class ansiblemetrics.playbook.num_external_modules.NumExternalModules(script: str)

This class measures the number of modules in a playbook that do not belong to the core Ansible modules or are not maintained by the Ansible community.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of external modules.

Example

from ansiblemetrics.general.num_external_modules import NumExternalModules

playbook = '''
- name: ensure foo
  file:   # Core module
    path: /tmp/foo
    state: touch

- name: do a remote copy
  remote_copy:    # External module
    source: /tmp/foo
    dest: /tmp/bar
'''

NumExternalModules(playbook).count()

>> 1
Returns

number of external modules

Return type

int

NumFactModules

class ansiblemetrics.playbook.num_fact_modules.NumFactModules(script: str)

This class measures the number of fact modules in a playbook.

Fact modules are modules that do not alter state but rather return data. Knowing the number of fact modules in a playbook could represent a measure of the responsibility of the playbook. The assumption is that the lower the fact modules wrt the total number of modules in the script, the more unstable is the class behaviour, as the other modules alter its state.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of external modules.

Example

from ansiblemetrics.general.num_fact_modules import NumFactModules

playbook = '''
- name: Find all instances in the specified region
  ali_instance_facts:   # Fact module
    alicloud_access_key: "{{ alicloud_access_key }}"
    alicloud_secret_key: "{{ alicloud_secret_key }}"
    alicloud_region: '{{ alicloud_region }}'
  register: all_instances

- name: Print data to terminal window
  debug:    # not fact module
    msg: 'End of tasks'
'''

NumFactModules(playbook).count()

>> 1
Returns

number of external modules

Return type

int

NumFileExists

class ansiblemetrics.playbook.num_file_exists.NumFileExists(script: str)

This class measures the number of time a playbook checks the existence of a file.

In particular, the module stat retrieves facts for a file similar to the Linux/Unix stat command, and can be used to check for the existence of a file or directory.

This property is measured by counting the matches of the following regular expression:

.(win_)?stat. is (not)? defined

to check if the file or directory exist.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of file existence checks.

Example

from ansiblemetrics.general.num_fact_modules import NumFileExists

playbook = '''
- stat:
    path: /path/to/something
  register: sym

- debug:
    msg: "islnk isn't defined (path doesn't exist)"
  when: sym.stat.islnk is not defined  # file existence check
'''

NumFileExists(playbook).count()

>> 1
Returns

number of file existence checks

Return type

int

NumFileMode

class ansiblemetrics.playbook.num_file_mode.NumFileMode(script: str)

This class measures the number of times playbook manages a file’s permissions.

File ‘mode’ is a source code property used to manage files, directories and symbolic links.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of file’s mode syntax occurrences.

Example

from ansiblemetrics.general.num_fact_modules import NumFileMode

playbook = '''
- name: Change file ownership, group and permissions
  file:
    path: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'    # 1st occurrence
'''

NumFileMode(playbook).count()

>> 1
Returns

number of file’s mode syntax occurrences

Return type

int

NumFileModules

class ansiblemetrics.playbook.num_file_modules.NumFileModules(script: str)

This class measures the occurrences of the file module in a playbook.

The file module is used to manage files and their properties.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the file module occurrences.

Example

from ansiblemetrics.general.num_file_modules import NumFileModules

playbook = '''
- name: Change file ownership, group and permissions
  file:    # 1st occurrence
    path: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'
'''

NumFileModules(playbook).count()

>> 1
Returns

number of file module occurrences

Return type

int

NumFilters

class ansiblemetrics.playbook.num_filters.NumFilters(script: str)

This class measures the number of filters in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of filters.

Example

from ansiblemetrics.general.num_filters import NumFilters

playbook = '''
- shell: cat /some/path/to/multidoc-file.yaml
  register: result
- debug:
    msg: '{{ item }}'
  loop: '{{ result.stdout | from_yaml_all | list }}'  # 2 filters
'''

NumFilters(playbook).count()

>> 2
Returns

number of filters

Return type

int

NumIgnoreErrors

class ansiblemetrics.playbook.num_ignore_errors.NumIgnoreErrors(script: str)

This class measures the number of times a playbook ignore errors through the property ignore_errors.

Ignoring errors is considered as a bad practice, since ignore errors only obscures error handling. There are better ways for handling errors. See https://blog.newrelic.com/engineering/ansible-best-practices-guide/ for more details.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of ignore_errors: yes/True.

Example

from ansiblemetrics.general.num_ignore_errors import NumIgnoreErrors

playbook = '''
- name: this will not be counted as a failure
  command: /bin/false
  ignore_errors: yes
'''

NumIgnoreErrors(playbook).count()

>> 1
Returns

number of ignore_errors set to True or yes

Return type

int

NumImportedPlaybooks

class ansiblemetrics.playbook.num_imported_playbooks.NumImportedPlaybooks(script: str)

This class measures the number of imported playbooks in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of imported playbooks.

Example

from ansiblemetrics.general.num_imported_playbooks import NumImportedPlaybooks

playbook = '''
- name: Include a play after another play
  import_playbook: otherplays.yml

- name: This fails because I'm inside a play already
  import_playbook: stuff.yaml
'''

NumImportedPlaybooks(playbook).count()

>> 2
Returns

number of imported playbooks

Return type

int

NumImportedRoles

class ansiblemetrics.playbook.num_imported_roles.NumImportedRoles(script: str)

This class measures the number of imported roles in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of imported roles.

Example

from ansiblemetrics.general.num_import_roles import NumImportedRoles

playbook = '''
- import_role:
    name: myrole

- name: Run tasks/other.yaml instead of "main"
  import_role:
    name: myrole
    tasks_from: other
'''

NumImportedRoles(playbook).count()

>> 2
Returns

number of imported roles

Return type

int

NumImportTasks

class ansiblemetrics.playbook.num_imported_tasks.NumImportedTasks(script: str)

This class measures the number of imported tasks list in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of imported tasks.

Example

from ansiblemetrics.general.num_imported_tasks import NumImportedTasks

playbook = '''
- name: Include task list in play
  import_tasks: stuff.yaml
'''

NumImportedTasks(playbook).count()

>> 1
Returns

number of imported tasks

Return type

int

NumIncludes

class ansiblemetrics.playbook.num_includes.NumIncludes(script: str)

This class measures the number of includes in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of includes.

Example

from ansiblemetrics.general.num_includes import NumIncludes

playbook = '''
- name: Include a play after another play
  include: otherplays.yaml

- name: Include task list in play
  include_role: role.yaml
'''

NumIncludes(playbook).count()

>> 1
Returns

number of includes

Return type

int

NumIncludedRole

class ansiblemetrics.playbook.num_included_roles.NumIncludedRoles(script: str)

This class measures the number of included roles in a playbook

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of included roles

Example

from ansiblemetrics.general.num_included_roles import NumIncludedRoles

playbook = '''
- name: Include task list in play
  include_role: role.yaml
'''

NumIncludedRoles(playbook).count()

>> 1
Returns

number of included roles

Return type

int

NumIncludedTasks

class ansiblemetrics.playbook.num_included_tasks.NumIncludedTasks(script: str)

This class measures the number of included tasks in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of included tasks.

Example

from ansiblemetrics.general.num_included_tasks import NumIncludedTasks

playbook = '''
- name: Include task list in play
  include_tasks: stuff.yaml
'''

NumIncludedTasks(playbook).count()

>> 1
Returns

number of included tasks

Return type

int

NumIncludedVars

class ansiblemetrics.playbook.num_included_vars.NumIncludedVars(script: str)

This class measures the number of included variables in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of included variables.

Example

from ansiblemetrics.general.num_included_vars import NumIncludedVars

playbook = '''
- name: Include a play after another play
  include_vars: myvars.yaml
'''

NumIncludedVars(playbook).count()

>> 1
Returns

number of included variables

Return type

int

NumLookups

class ansiblemetrics.playbook.num_lookups.NumLookups(script: str)

This class measures the number of lookups in a playbook.

Lookups are evaluated when the task referencing them is executed, which allows for dynamic data discovery. To reuse a particular lookup in multiple tasks and re-evaluate it each time, a playbook variable can be defined with a lookup value. Each time the playbook variable is referenced the lookup will be executed, potentially providing different values over time.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of lookups.

Example

from ansiblemetrics.general.num_lookups import NumLookups

playbook = '''
- hosts: all
  vars:
    contents: "{{ lookup('file', '/etc/foo.txt') }}"
'''

NumLookups(playbook).count()

>> 1
Returns

number of lookups

Return type

int

NumLoops

class ansiblemetrics.playbook.num_loops.NumLoops(script: str)

This class measures the number of loops in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of loops.

Example

from ansiblemetrics.general.num_loops import NumLoops

playbook = '''
---
- name: with_list
  debug:
    msg: "{{ item }}"
  with_list:    # 1st loop
    - one
    - two

- name: with_list -> loop
  debug:
    msg: "{{ item }}"
  loop:    # 2nd loop
    - one
    - two
'''

NumLoops(playbook).count()

>> 2
Returns

number of loops

Return type

int

NumNameWithVars

class ansiblemetrics.playbook.num_name_with_vars.NumNameWithVars(script: str)

This class measures the number of names that use variables.

With uniqueness as a goal, many playbook authors look to variables to satisfy this constraint. This strategy may work well but authors need to take care as to the source of the variable data they are referencing. Variable data can come from a variety of locations, and the values assigned to variables can be defined at a variety of times. For the sake of play and task names, it is important to remember that only variables for which the values can be determined at playbook parse time will parse and render correctly. If the data of a referenced variable is discovered via a task or other operation, the variable string will be displayed unparsed in the output.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of plays and tasks with names referencing variables.

Example

from ansiblemetrics.general.num_name_with_vars import NumNameWithVars

playbook = '''
- name: play with a {{ var_name }}    # uses variable
  hosts: localhost
  vars:
    var_name: not-mastery

  tasks:
  - name: set a variable    # does not use variable
    set_fact:
    task_var_name: "defined variable"

'''

NumNameWithVars(playbook).count()

>> 1
Returns

number of plays and tasks with names referencing variables

Return type

int

NumParameters

class ansiblemetrics.playbook.num_parameters.NumParameters(script: str)

This class measures the number of parameters in a playbook.

Modules in Ansible have paramaters that describe the desired state of the module; each parameter handles some aspect of the module. For example, the module file has a mode parameter that specifies the permissions for the file.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of modules parameters.

Example

from ansiblemetrics.general.num_parameters import NumParameters

playbook = '''
- name: Create two hard links
  file:
    src: '/tmp/foo'
    dest: '/tmp/bar'
    state: hard
'''

NumParameters(playbook).count()

>> 3
Returns

number of modules parameters

Return type

int

NumPaths

class ansiblemetrics.playbook.num_paths.NumPaths(script: str)

This class measures the number of paths in a playbook.

Paths are identified by analyzing the parameters path, src, dest

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of paths.

Example

from ansiblemetrics.general.num_paths import NumPaths

playbook = '''
---
- name: "Downloading {{program_var.stdout}} from Google Drive"
  synchronize:
    src: "/mnt/gdrive/plexguide/backup/{{program_var.stdout}.tar"
    dest: "/tmp"
'''

NumPaths(playbook).count()

>> 1
Returns

number of paths

Return type

int

NumPlays

class ansiblemetrics.playbook.num_plays.NumPlays(script: str)

This class measures the number of plays in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of plays.

Example

from ansiblemetrics.general.num_plays import NumPlays

playbook = '''
---
- hosts: all
  roles:
  - common

- hosts: dbservers
  roles:
  - db
'''

NumPlays(playbook).count()

>> 2
Returns

number of plays

Return type

int

NumPrompts

class ansiblemetrics.playbook.num_prompts.NumPrompts(script: str)

This class measures the number of interactions with users by means of the module prompt.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of

Example

from ansiblemetrics.general.num_prompts import NumPrompts

playbook = '''
- hosts: all
  remote_user: root

  vars_prompt:
    - name: "name"
      prompt: "what is your name?"
    - name: "quest"
      prompt: "what is your quest?"
    - name: "favcolor"
      prompt: "what is your favorite color?"
'''

NumPrompts(playbook).count()

>> 3
Returns

number of

Return type

int

NumRegex

class ansiblemetrics.playbook.num_regex.NumRegex(script: str)

This class measures the number of regular expressions in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of regular expressions.

Example

from ansiblemetrics.general.num_regex import NumRegex

playbook = '''
---
- name: Remove Password
  lineinfile:
    path: "/opt/appdata/nzbget/nzbget.conf"
    regexp: ControlPassword=tegbzn6789
    line: 'ControlPassword='
    state: present
  when: nzbget_conf.stat.exists == False
'''

NumRegex(playbook).count()

>> 1
Returns

number of regular expressions

Return type

int

NumRoles

class ansiblemetrics.playbook.num_roles.NumRoles(script: str)

This class measures the number of roles in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of roles.

Example

from ansiblemetrics.general.num_roles import NumRoles

playbook = '''
---
- hosts: all
  roles:
  - common  # 1st role

- hosts: dbservers
  roles:
  - db  # 2nd role

'''

NumRoles(playbook).count()

>> 2
Returns

number of roles

Return type

int

NumTasks

class ansiblemetrics.playbook.num_tasks.NumTasks(script: str)

This class measures the number of tasks in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of tasks.

Example

from ansiblemetrics.general.num_tasks import NumTasks

playbook = '''
- name: Say Hello
  debug:
    msg: "Hello"

- name: Say World!
  debug:
    msg: "World!"
'''

NumTasks(playbook).count()

>> 2
Returns

number of tasks

Return type

int

NumUniqueNames

class ansiblemetrics.playbook.num_unique_names.NumUniqueNames(script: str)

This class measures the number of plays and tasks with unique a name.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of plays and tasks with a unique name.

Example

from ansiblemetrics.general.num_unique_names import NumUniqueNames

playbook = '''
---
- name: demo the logic                    # unique name
  hosts: localhost
  gather_facts: false
  vars:
    num1: 10
    num3: 10

  tasks:
  - name: logic and comparison            # duplicate
    debug:
      msg: "Can you read me?"
    when: num1 >= num3 and num1 is even and num2 is not defined

  - name: logic and comparison            # duplicate
    debug:
      msg: "Can you read me again?"
    when: num3 >= num1
'''

NumUniqueNames(playbook).count()

>> 1
Returns

number of plays and tasks with a unique name

Return type

int

NumUri

class ansiblemetrics.playbook.num_uri.NumUri(script: str)

This class measures the number of URIs in a playbook.

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of URIs

Example

from ansiblemetrics.general.num_uri import NumUri

playbook = '''
- name: Check that you can connect (GET) to a page and it returns a status 200
  uri:
    url: http://www.example.com
'''

NumUri(playbook).count()

>> 1
Returns

number of URIs

Return type

int

NumVars

class ansiblemetrics.playbook.num_vars.NumVars(script: str)

This class measures the number of variables in a playbook.

TODO add support for included and imported variables

__init__(script: str)

The class constructor.

Parameters

script (str) – A plain Ansible file

Raises

TypeError – If the script is empty or an invalid YAML file

count()

Return the number of variables.

Example

from ansiblemetrics.general.num_vars import NumVars

playbook = '''
- hosts: all
  remote_user: root
  vars:
    favcolor: blue                      # 1st variable
  vars_files:                           # vars_files is not supported by this version
  - /vars/external_vars.yml
'''

NumVars(playbook).count()

>> 1
Returns

number of variables.

Return type

int