# Ansible

> ⚠ **WARNING**: Extra vars won't get overwritten in the playbook life cycle, not even with `set_fact`!

## Adhoc commands

**Generic**

```
ansible <hosts/groups pattern> -l <limit pattern> -m <module> -a "<module args>" -u <login user> --become --ask-become-pass
```

**Example**

```
ansible all -l localhost -m systemd -a "name=nginx state=restarted" -u test --become --ask-become-pass
```

## Usecases

### Filter numbers from a list of strings

`sample.result_list` is a list of lists containing stdout output. We want to filter some numbers from this output. To do this we first filter the correct lines by using the `json_query` filter. If you need to match a specific substring, you could use `select("match", "<regex>")` in combination with the `json_query`. Next we `map` the `regex_search` filter on all lines to extract the data we need. As the `map` filter is a Python generator object, we need to convert it to a list.

The regex `(?<=\()\d+` uses a feature called *positive lookbehind*: `(?<=\()`. It matches a group before the main expression with including it in the result. In this case it matches the opening parantheses `(`. This feature may not be supported in your regex implementation, but in Ansible/Python it is supported. To make the regex even more specific you could add a *positive lookahead* (`(?=\))`) after the `\d+` to match the closing parantheses `)`.

```yaml
---

- hosts: localhost

  vars:
    sample:
      result_list:
      - stdout_lines:
        - 'line0'
        - 'line12 (2319)'
      - stdout_lines:
        - 'line2'
        - 'line12 (2320)'

  tasks:
  - debug:
      msg: '{{ sample.result_list | json_query("[*].stdout_lines[1]") | map("regex_search" ,"(?<=\()\d+") | list }}'
```

## Skip (or run) tags by default

When working with tags you may not want to run tasks with a specific tag. For this you can add a section `tags` to the `ansible.cfg` file:

```ini
[tags]
skip: my_tag_to_skip
```

## Links

* [Module defaults](https://docs.ansible.com/ansible/latest/user_guide/playbooks_module_defaults.html)
* [Module rejection](https://docs.ansible.com/ansible/latest/user_guide/plugin_filtering_config.html)
* [JMESPath examples](https://jmespath.org/examples.html)
