Skip to content

Commit

Permalink
issue ansible#2672 usage docs
Browse files Browse the repository at this point in the history
  • Loading branch information
oraNod committed Nov 21, 2022
1 parent 7be2420 commit c49d13c
Showing 1 changed file with 77 additions and 107 deletions.
184 changes: 77 additions & 107 deletions docs/usage.md
Original file line number Diff line number Diff line change
@@ -1,190 +1,165 @@
(using-lint)=

# Usage
# Using Ansible-lint

```{contents} Topics
```

## Command Line Options
## Working with Ansible-lint commands

The tool produces output on both `stdout` and `stderr`, first one being
used to display any matching rule violations while the second one being used
for logging and free form messages, like displaying stats.

In most of our examples we will be using the pep8 output format (`-p`) which
is machine parseable. The default output format is more verbose and likely
to contain more information, like long description of the rule and its
associated tags.
After you install Ansible-lint, run `ansible-lint --help` to display available commands and their options.

```{command-output} ansible-lint --help
:cwd: ..
:returncode: 0
```

## Temporary files
### Ansible-lint output

As part of the execution, the linter will likely need to create a cache of
installed or mocked roles, collections and modules. This is done inside
`{project_dir}/.cache` folder. The project directory is either given as a
command line argument, determined by location of the configuration
file, git project top-level directory or user home directory as fallback.
In order to speed-up reruns, the linter does not clean this folder by itself.
Ansible-lint prints output on both `stdout` and `stderr`.

If you are using git, you will likely want to add this folder to your
`.gitignore` file.
* `stdout` displays rule violations.
* `stderr` displays logging and free-form messages like statistics.

## Progressive mode
Most `ansible-lint` examples use pep8 as the output format (`-p`) which is machine parseable.

In order to ease tool adoption, git users can enable the progressive mode using
`--progressive` option. This makes the linter return a success even if
some failures are found, as long the total number of violations did not
increase since the previous commit.
Ansible-lint also print errors using their [annotation] format when it detects the `GITHUB_ACTIONS=true` and `GITHUB_WORKFLOW=...` variables.

As expected, this mode makes the linter run twice if it finds any violations.
The second run is performed against a temporary git working copy that contains
the previous commit. All the violations that were already present are removed
from the list and the final result is displayed.
[annotation]: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message

The most notable benefit introduced by this mode it does not prevent merging
new code while allowing developer to address historical violation at his own
speed.
## Configuring Ansible-lint caches

## CI/CD
For optimal performance, Ansible-lint creates caches with installed or mocked roles, collections, and modules in the `{project_dir}/.cache` folder.
The location of `{project_dir}` is passed with a command line argument, determined by the location of the configuration file, git project top-level directory, or user home directory.

If execution under [Github Actions] is detected via the presence of
`GITHUB_ACTIONS=true` and `GITHUB_WORKFLOW=...` variables, the linter will
also print errors using their [annotation] format.
To perform faster re-runs, Ansible-lint does not automatically clean the cache.
If required you can do this manually by simply deleting the `.cache` folder.
Ansible-lint creates a new cache on the next invocation.

## Linting Playbooks and Roles
You should add the `.cache` folder to the `.gitignore` file in your git repositories.

We recommend following the {ref}`collection structure layout <collection_structure>` regardless if you are planning to build a
collection or not. Following that layout assures the best integration
with all ecosystem tools as it helps them better distinguish between
random YAML files and files managed by ansible.
## Using progressive mode

For easier adoption, Ansible-lint can alert for rule violations that occur since the last commit.
This allows new code to be merged without any rule violations while allowing content developers to address historical violations at a different pace.

The `--progressive` option runs Ansible-lint twice if rule violations exist in your content.
The second run is performed against a temporary git working copy that contains
the last commit.
Rule violations that exist in the last commit are ignored and Ansible-lint displays only the violations that exist in the new commit.

When you call ansible-lint without arguments the tool will use its internal
heuristics to determine file types.
## Linting playbooks and roles

`ansible-lint` also accepts a list of **roles** or **playbooks** as
arguments. The following command lints `examples/playbooks/play.yml` and
`examples/roles/bobbins` role:
Ansible-lint recommends following the {ref}`collection structure layout <collection_structure>` whether you plan to build a collection or not.

Following that layout assures the best integration with all ecosystem tools because it helps those tools better distinguish between random YAML files and files managed by Ansible.
When you call `ansible-lint` without arguments, it uses internal heuristics to determine file types.

You can specify the list of **roles** or **playbooks** that you want to lint with the `-p` argument.
For example, to lint `examples/playbooks/play.yml` and `examples/roles/bobbins`, use the following command:

```{command-output} ansible-lint -p examples/playbooks/play.yml examples/roles/bobbins
:cwd: ..
:returncode: 2
:nostderr: true
```

## Examples
## Running example playbooks

Included in `ansible-lint/examples` are some example playbooks with
undesirable features. Running ansible-lint on them works, as demonstrated in
the following:
Ansible-lint includes an `ansible-lint/examples` folder that contains example playbooks with different rule violations and undesirable characteristics.
You can run `ansible-lint` on the example playbooks to observe Ansible-lint in action, as follows:

```{command-output} ansible-lint -p examples/playbooks/example.yml
:cwd: ..
:returncode: 2
:nostderr: true
```

If playbooks include other playbooks, or tasks, or handlers or roles, these
are also handled:
Ansible-lint also handles playbooks that include other playbooks, tasks, handlers, or roles, as the `examples/playbooks/include.yml` example demonstrates.

```{command-output} ansible-lint --force-color --offline -p examples/playbooks/include.yml
:cwd: ..
:returncode: 2
:nostderr: true
```

A `JSON` report, based on codeclimate specification, can be generated with
ansible-lint.
You can generate `JSON` reports based on the codeclimate specification as the `examples/playbooks/norole.yml` example demonstrates.

```{command-output} ansible-lint -f json examples/playbooks/norole.yml
:cwd: ..
:returncode: 2
:nostderr: true
```

[annotation]: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message
[github actions]: https://github.com/features/actions
## Specifying rules at runtime

## Specifying Rules at Runtime
By default, `ansible-lint` applies rules found in `ansible-lint/src/ansiblelint/rules`.
Use the `-r /path/to/custom-rules` option to specify the directory path to a set of custom rules.
For multiple custom rule sets, pass each set with a separate `-r` option.

By default, `ansible-lint` uses the rules found in
`ansible-lint/src/ansiblelint/rules`. To override this behavior and use a
custom set of rules, use the `-r /path/to/custom-rules` option to provide a
directory path containing the custom rules. For multiple rule sets, pass
multiple `-r` options.
You can also combine the default rules with custom rules with the `-R` option along with one or more `-r` options.

It's also possible to use the default rules, plus custom rules. This can be
done by passing the `-R` to indicate that the default rules are to be used,
along with one or more `-r` options.
### Including rules with tags

### Using Tags to Include Rules
Each rule has an associated set of one or more tags.
Use the `-T` option to view the list of tags for each available rule.

Each rule has an associated set of one or more tags. To view the list of tags
for each available rule, use the `-T` option.
You can then use the `-t` option to specify a tag and include the associated rules in the lint run.
For example, the following `ansible-lint` command applies only the rules associated with the _idempotency_ tag:

The following shows the available tags in an example set of rules, and the
rules associated with each tag:
```bash
$ ansible-lint -t idempotency playbook.yml
```

The following shows the available tags in an example set of rules and the rules associated with each tag:

```{command-output} ansible-lint -T
:cwd: ..
:returncode: 0
:nostderr: true
```

To run just the _idempotency_ rules, for example, run the following:

```bash
$ ansible-lint -t idempotency playbook.yml
```

### Excluding Rules
### Excluding rules with tags

To exclude rules using their identifiers or tags, use the `-x SKIP_LIST`
option. For example, the following runs all of the rules except those with the
tags _formatting_ and _metadata_:
To exclude rules by identifiers or tags, use the `-x SKIP_LIST` option.
For example, the following command applies all rules except those with the _formatting_ and _metadata_ tags:

```bash
$ ansible-lint -x formatting,metadata playbook.yml
```

### Ignoring Rules
### Ignoring rules

To only warn about rules, use the `-w WARN_LIST` option. In this example all
rules are run, but if rules with the `experimental` tag match they only show
an error message but don't change the exit code:
To only warn about rules, use the `-w WARN_LIST` option.
For example, the following command displays only warns about violations with rules associated with the `experimental` tag:

```console
$ ansible-lint -w experimental playbook.yml
```

The default value for `WARN_LIST` is `['experimental']` if you don't
define your own either on the cli or in the config file. If you do define your
own `WARN_LIST` you will need to add `'experimental'` to it if you don't
want experimental rules to change your exit code.
By default, the `WARN_LIST` includes the `['experimental']` tag.
If you define a custom `WARN_LIST` you must add `'experimental'` so that Ansible-lint does not fail against experimental rules.

## False positives: muting Ansible-lint warnings

## False Positives: Skipping Rules
Not all linting rules are precise, some are general rules of thumb.
Advanced _git_, _yum_ or _apt_ usage, for example, can be difficult to achieve in a playbook.
In cases like this, Ansible-lint can incorrectly trigger rule violations.

Some rules are a bit of a rule of thumb. Advanced _git_, _yum_ or _apt_ usage,
for example, is typically difficult to achieve through the modules. In this
case, you should mark the task so that warnings aren't produced.
To disable rule violations for specific tasks, and mute false positives, add `# noqa [rule_id]` to the end of the line.
It is best practice to add a comment that explains why rules are disabled.

To skip a specific rule for a specific task, inside your ansible yaml add
`# noqa [rule_id]` at the end of the line. If the rule is task-based (most
are), add at the end of any line in the task. You can skip multiple rules via
a space-separated list.
You can add the `# noqa [rule_id]` comment to the end of any line in a task.
You can also skip multiple rules with a space-separated list.

```yaml
- name: This would typically fire git-latest and partial-become
- name: This task would typically fire git-latest and partial-become rules
become_user: alice # noqa git-latest partial-become
git: src=/path/to/git/repo dest=checkout
ansible.builtin.git: src=/path/to/git/repo dest=checkout
```
If the rule is line-based, `# noqa [rule_id]` must be at the end of the
particular line to be skipped
If the rule is line-based, `# noqa [rule_id]` must be at the end of the line.

```yaml
- name: This would typically fire LineTooLongRule 204 and jinja[spacing]
Expand All @@ -193,15 +168,10 @@ particular line to be skipped
dest: "{{dest_proj_path}}/foo.conf" # noqa jinja[spacing]
```

It's also a good practice to comment the reasons why a task is being skipped.

If you want skip running a rule entirely, you can use either use `-x` command
line argument, or add it to `skip_list` inside the configuration file.
If you want Ansible-lint to skip a rule entirely, use the `-x` command line argument or add it to `skip_list` in your configuration.

A less-preferred method of skipping is to skip all task-based rules for a task
(this does not skip line-based rules). There are two mechanisms for this: the
`skip_ansible_lint` tag works with all tasks, and the `warn` parameter
works with the _command_ or _shell_ modules only. Examples:
The least preferred method of skipping rules is to skip all task-based rules for a task, which does not skip line-based rules.
You can use the `skip_ansible_lint` tag with all tasks or the `warn` parameter with the _command_ or _shell_ modules, for example:

```yaml
- name: This would typically fire deprecated-command-syntax
Expand Down

0 comments on commit c49d13c

Please sign in to comment.