Skip to content

Commit

Permalink
Use temporary playbooks to check role syntax (#3280)
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbarnea committed Apr 13, 2023
1 parent e197112 commit 6da0313
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 17 deletions.
1 change: 1 addition & 0 deletions .config/dictionary.txt
Expand Up @@ -167,6 +167,7 @@ isdir
isdisjoint
iskeyword
isort
isorted
jsonfile
jsonschema
junitxml
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -3,6 +3,9 @@ __pycache__
*.py[co]
*$py.class

# Temporary ruff file
*.isorted

# Packages
.Python
env/
Expand Down
44 changes: 27 additions & 17 deletions src/ansiblelint/rules/syntax_check.py
Expand Up @@ -5,6 +5,7 @@
import re
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from typing import Any

Expand Down Expand Up @@ -72,33 +73,40 @@ class AnsibleSyntaxCheckRule(AnsibleLintRule):
def _get_ansible_syntax_check_matches(lintable: Lintable) -> list[MatchError]:
"""Run ansible syntax check and return a list of MatchError(s)."""
default_rule: BaseRule = AnsibleSyntaxCheckRule()
fh = None
results = []
if lintable.kind not in ("playbook", "role"):
return []

with timed_info(
"Executing syntax check on %s %s", lintable.kind, lintable.path
):
if lintable.kind == "role":
playbook_text = f"""
---
- name: Temporary playbook for role syntax check
hosts: localhost
tasks:
- ansible.builtin.import_role:
name: {str(lintable.path.expanduser())}
"""
# pylint: disable=consider-using-with
fh = tempfile.NamedTemporaryFile(mode="w", suffix=".yml", prefix="play")
fh.write(playbook_text)
fh.flush()
playbook_path = fh.name
else:
playbook_path = str(lintable.path.expanduser())
# To avoid noisy warnings we pass localhost as current inventory:
# [WARNING]: No inventory was parsed, only implicit localhost is available
# [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
if lintable.kind == "playbook":
cmd = [
"ansible-playbook",
"-i",
"localhost,",
"--syntax-check",
str(lintable.path.expanduser()),
]
else: # role
cmd = [
"ansible",
"localhost",
"--syntax-check",
"--module-name=include_role",
"--args",
f"name={str(lintable.path.expanduser())}",
]
cmd = [
"ansible-playbook",
"-i",
"localhost,",
"--syntax-check",
playbook_path,
]
if options.extra_vars:
cmd.extend(["--extra-vars", json.dumps(options.extra_vars)])

Expand Down Expand Up @@ -178,6 +186,8 @@ def _get_ansible_syntax_check_matches(lintable: Lintable) -> list[MatchError]:
)
)

if fh:
fh.close()
return results


Expand Down

0 comments on commit 6da0313

Please sign in to comment.