Skip to content

Ansible Filters

Overview

Filters in Ansible transform data and are an essential part of template processing. They allow you to manipulate variables, format output, and process complex data structures.

Common Filters

String Filters

# String manipulation
- name: String filter examples
  debug:
    msg:
      - "Uppercase: {{ mystring | upper }}"
      - "Lowercase: {{ mystring | lower }}"
      - "Title Case: {{ mystring | title }}"
      - "Replace: {{ mystring | replace('old', 'new') }}"
      - "Default: {{ undefined_var | default('default_value') }}"
      - "Regular Expression: {{ mystring | regex_replace('^foo', 'bar') }}"
      - "Trim: {{ mystring | trim }}"

# String concatenation
- name: Join strings
  vars:
    paths: 
      - /var
      - log
      - messages
  debug:
    msg: "Path: {{ paths | join('/') }}"

Data Type Filters

# Type conversion
- name: Type conversion examples
  debug:
    msg:
      - "To JSON: {{ myvar | to_json }}"
      - "From JSON: {{ json_string | from_json }}"
      - "To YAML: {{ myvar | to_yaml }}"
      - "From YAML: {{ yaml_string | from_yaml }}"
      - "To Boolean: {{ myvar | bool }}"
      - "To Integer: {{ myvar | int }}"
      - "To Float: {{ myvar | float }}"

List and Dictionary Filters

# List manipulation
- name: List filter examples
  vars:
    mylist: [1, 2, 3, 2, 1]
    mydict: {'a': 1, 'b': 2}
  debug:
    msg:
      - "Unique: {{ mylist | unique }}"
      - "Sort: {{ mylist | sort }}"
      - "Length: {{ mylist | length }}"
      - "Min: {{ mylist | min }}"
      - "Max: {{ mylist | max }}"
      - "First: {{ mylist | first }}"
      - "Last: {{ mylist | last }}"
      - "Flatten: {{ nested_list | flatten }}"
      - "Dictionary Keys: {{ mydict | dict2items }}"

Path and File Filters

# Path manipulation
- name: Path filter examples
  debug:
    msg:
      - "Basename: {{ path | basename }}"
      - "Dirname: {{ path | dirname }}"
      - "Expanduser: {{ path | expanduser }}"
      - "Realpath: {{ path | realpath }}"
      - "Splitext: {{ path | splitext }}"

Custom Filters

# filter_plugins/custom_filters.py
class FilterModule(object):
    def filters(self):
        return {
            'format_size': self.format_size,
            'to_uppercase': self.to_uppercase
        }

    def format_size(self, size_in_bytes):
        """Convert bytes to human readable format"""
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size_in_bytes < 1024:
                return f"{size_in_bytes:.2f}{unit}"
            size_in_bytes /= 1024
        return f"{size_in_bytes:.2f}TB"

    def to_uppercase(self, string):
        """Convert string to uppercase"""
        return string.upper()

Advanced Filter Usage

Combining Filters

# Multiple filters
- name: Complex filter combinations
  debug:
    msg:
      - "Combined: {{ myvar | upper | replace(' ', '_') }}"
      - "Nested: {{ mylist | map('upper') | list | join(', ') }}"
      - "Complex: {{ mydict | dict2items | selectattr('value', 'gt', 5) | list }}"

JSON Query (JMESPath)

# JSON querying
- name: JSON query examples
  vars:
    complex_data:
      servers:
        - name: web01
          status: running
        - name: web02
          status: stopped
  debug:
    msg:
      - "Query: {{ complex_data | json_query('servers[*].name') }}"
      - "Filter: {{ complex_data | json_query('servers[?status == `running`]') }}"

Date and Time Filters

# Date manipulation
- name: Date filter examples
  debug:
    msg:
      - "Format Date: {{ ansible_date_time.iso8601 | to_datetime('%Y-%m-%d') }}"
      - "Add Time: {{ (ansible_date_time.epoch | int) + (3600 * 24) | to_datetime }}"
      - "Human Time: {{ ansible_date_time.epoch | to_datetime | human_to_seconds }}"

Best Practices

Error Handling

# Safe filter usage
- name: Handle missing values
  debug:
    msg: "Value: {{ myvar | default('N/A') }}"

# Combine with conditions
- name: Conditional filter
  debug:
    msg: "Status: {{ status | default('unknown') | upper if status is defined else 'UNKNOWN' }}"

Performance Considerations

# Efficient filtering
- name: Optimize filter chains
  debug:
    msg: "{{ large_list | selectattr('status', 'eq', 'active') | map(attribute='name') | list }}"

Documentation

# Document complex filters
- name: Complex data transformation
  vars:
    filter_explanation: |
      This filter chain:
      1. Converts the input to items
      2. Selects items matching criteria
      3. Transforms the result
  debug:
    msg: |
      {{ filter_explanation }}
      Result: {{ complex_data | dict2items | selectattr('value.status', 'eq', 'active') | map(attribute='key') | list }}