final docs for filters (#78800)

Co-authored-by: Felix Fontein <felix@fontein.de>
pull/78825/head
Brian Coca 2 years ago committed by GitHub
parent 24a42bb25e
commit 3b937123d2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -350,7 +350,7 @@ Combining and selecting data
You can combine data from multiple sources and types, and select values from large data structures, giving you precise control over complex data.
.. _zip_filter:
.. _zip_filter_example:
Combining items from multiple lists: zip and zip_longest
--------------------------------------------------------
@ -1008,7 +1008,7 @@ As of Ansible version 2.9, you can also initialize the random number generator f
"{{ '52:54:00' | community.general.random_mac(seed=inventory_hostname) }}"
.. _random_filter:
.. _random_filter_example:
Random items or numbers
-----------------------

@ -1288,7 +1288,10 @@ class DocCLI(CLI, RoleMixin):
if isinstance(doc['plainexamples'], string_types):
text.append(doc.pop('plainexamples').strip())
else:
text.append(yaml_dump(doc.pop('plainexamples'), indent=2, default_flow_style=False))
try:
text.append(yaml_dump(doc.pop('plainexamples'), indent=2, default_flow_style=False))
except Exception as e:
raise AnsibleParserError("Unable to parse examples section", orig_exc=e)
text.append('')
text.append('')

@ -0,0 +1,28 @@
DOCUMENTATION:
name: bool
version_added: "historical"
short_description: cast into a boolean
description:
- Attempt to cast the input into a boolean (C(True) or C(False)) value
positional: _input
options:
_input:
description: Data to cast.
type: raw
required: true
EXAMPLES: |
# simply encrypt my key in a vault
vars:
isbool: "{{ (a == b)|bool }} "
otherbool: "{{ anothervar|bool }} "
# in a task
...
when: some_string_value | bool
RETURN:
_value:
description: The boolean resulting of casting the input expression into a C(True) or C(False) value
type: bool

@ -0,0 +1,21 @@
DOCUMENTATION:
name: checksum
version_added: "1.9"
short_description: checksum of input data
description:
- Returns a checksum (L(SHA-1, https://en.wikipedia.org/wiki/SHA-1)) hash of the input data.
positional: _input
options:
_input:
description: Data to checksum.
type: raw
required: true
EXAMPLES: |
# csum => "109f4b3c50d7b0df729d299bc6f8e9ef9066971f"
csum : {{ 'test2' | checksum }}
RETURN:
_value:
description: The checksum (SHA-1) of the input.
type: string

@ -0,0 +1,26 @@
DOCUMENTATION:
name: combinations
version_added: "historical"
short_description: combinations from the elements of a list
description:
- Create a list of combinations of sets from the elements of a list.
positional: _input, set_size
options:
_input:
description: Elements to combine.
type: list
required: true
set_size:
description: The size of the set for each combination.
type: int
required: true
EXAMPLES: |
# combos_of_two => [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 1, 5 ], [ 2, 3 ], [ 2, 4 ], [ 2, 5 ], [ 3, 4 ], [ 3, 5 ], [ 4, 5 ] ]
combos_of_two: "{{ [1,2,3,4,5] | combinations(2) }}"
RETURN:
_value:
description: List of combination sets resulting from the supplied elements and set size.
type: list

@ -0,0 +1,45 @@
DOCUMENTATION:
name: combine
version_added: "2.0"
short_description: combine two dictionaries
description:
- Create a dictionary (hash/associative array) as a result of merging existing dictionaries.
positional: _input, _dicts
options:
_input:
description: First dictionary to combine.
type: dict
required: true
_dicts: # TODO: this is really an *args so not list, but list ref
description: The list of dictionaries to combine.
type: list
elements: dictionary
required: true
recursive:
description: If C(True), merge elements recursively.
type: bool
default: false
list_merge:
describe: Behaviour when encountering list elements.
type: str
default: replace
choices:
replace: overwrite older entries with newer ones
keep: discard newer entries
append: append newer entries to the older ones
prepend: insert newer entries in front of the older ones
append_rp: append newer entries to the older ones, overwrite duplicates
prepend_rp: insert newer entries in front of the older ones, discard duplicates
EXAMPLES: |
# ab => {'a':1, 'b':3, 'c': 4}
ab: {{ {'a':1, 'b':2} | combine({'b':3, 'c':4}) }}
# ab => {'a':1, 'b':3, 'c': 4}
many: "{{ dict1 | combine(dict2, dict3, dict4) }}"
RETURN:
_value:
description: Resulting merge of supplied dictionaries.
type: dict

@ -0,0 +1,60 @@
DOCUMENTATION:
name: comment
version_added: 'historical'
short_description: comment out a string
description:
- Use a programmign language convention to turn the string into an embeddable comment.
positional: _input, style
options:
_input:
description: String to comment.
type: string
required: true
style:
description: Comment style to use.
type: string
default: plain
choices: ['plain', 'decoration', 'erlang', 'c', 'cblock', 'xml']
decoration:
description: Indicator for comment or intermediate comment depending on the style.
type: string
begining:
description: Indicator of the start of a comment block, only available for styles that support multiline comments.
type: string
end:
description: Indicator the end of a comment block, only available for styles that support multiline comments.
type: string
newline:
description: Indicator of comment end of line, only available for styles that support multiline comments
type: string
default: '\n'
prefix:
description: Token to start each line inside a comment block, only available for styles that support multiline comments
type: string
prefix_count:
description: Number of times to add a prefix at the start of a line, when a prefix exists and is usable
type: int
default: 1
postfix:
description: Indicator of the end of each line inside a comment block, only available for styles that support multiline comments
type: string
protfix_count:
description: Number of times to add a postfix at the end of a line, when a prefix exists and is usable
type: int
default: 1
EXAMPLES: |
# commented => #
# # Plain style (default)
# #
commented: "{{ 'Plain style (default)' | comment }}"
# not going to show that here ...
verycustom: "{{ "Custom style" | comment('plain', prefix='#######\n#', postfix='#\n#######\n ###\n #') }}"
RETURN:
_value:
description: The 'commented out' string.
type: string

@ -2,7 +2,8 @@ DOCUMENTATION:
name: dict2items
author: Ansible core team
version_added: "2.6"
short_description: takes a dictionary and transforms it into a list of dictionaries
short_description: Convert a dictionary into an itemized list of dictionaries
positional: _input, key_name, value_name
description:
- Takes a dictionary and transforms it into a list of dictionaries, with each having a
C(key) and C(value) keys that correspond to the keys and values of the original.
@ -13,32 +14,29 @@ DOCUMENTATION:
type: dict
required: true
key_name:
description: Configure the key to use instead of C(key).
description: The name of the property on the item representing the dictionary's keys.
type: str
default: key
version_added: "2.8"
value_name:
description: Configure the key to use instead of C(value).
description: The name of the property on the item representing the dictionary's values.
type: str
default: value
version_added: "2.8"
seealso:
- plugin_type: filter
plugin: ansible.builtin.items2dict
EXAMPLES: |
- name: Convert a dictionary into a list of dictionaries
debug:
msg: "{{ files | dict2items(key_name='file', value_name='path') }}"
vars:
files:
users: /etc/passwd
groups: /etc/group
# The output is a list of dictionaries:
# - file: users
# path: /etc/passwd
# - file: groups
# path: /etc/group
# items => [ { "key": "a", "value": 1 }, { "key": "b", "value": 2 } ]
items: "{{ {'a': 1, 'b': 2}| dict2items}}"
vars:
files:
users: /etc/passwd
groups: /etc/group
files_dicts: "{{ files | dict2items(key_name='file', value_name='path') }}"
RETURN:
_value:

@ -0,0 +1,39 @@
DOCUMENTATION:
name: extract
version_added: "2.1"
short_description: extract a value based on an index or key
description:
- Extract a value from a list or dictionary based on an index/key.
- User must ensure that index or key used matches the type of container.
- Equivalent of using C(list[index]) and C(dictionary[key]) but useful as a filter to combine with C(map).
positional: _input, container, morekeys
options:
_input:
description: Index or key to extract.
type: raw
required: true
contianer:
description: dictionary or list from which to extract a value
type: raw
required: true
morekeys:
description: Indicies or keys to extract from the initial result (subkeys/subindices).
type: list
elements: dictionary
required: true
EXAMPLES: |
# extracted => 'b', same as ['a', 'b', 'c'][1]
extracted: "{{ 1 | extract(['a', 'b', 'c']) }}"
# extracted_key => '2', same as {'a': 1, 'b': 2, 'c': 3}['b']
extracted_key: "{{ 'b' | extract({'a': 1, 'b': 2, 'c': 3}) }}"
# extracted_key_r => '2', same as [{'a': 1, 'b': 2, 'c': 3}, {'x': 9, 'y': 10}][0]['b']
extracted_key_r: "{{ 0 | extract([{'a': 1, 'b': 2, 'c': 3}, {'x': 9, 'y': 10}], morekeys='b') }}"
RETURN:
_value:
description: Resulting merge of supplied dictionaries.
type: dict

@ -0,0 +1,21 @@
DOCUMENTATION:
name: fileglob
short_description: explode a path glob to matching files
description:
- return a list of files that matches the supplied path glob pattern
- filters run on the controller, so the files are matched from the controller's file system
positional: _input
options:
_input:
description: Path glob pattern.
type: string
required: true
EXAMPLES: |
# found = ['/etc/hosts', '/etc/hasts']
found: "{{ '/etc/h?sts' | fileglob }}"
RETURN:
_value:
description: List of files matched.
type: list

@ -0,0 +1,32 @@
DOCUMENTATION:
name: flatten
version_added: "2.5"
short_description: flatten lists within a list
description:
- For a given list, take any elements that are lists and insert their elements into the parent list directly.
positional: _input, levels, skip_nulls
options:
_input:
description: First dictionary to combine.
type: dict
required: true
levels:
description: Number of recursive list depths to flatten.
type: int
skip_nulls:
description: Skip C(null)/C(None) elements when inserting into the top list.
type: bool
default: true
EXAMPLES: |
# [1,2,3,4,5,6]
flat: "{{ [1 , 2, [3, [4, 5]], 6] | flatten }}"
# [1,2,3,[4,5],6]
flatone: "{{ [1, 2, [3, [4, 5]], 6] | flatten(1) }}"
RETURN:
_value:
description: The flattened list.
type: list

@ -0,0 +1,25 @@
DOCUMENTATION:
name: from_json
version_added: 'historical'
short_description: Convert JSON string into variable structure
description:
- Converts a JSON string representation into an equivalent structured Ansible variable.
- Ansible internally auto-converts JSON strings into variable structures in most contexts, this plugin is used for those contexts it doesn't.
notes:
- This filter functions as a wrapper to the Python C(json.loads) function.
options:
_input:
description: A JSON string.
type: string
required: true
EXAMPLES: |
# variable from string variable containing a JSON document
{{ docker_config | from_json }}
# variable from string JSON document
{{ '{"a": true, "b": 54, "c": [1,2,3]}' | from_json }}
RETURN:
_value:
description: The variable resulting from deserialization of the JSON document.
type: raw

@ -0,0 +1,25 @@
DOCUMENTATION:
name: from_yaml
version_added: 'historical'
short_description: Convert YAML string into variable structure
description:
- Converts a YAML string representation into an equivalent structured Ansible variable.
- Ansible internally auto-converts YAML strings into variable structures in most contexts, this plugin is used for those contexts it doesn't.
notes:
- This filter functions as a wrapper to the Python pyyaml library's ``yaml.safe_load()`` function.
options:
_input:
description: A YAML string.
type: string
required: true
EXAMPLES: |
# variable from string variable containing a YAML document
{{ github_workflow | from_yaml}}
# variable from string JSON document
{{ '{"a": true, "b": 54, "c": [1,2,3]}' | from_yaml }}
RETURN:
_value:
description: the variable resuliting from deserializing the YAML document.
type: raw

@ -0,0 +1,28 @@
DOCUMENTATION:
name: from_yaml_all
version_added: 'historical'
short_description: Convert a series of YAML documents into a variable structure
description:
- Converts a YAML documents in a string representation into an equivalent structured Ansible variable.
- Ansible internally auto-converts YAML strings into variable structures in most contexts, but by default does not handle 'multi document' YAML files or strings.
- If multiple YAML documents are not supplied, this is the equivalend of using C(from_yaml).
notes:
- This filter functions as a wrapper to the Python ``yaml.safe_load_all()`` function, part of the pyyaml python library
- Possible conflicts in variable names from the mulitple documents are resolved directly by the pyyaml library.
options:
_input:
description: A YAML string.
type: string
required: true
EXAMPLES: |
# variable from string variable containing YAML documents
{{ multidoc_yaml_string | from_yaml_all }}
# variable from multidocument YAML string
{{ '---\n{"a": true, "b": 54, "c": [1,2,3]}\n...\n---{"x": 1}\n...\n' | from_yaml_all}}
RETURN:
_value:
description: the variable resuliting from deserializing the YAML documents.
type: raw

@ -0,0 +1,28 @@
DOCUMENTATION:
name: checksum
version_added: "1.9"
short_description: hash of input data
description:
- Returns a configurable hash (sha1) hash of the input data
positional: _input
options:
_input:
description: data to checksum
type: raw
required: true
hashtype:
description:
- type of algorighim to produce the hash
- the list of available choices depends on the installed Python's hashlib
type: string
default: sha1
EXAMPLES: |
# sha1_hash => "109f4b3c50d7b0df729d299bc6f8e9ef9066971f"
sha1_hash: {{ 'test2' | hash('sha1') }}
# md5 => "5a105e8b9d40e1329780d62ea2265d8a"
md5: {{ 'test2' | hash('md5') }}
RETURN:
_value:
description: The checksum (sha1) of the input
type: string

@ -0,0 +1,34 @@
DOCUMENTATION:
name: human_redable
version_added: "historical"
short_description: Make bytes/bits human readable
description:
- Convert byte or bit figures to more human readable formats
positional: _input, isbits, unit
options:
_input:
description: bytes
type: int
required: true
isbits:
description: input is bits, instead of bytes
type: bool
unit:
description: unit to force output into, if none specified the largest unit arrived at will be used
type: str
choices: [ 'Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'K', 'B']
EXAMPLES: |
# size => "1.15 GB"
size: "{{ 1232345345|human_readable }}"
# size => "1.15 Gb"
size_bits: "{{ 1232345345|human_readable(true) }}"
# size => "1175.26 MB"
size_MB: "{{ 1232345345|human_readable(unit='M') }}"
RETURN:
_value:
description: human readable byte or bit size
type: str

@ -0,0 +1,34 @@
DOCUMENTATION:
name: human_to_bytes
version_added: "historical"
short_description: Get bytes from string
description:
- Convert a human readable byte or bit string into a number bytes
positional: _input, default_unit, isbits
options:
_input:
description: bytes
type: int
required: true
default_unit:
description: unit to assume when input does not specify it
type: str
choices: ['Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'K', 'B']
isbits:
description: if C(True) force to interpet only bit input, if C(False) force bytes, otherwise just use the notation to guess
type: bool
EXAMPLES: |
# size => 1234803098
size: '{{ "1.15 GB" | human_to_bytes }}'
# size => 1234803098
size: '{{ "1.15" | human_to_bytes(deafult_unit="G") }}'
# this is an error, wants bits, got bytes
ERROR: '{{ "1.15 GB" | human_to_bytes(isbits=true) }}'
RETURN:
_value:
description: integer representing the bytes from the input
type: int

@ -2,7 +2,8 @@ DOCUMENTATION:
name: items2dict
author: Ansible core team
version_added: "2.7"
short_description: convert a list of one-element dictionaries into a dictionary
short_description: Consolidate a list of itemized dictionaries into a dictionary
positional: _input, key_name, value_name
description:
- Takes a list of dicts with each having a C(key) and C(value) keys, and transforms the list into a dictionary,
effectively as the reverse of R(dict2items,ansible_collections.ansible.builtin.dict2items_filter).
@ -15,33 +16,33 @@ DOCUMENTATION:
elements: dict
required: true
key_name:
description: Configure the key to use instead of C(key).
description: The name of the key in the element dictionaries that holds the key to use at destination
type: str
default: key
value_name:
description: Configure the key to use instead of C(value).
description: The name of the key in the element dictionaries that holds the value to use at destination
type: str
default: value
seealso:
- plugin_type: filter
plugin: ansible.builtin.dict2items
EXAMPLES: |
- name: Convert list of key-value pairs to dictionary
debug:
msg: "{{ tags | items2dict }}"
vars:
tags:
- key: Application
value: payment
- key: Environment
value: dev
# mydict => { "hi": "bye", "ciao": "ciao" }
mydict: {{ [{'key': 'hi', 'value': 'bye'}, {'key': 'ciao', 'value': 'ciao'} ]| items2dict}}
# The output is a dictionary with two key/value pairs:
#
# Application: payment
# Environment: dev
vars:
tags:
- key: Application
value: payment
- key: Environment
value: dev
consolidated: "{{ tags | items2dict }}"
RETURN:
_value:
description: The resulting dictionary.
description: dictionary with the consolidated key/values
type: dict

@ -0,0 +1,32 @@
DOCUMENTATION:
name: log
version_added: "1.9"
short_description: log of (math operation)
description:
- math operation that returns the N logarithim of inputed number logN(X)
notes:
- This is a passthrough to Python's C(math.log)
positional: _input, base
options:
_input:
description: number to operate on
type: int
required: true
base:
description: which base to use
type: int
default: 10
EXAMPLES: |
# 1.2920296742201791
eightlogfive: "{{ 8 | log(5) }}"
# 0.9030899869919435
eightlog10: "{{ 8 | log() }}"
RETURN:
_value:
description: resulting number
type: int

@ -0,0 +1,21 @@
DOCUMENTATION:
name: mandatory
version_added: "historical"
short_description: make a varaible's existance mandatory
description:
- Depending on context undefined variables can be ignored or skipped, this ensures they force an error.
positional: _input
options:
_input:
description: mandatory expression
type: raw
required: true
EXAMPLES: |
# results in a Filter Error
{{ notdefined | mandatory}}
RETURN:
_value:
description: the input if defined, otherwise an error
type: raw

@ -0,0 +1,24 @@
DOCUMENTATION:
name: md5
version_added: "historical"
short_description: md5 hash of input data
description:
- Returns a md5 hash of the input data
positional: _input
notes:
- This requires the md5 algorithim to be available on the system, security contexts like FIPS might prevent this.
- MD5 has long been deemed insecure and is not recommended for security related uses.
options:
_input:
description: data to hash
type: raw
required: true
EXAMPLES: |
# md5hash => "ae2b1fca515949e5d54fb22b8ed95575"
md5hash: "{{ 'testing' | md5 }}"
RETURN:
_value:
description: The md5 hash of the input
type: string

@ -0,0 +1,37 @@
DOCUMENTATION:
name: password_hash
version_added: "historical"
short_description: convert input password into password_hash
description:
- Returns a password_hash of a secret
positional: _input
notes:
- Algorithims available might be restricted by the system
options:
_input:
description: secret to hash
type: string
required: true
hashtype:
description: hashing algorithm to use
type: string
default: sha512
choices: [ md5, blowfish, sha256, sha512 ]
salt:
description: secret string that is used for the hashing, if none is provided a random one can be generated
type: int
rounds:
description: number of encryption rounds, default varies by algorithim used
type: int
ident:
description: no clue
type: string?
EXAMPLES: |
# pwdhash => "$6$/bQCntzQ7VrgVcFa$VaMkmevkY1dqrx8neaenUDlVU.6L/.ojRbrnI4ID.yBHU6XON1cB422scCiXfUL5wRucMdLgJU0Fn38uoeBni/"
pwdhash: "{{ 'testing' | password_hash}}"
RETURN:
_value:
description: The resulting password hash
type: string

@ -2,20 +2,29 @@ DOCUMENTATION:
name: path_join
author: Anthony Bourguignon (@Toniob)
version_added: "2.10"
short_description: join one or more path components
short_description: Join one or more path components
positional: _input
description:
- Returns a path obtained by joining one or more path components.
options:
_input:
description: A path, or a list of paths.
type: any
type: list
elements: str
required: true
EXAMPLES: |
# If path == 'foo/bar' and file == 'baz.txt', the result is '/etc/foo/bar/subdir/baz.txt'
{{ ('/etc', path, 'subdir', file) | path_join }}
# equivalent to '/etc/subdir/{{filename}}'
wheremyfile: "{{ ['/etc', 'subdir', filename] | path_join }}"
# trustme => '/etc/apt/trusted.d/mykey.gpgp'
trustme: "{{ ['/etc', 'apt', 'trusted.d', 'mykey.gpg'] | path_join }}"
RETURN:
_value:
description: The concatenated path.
type: path
type: str

@ -0,0 +1,26 @@
DOCUMENTATION:
name: permutations
version_added: "historical"
short_description: permutations from the elements of a list
description:
- Create a list of the permutations of lists from the elements of a list
- Unlke combinations, in permutations order is significant
positional: _input, list_size
options:
_input:
description: elements to base the permutations on
type: list
required: true
list_size:
description: the size of the list for each permutation
type: int
required: true
EXAMPLES: |
# ptrs_of_two => [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 1, 5 ], [ 2, 1 ], [ 2, 3 ], [ 2, 4 ], [ 2, 5 ], [ 3, 1 ], [ 3, 2 ], [ 3, 4 ], [ 3, 5 ], [ 4, 1 ], [ 4, 2 ], [ 4, 3 ], [ 4, 5 ], [ 5, 1 ], [ 5, 2 ], [ 5, 3 ], [ 5, 4 ] ]
prts_of_two: "{{ [1,2,3,4,5] | permutations(2) }}"
RETURN:
_value:
description: list of permutations lists resulting from the supplied elements and list size
type: list

@ -0,0 +1,34 @@
DOCUMENTATION:
name: pow
version_added: "1.9"
short_description: power of (math operation)
description:
- math operation that returns the N power of inputed number X ^ N
notes:
- This is a passthrough to Python's C(itertools.product)
positional: _input, _power
options:
_input:
description: number to power up!
type: int
required: true
_power:
description: which power to use
type: int
required: true
EXAMPLES: |
# => 32768
eight_power_five: "{{ 8 | pow(5) }}"
# 4
square_of_2: "{{ 2 | pow(2) }}"
# me ^ 3
cube_me: "{{ me | pow(3) }}"
RETURN:
_value:
description: resulting number
type: int

@ -0,0 +1,41 @@
DOCUMENTATION:
name: product
version_added: "historical"
short_description: cartesian product of lists
description:
- Combines two lists into one with each element being the product of the elements of the input lists
- this is an effective way to create 'nested loops', looping over C(listA) and C(listB) is the same as looping over C(listA|product(listB))
notes:
- This is a passthrough to Python's C(itertools.product)
positional: _input, _additional_lists, repeat
options:
_input:
description: first list
type: list
required: true
_additional_lists: #TODO: *args, N possible additional lists
description: addional list for the product
type: list
required: false
repeat:
description: number of times to repeat the product against itself
default: 1
type: int
EXAMPLES: |
# product => [ [ 1, "a" ], [ 1, "b" ], [ 1, "c" ], [ 2, "a" ], [ 2, "b" ], [ 2, "c" ], [ 3, "a" ], [ 3, "b" ], [ 3, "c" ], [ 4, "a" ], [ 4, "b" ], [ 4, "c" ], [ 5, "a" ], [ 5, "b" ], [ 5, "c" ] ]
product: "{{ [1,2,3,4,5] | product(['a', 'b', 'c']) }}"
# repeat_original => [ [ 1, 1 ], [ 1, 2 ], [ 2, 1 ], [ 2, 2 ] ]
repeat_original: "{{ [1,2] | product(repeat=2) }}"
# repeat_product => [ [ 1, "a", 1, "a" ], [ 1, "a", 1, "b" ], [ 1, "a", 2, "a" ], [ 1, "a", 2, "b" ], [ 1, "b", 1, "a" ], [ 1, "b", 1, "b" ], [ 1, "b", 2, "a" ], [ 1, "b", 2, "b" ], [ 2, "a", 1, "a" ], [ 2, "a", 1, "b" ], [ 2, "a", 2, "a" ], [ 2, "a", 2, "b" ], [ 2, "b", 1, "a" ], [ 2, "b", 1, "b" ], [ 2, "b", 2, "a" ], [ 2, "b", 2, "b" ] ]
repeat_product: "{{ [1,2] | product(['a', 'b']) }}"
# domains => [ 'example.com', 'ansible.com', 'redhat.com' ]
domains: "{{ [ 'example', 'ansible', 'redhat'] | product(['com']) | map('join', '.') }}"
RETURN:
_value:
description: list of lists of combined elements from the input lists
type: list

@ -0,0 +1,23 @@
DOCUMENTATION:
name: quote
version_added: "2.10"
short_description: shell quoting
description:
- Quote a string to safely use as in a POSIX shell
notes:
- This is a passthrough to Python's C(shelex.quote)
positional: _input
options:
_input:
description: string to quote
type: str
required: true
EXAMPLES:
- name: Run a shell command
shell: echo {{ string_value | quote }}
RETURN:
_value:
description: quoted string
type: str

@ -0,0 +1,37 @@
DOCUMENTATION:
name: random
version_added: "2.6"
short_description: random number or list item
description:
- Use the intput to either select a random element of a list or generate a random number
notes:
- This is a passthrough to Python's C(shelex.quote)
positional: _input, start, step, seed
options:
_input:
description: A number or list/sequence, if it is a number it is the top bound for random number generation, if it is a sequence or list, the source of the random element selected
type: raw
required: true
start:
description: bottom bound for the random number/element generated
type: int
step:
description: subsets the defined range by only using this value to select the increments of it between start and end
type: int
default: 1
seed:
description: if specified use a pseudo random selection instead (repeatable)
type: str
EXAMPLES: |
# can be any item from the list
random_item: "{{ ['a','b','c'] | random }}"
# cron line, select random minute repeatable for each host
"{{ 60 | random(seed=inventory_hostname) }} * * * * root /script/from/cron"
RETURN:
_value:
description: random number or list element
type: raw

@ -2,19 +2,18 @@ DOCUMENTATION:
name: realpath
author: darkone23 (@darkone23)
version_added: "1.8"
short_description: get canonical path for the given file
short_description: Turn path into real path
description:
- Returns the canonical path for the given file. This is done by eliminating symbolic
links encountered in the path.
- Resolves/follows symliknks to return the 'real path' from a given path.
- Filters alwasy run on controller so this path is resolved using the controller's filesystem.
options:
_input:
description: A path to a file.
description: A path.
type: path
required: true
EXAMPLES: |
# To get the real path of a link
{{ mypath | realpath }}
realpath: {{ '/path/to/synlink' | realpath }}
RETURN:
_value:

@ -0,0 +1,29 @@
DOCUMENTATION:
name: regex_escape
version_added: "2.8"
short_description: escape regex chars
description:
- Escape special characters in a string for use in a regular expression
positional: _input, re_type
notes:
- posix_extended is not implemented yet
options:
_input:
description: String to escape
type: str
required: true
re_type:
description: Which type of escaping to use
type: str
default: python
choices: [python, posix_basic]
EXAMPLES: |
# safe_for_regex => '\^f\.\*o\(\.\*\)\$'
safe_for_regex: "{{ '^f.*o(.*)$' | regex_escape() }}"
RETURN:
_value:
description: escaped string
type: str

@ -0,0 +1,37 @@
DOCUMENTATION:
name: regex_findall
version_added: "2.0"
short_description: extract all regex matches from string
description:
- Search in a string or extract all the parts of a string matching a regular expression
positional: _input, _regex
options:
_input:
description: String to match against
type: str
required: true
_regex:
description: regular expression string that defines the match
type: str
multiline:
description: search across line endings if C(True), don't if otherwise
type: bool
default: no
ignorecase:
description: force the serach to be case insensitive if C(True), case senstitive otherwise
type: bool
default: no
EXAMPLES: |
# all_pirates => ['CAR', 'tar', 'bar']
all_pirates: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_findall('^.ar$', multiline=True, ignorecase=True) }}"
# get_ips => ['8.8.8.8', '8.8.4.4']
get_ips: "{{ 'Some DNS servers are 8.8.8.8 and 8.8.4.4' | regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b') }}"
RETURN:
_value:
description: list of matched strings
type: list
elements: str

@ -0,0 +1,46 @@
DOCUMENTATION:
name: regex_replace
version_added: "2.0"
short_description: replace a string via regex
description:
- Replace a substring defined by a regular expression with another defined by another regular expressoin based on the first match
notes:
- Maps to Python's C(regex.replace)
positional: _input, _regex_match, _regex_replace
options:
_input:
description: String to match against
type: str
required: true
_regex_match:
description: regular expression string that defines the match
type: int
required: true
_regex_replace:
description: regular expression string that defines the replacement
type: int
required: true
multiline:
description: search across line endings if C(True), don't if otherwise
type: bool
default: no
ignorecase:
description: force the serach to be case insensitive if C(True), case senstitive otherwise
type: bool
default: no
EXAMPLES: |
# whatami => 'able'
whatami: "{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}"
# commalocal => 'localhost, 80'
commalocal: "{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}"
# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('^(.ar)$', '#\\1', multiline=True, ignorecase=True) }}"
RETURN:
_value:
description: string with substitution (or original if no match)
type: str

@ -0,0 +1,38 @@
DOCUMENTATION:
name: regex_search
version_added: "2.0"
short_description: extract regex match from string
description:
- Search in a string to extract the part that matches the regular expression
notes:
- Maps to Python's C(regex.search)
positional: _input, _regex
options:
_input:
description: String to match against
type: str
required: true
_regex:
description: regular expression string that defines the match
type: str
multiline:
description: search across line endings if C(True), don't if otherwise
type: bool
default: no
ignorecase:
description: force the serach to be case insensitive if C(True), case senstitive otherwise
type: bool
default: no
EXAMPLES: |
# db => 'database42'
db: "{{ 'server1/database42' | regex_search('database[0-9]+') }}"
# drinkat => 'BAR'
drinkat: "{{ 'foo\nBAR' | regex_search('^bar', multiline=True, ignorecase=True) }}"
RETURN:
_value:
description: matched string or empty string if no match
type: str

@ -0,0 +1,32 @@
DOCUMENTATION:
name: rekey_on_member
version_added: "2.13"
short_description: Rekey a list of dicts into a dict using a member
positional: _input, '_key', duplicates
description: Iterate over several iterables in parallel, producing tuples with an item from each one
notes:
- This is mostly a passhtrough to Python's C(zip) function
options:
_input:
description: Original dictionary
type: dict
required: yes
_key:
description: The key to rekey
type: str
required: yes
duplicates:
description: how to handle duplilcates
type: str
default: error
choices: [overwrite, error]
EXAMPLES: |
# mydict => {'eigrp': {'state': 'enabled', 'proto': 'eigrp'}, 'ospf': {'state': 'enabled', 'proto': 'ospf'}}
mydict: '{{ [{"proto": "eigrp", "state": "enabled"}, {"proto": "ospf", "state": "enabled"}] | rekey_on_member("proto") }}'
RETURN:
_value:
description: the resulting dictionary
type: dict

@ -2,28 +2,27 @@ DOCUMENTATION:
name: relpath
author: Jakub Jirutka (@jirutka)
version_added: "1.7"
short_description: get relative path of the given file
short_description: Make a path relative
positional: _input, start
description:
- Returns the relative path of the given file to the current directory if I(start) is not specified,
- Converts the given path to a relative path from the C(start).
or relative to the directory given in I(start).
positional: start
options:
_input:
description: A path.
type: path
type: str
required: true
start:
description: The directory the path should be relative to.
type: path
EXAMPLES: |
description: The directory the path should be relative to. if not supplied the current working directory will be used
type: str
# Get the relative path to 'mypath' from 'mydir'
{{ mypath | relpath(mydir) }}
EXAMPLES: |
# Returns '../foo/bar.txt'
{{ '/tmp/foo/bar.txt' | relpath('/tmp/baz/') }}
# foobar => ../test/me.txt
testing: "{{ '/tmp/test/me.txt' | relpath('/tmp/other/') }}"
otherrelpath: "{{ mypath | relpath(mydir) }}"
RETURN:
_value:
description: The relative path.
type: path
type: str

@ -0,0 +1,32 @@
DOCUMENTATION:
name: root
version_added: "1.9"
short_description: root of (math operation)
description:
- math operation that returns the N root of inputed number X ^^ N
positional: _input, base
options:
_input:
description: number to operate on
type: int
required: true
base:
description: which base to use
type: int
default: 2
EXAMPLES: |
# => 8
fiveroot: "{{ 32768 | root (5) }}"
# 2
sqrt_of_2: "{{ 4 | root }}"
# me ^^ 3
cuberoot_me: "{{ me | root(3) }}"
RETURN:
_value:
description: resulting number
type: int

@ -0,0 +1,24 @@
DOCUMENTATION:
name: sha1
version_added: "historical"
short_description: sha1 hash of input data
description:
- Returns a sha1 hash of the input data
positional: _input
notes:
- This requires the md5 algorithim to be available on the system, security contexts like FIPS might prevent this.
- SHA1 has been deemed insecure and is not recommended for security related uses.
options:
_input:
description: data to hash
type: raw
required: true
EXAMPLES: |
# sha1hash => "dc724af18fbdd4e59189f5fe768a5f8311527050"
sha1hash: "{{ 'testing' | sha1 }}"
RETURN:
_value:
description: The sha1 hash of the input
type: string

@ -0,0 +1,27 @@
DOCUMENTATION:
name: shuffle
version_added: "2.6"
short_description: randomize a list
description:
- Take the elements of the input list and return in a random order
positional: _input
options:
_input:
description: A number or list to randomize
type: list
elements: any
required: true
seed:
description: if specified use a pseudo random selection instead (repeatable)
type: str
EXAMPLES:
randomized_list: "{{ ['a','b','c'] | shuffle}}"
per_host_repeatable: "{{ ['a','b','c'] | shuffle(seed=inventory_hostname) }}"
RETURN:
_value:
description: random number or list element
type: list
elements: any

@ -0,0 +1,32 @@
DOCUMENTATION:
name: split
version_added: "historical"
short_description: split a string into a list
description:
- Using Python's text object method C(split()) we turn strings into lists via a 'spliting character'.
notes:
- This is a passthrough to Python's C(shelex.quote)
positional: _input, _split_string
options:
_input:
description: A string to split
type: str
required: true
_split_string:
description: a string on which to split the original
type: str
default: ' '
EXAMPLES:
# listjojo => [ "jojo", "is", "a" ]
listjojo: "{{ 'jojo is a' | split }}"
# listjojocomma => [ "jojo is", "a" ]
listjojocomma: "{{ 'jojo is, a' | split(',' }}"
RETURN:
_value:
description: list of substrings split from the original
type: list
elements: str

@ -2,29 +2,29 @@ DOCUMENTATION:
name: splitext
author: Matt Martz (@sivel)
version_added: "2.0"
short_description: split a filename into root and file extension
short_description: split a path into root and file extension
positional: _input
description:
- Returns a tuple consisting of C(root) and C(extension), where C(root ~ extension) equals the filename.
- Returns a list of two, with the elements consisting filename root and extension
options:
_input:
description:
- A filename.
- Path components contained in the filename will be returned as part of the root.
description: A path.
type: str
required: true
EXAMPLES: |
# with path == 'nginx.conf' the return would be ('nginx', '.conf')
{{ path | splitext }}
# gobble => [ '/etc/make', 'conf' ]
gobble: "{{ '/etc/make.conf' | splitext }}"
# with path == 'nginx.conf' the return would be 'nginx'
{{ path | splitext | first }}
# file_n_ext => [ 'ansible', 'cfg' ]
file_n_ext: "{{ 'ansible.cfg' | splitext }}"
# with path == 'nginx.conf' the return would be '.conf'
{{ path | splitext | last }}
# hoax => ['/etc/hoasdf', '']
hoax: '{{ "/etc//hoasdf/"|splitext }}'
RETURN:
_value:
description: A tuple consisting of root and the extension.
type: tuple
description: A list consisting of root of the path and the extension.
type: list
elements: str

@ -0,0 +1,43 @@
DOCUMENTATION:
name: strftime
version_added: "2.4"
short_description: date formating
description:
- Using Python's stftime function, take a data formating string and a date/time to create a formated date.
notes:
- This is a passthrough to Python's C(shelex.quote)
positional: _input, second, utc
options:
_input:
description: A formating string following stftime convetions
type: str
required: true
second:
description: datetime in seconds from C(epoch) to format, if not suplied C(gmttime()/localtime()) will be used
type: int
utc:
description: if time supplied is in UTC
type: bool
default: false
EXAMPLES: |
# Display year-month-day
{{ '%Y-%m-%d' | strftime }}
# => "2021-03-19"
# Display hour:min:sec
{{ '%H:%M:%S' | strftime }}
# => "21:51:04"
# Use ansible_date_time.epoch fact
{{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }}
# => "2021-03-19 21:54:09"
# Use arbitrary epoch value
{{ '%Y-%m-%d' | strftime(0) }} # => 1970-01-01
{{ '%Y-%m-%d' | strftime(1441357287) }} # => 2015-09-04
RETURN:
_value:
description: a formated date/time
type: str

@ -0,0 +1,38 @@
DOCUMENTATION:
name: subelements
version_added: "2.7"
short_description: retuns a product of a list and it's elements
positional: _input, _subelement, skip_missing
description:
- This produces a product of an object and the subelement values of that object, similar to the subelements lookup. This lets you specify individual subelements to use in a template _input
options:
_input:
description: Original list
type: list
elements: any
required: yes
_subelement:
description: Label of property to extract from original list items
type: str
required: yes
skip_missing:
description: if C(True), ignore missing subelements, otherwise it is an error.
type: bool
default: no
EXAMPLES: |
# data
users:
- groups: [1,2,3]
name: lola
- name: fernando
groups: [2,3,4]
# user_w_groups =>[ { "groups": [ 1, 2, 3 ], "name": "lola" }, 1 ], [ { "groups": [ 1, 2, 3 ], "name": "lola" }, 2 ], [ { "groups": [ 1, 2, 3 ], "name": "lola" }, 3 ], [ { "groups": [ 2, 3, 4 ], "name": "fernando" }, 2 ], [ { "groups": [ 2, 3, 4 ], "name": "fernando" }, 3 ], [ { "groups": [ 2, 3, 4 ], "name": "fernando" }, 4 ] ]
users_w_groups: {{ users | subelements('groups', skip_missing=True) }}
RETURN:
_value:
description: list made of original list and product of the subelement list
type: list
elements: any

@ -0,0 +1,34 @@
DOCUMENTATION:
name: to_datetime
version_added: "2.4"
short_description: Get datetime from string
description:
- Using the input string attempt to create a matching Python datetime object
notes:
- For a full list of format codes for working with python date format strings, see https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.
positional: _input
options:
_input:
description: A string containing date time information
type: str
required: true
format:
description: strformat formated string that describes the expected format of the input string
type: str
EXAMPLES: |
# Get total amount of seconds between two dates. Default date format is %Y-%m-%d %H:%M:%S but you can pass your own format
secsdiff: '{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime("%Y-%m-%d"))).total_seconds() }}'
# Get remaining seconds after delta has been calculated. NOTE: This does NOT convert years, days, hours, and so on to seconds. For that, use total_seconds()
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2016-08-14 18:00:00" | to_datetime)).seconds }}
# This expression evaluates to "12" and not "132". Delta is 2 hours, 12 seconds
# get amount of days between two dates. This returns only number of days and discards remaining hours, minutes, and seconds
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).days }}
RETURN:
_value:
description: datetime object from the represented value
type: raw

@ -0,0 +1,39 @@
DOCUMENTATION:
name: to_yaml
author: core team
version_added: 'historical'
short_description: Convert variable to YAML string
description:
- Converts an Ansible variable into a YAML string representation.
- This filter functions as a wrapper to the Python pyaml library's ``yaml.dump()`` function.
- Ansible internally auto-converts YAML strings into variable structures so this plugin is used to force it into a YAML string.
positional: _input
options:
_input:
description: A variable or expression that returns a data structure.
type: raw
required: true
indent:
description: Number of spaces to indent python structures, mainly used for display to humans
type: integer
sort_keys:
description: Affects sorting of dictionary keys
default: True
type: bool
#allow_unicode:
# description:
# type: bool
# default: true
#default_style=None, canonical=None, width=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None
notes:
- more optoins may be available, see pyyaml docs for details
- 'These parameters to ``yaml.dump()`` will be ignored, as they are overriden internally: I(default_flow_style)'
EXAMPLES: |
# dump variable in a template to create a YAML document
{{ github_workflow |to_nice_yaml}}
RETURN:
_value:
description: The YAML serialized string representing the variable structure inputted
type: string

@ -0,0 +1,30 @@
DOCUMENTATION:
name: to_uuid
version_added: "2.9"
short_description: namespaced UUID generator
description:
- Use to generate namespeced Universal Unique ID
positional: _input, namespace
options:
_input:
description: string to use as base fo the UUID
type: str
required: true
namespace:
description: UUID nsamespace to use
type: str
default: 361E6D51-FAEC-444A-9079-341386DA8E2E
EXAMPLES: |
# To create a namespaced UUIDv5
uuid: "{{ string | to_uuid(namespace='11111111-2222-3333-4444-555555555555') }}"
# To create a namespaced UUIDv5 using the default Ansible namespace '361E6D51-FAEC-444A-9079-341386DA8E2E'
uuid: "{{ string | to_uuid }}"
RETURN:
_value:
description: generated UUID
type: string

@ -0,0 +1,52 @@
DOCUMENTATION:
name: to_yaml
author: core team
version_added: 'historical'
short_description: Convert variable to YAML string
description:
- Converts an Ansible variable into a YAML string representation.
- This filter functions as a wrapper to the Python pyaml library's ``yaml.dump()`` function.
- Ansible internally auto-converts YAML strings into variable structures so this plugin is used to force it into a YAML string.
positional: _input
options:
_input:
description: A variable or expression that returns a data structure.
type: raw
required: true
indent:
description: Number of spaces to indent python structures, mainly used for display to humans
type: integer
sort_keys:
description: Affects sorting of dictionary keys
default: True
type: bool
notes:
- more optoins may be available, see pyyaml docs for details
# TODO: find docs for these
#allow_unicode:
# description:
# type: bool
# default: true
#default_flow_style
#default_style
#canonical=None,
#width=None,
#line_break=None,
#encoding=None,
#explicit_start=None,
#explicit_end=None,
#version=None,
#tags=None
EXAMPLES: |
# dump variable in a template to create a YAML document
{{ github_workflow |to_yaml}}
# same as above but 'prettier' (equivalent to to_nice_yaml filter)
{{ docker_config|to_json(indent=4) }}
RETURN:
_value:
description: The YAML serialized string representing the variable structure inputted
type: string

@ -0,0 +1,46 @@
DOCUMENTATION:
name: urlsplit
version_added: "2.4"
short_description: get components from URL
description:
- Given an URL, spiti it into it's component parts
positional: _input, query
options:
_input:
description: url string to split
type: str
required: true
query:
description: specify a single compoenent to return
type: str
choices: ["fragment", "hostname", "netloc", "password", "path", "port", "query", "scheme", "username"]
RETURN:
_value:
description: a dictionary with components as keyword and their value
type: dict
EXAMPLES: |
{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit }}
# =>
# {
# "fragment": "fragment",
# "hostname": "www.acme.com",
# "netloc": "user:password@www.acme.com:9000",
# "password": "password",
# "path": "/dir/index.html",
# "port": 9000,
# "query": "query=term",
# "scheme": "http",
# "username": "user"
# }
{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit('hostname') }}
# => 'www.acme.com'
{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit('query') }}
# => 'query=term'
{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit('path') }}
# => '/dir/index.html'

@ -5,6 +5,55 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
name: urlsplit
version_added: "2.4"
short_description: get components from URL
description:
- Given an URL, spiti it into it's component parts
positional: _input, query
options:
_input:
description: url string to split
type: str
required: true
query:
description: specify a single compoenent to return
type: str
choices: ["fragment", "hostname", "netloc", "password", "path", "port", "query", "scheme", "username"]
'''
EXAMPLES = r'''
parts: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit }}'
# =>
# {
# "fragment": "fragment",
# "hostname": "www.acme.com",
# "netloc": "user:password@www.acme.com:9000",
# "password": "password",
# "path": "/dir/index.html",
# "port": 9000,
# "query": "query=term",
# "scheme": "http",
# "username": "user"
# }
hostname: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("hostname") }}'
# => 'www.acme.com'
query: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("query") }}'
# => 'query=term'
path: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("path") }}'
# => '/dir/index.html'
'''
RETURN = r'''
_value:
description: a dictionary with components as keyword and their value
type: dict
'''
from urllib.parse import urlsplit

@ -0,0 +1,43 @@
DOCUMENTATION:
name: zip
version_added: "2.3"
short_description: combine list elements
positional: _input, _additional_lists
description: Iterate over several iterables in parallel, producing tuples with an item from each one
notes:
- This is mostly a passhtrough to Python's C(zip) function
options:
_input:
description: Original list
type: list
elements: any
required: yes
_additional_lists:
description: Additional list(s)
type: list
elements: any
required: yes
strict:
description: If C(True) return an error on mismatching list length, otherwise shortest list determines output
type: bool
default: no
EXAMPLES: |
# two => [[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"], [6, "f"]]
two: "{{ [1,2,3,4,5,6] | zip(['a','b','c','d','e','f']) }}"
# three => [ [ 1, "a", "d" ], [ 2, "b", "e" ], [ 3, "c", "f" ] ]
three: "{{ [1,2,3] | zip(['a','b','c'], ['d','e','f']) }}"
# shorter => [[1, "a"], [2, "b"], [3, "c"]]
shorter: "{{ [1,2,3] | zip(['a','b','c','d','e','f']) }}"
# compose dict from lists of keys and values
mydcit: "{{ dict(keys_list | zip(values_list)) }}"
RETURN:
_value:
description: list of lists made of elements matching the positions of the input lists
type: list
elements: list

@ -0,0 +1,36 @@
DOCUMENTATION:
name: zip_longest
version_added: "2.3"
short_description: combine list elements, with filler
positional: _input, _additional_lists
description:
- Make an iterator that aggregates elements from each of the iterables.
If the iterables are of uneven length, missing values are filled-in with fillvalue.
Iteration continues until the longest iterable is exhausted.
notes:
- This is mostly a passhtrough to Python's C(itertools.zip_longest) function
options:
_input:
description: Original list
type: list
elements: any
required: yes
_additional_lists:
description: Additional list(s)
type: list
elements: any
required: yes
fillvalue:
description: Filler value to add to output when one of the lists does not contain enough elements to match the others
type: any
EXAMPLES: |
# X_fill => [[1, "a", 21], [2, "b", 22], [3, "c", 23], ["X", "d", "X"], ["X", "e", "X"], ["X", "f", "X"]]
X_fill: "{{ [1,2,3] | zip_longest(['a','b','c','d','e','f'], [21, 22, 23], fillvalue='X') }}"
RETURN:
_value:
description: list of lists made of elements matching the positions of the input lists
type: list
elements: list
Loading…
Cancel
Save