7
7
from typing import TYPE_CHECKING , Any
8
8
9
9
from ansible .parsing .yaml .objects import AnsibleUnicode
10
+ from ansible .vars .reserved import get_reserved_names
10
11
11
12
from ansiblelint .config import options
12
13
from ansiblelint .constants import LINE_NUMBER_KEY , RC
@@ -31,8 +32,9 @@ class VariableNamingRule(AnsibleLintRule):
31
32
needs_raw_task = True
32
33
re_pattern_str = options .var_naming_pattern or "^[a-z_][a-z0-9_]*$"
33
34
re_pattern = re .compile (re_pattern_str )
35
+ reserved_names = get_reserved_names ()
34
36
35
- # pylint: disable=too-many-return-statements)
37
+ # pylint: disable=too-many-return-statements
36
38
def get_var_naming_matcherror (
37
39
self ,
38
40
ident : str ,
@@ -52,14 +54,21 @@ def get_var_naming_matcherror(
52
54
except UnicodeEncodeError :
53
55
return MatchError (
54
56
tag = "var-naming[non-ascii]" ,
55
- message = "Variables names must be ASCII." ,
57
+ message = f "Variables names must be ASCII. ( { ident } ) " ,
56
58
rule = self ,
57
59
)
58
60
59
61
if keyword .iskeyword (ident ):
60
62
return MatchError (
61
63
tag = "var-naming[no-keyword]" ,
62
- message = "Variables names must not be Python keywords." ,
64
+ message = f"Variables names must not be Python keywords. ({ ident } )" ,
65
+ rule = self ,
66
+ )
67
+
68
+ if ident in self .reserved_names :
69
+ return MatchError (
70
+ tag = "var-naming[no-reserved]" ,
71
+ message = f"Variables names must not be Ansible reserved names. ({ ident } )" ,
63
72
rule = self ,
64
73
)
65
74
@@ -74,7 +83,7 @@ def get_var_naming_matcherror(
74
83
if not bool (self .re_pattern .match (ident )):
75
84
return MatchError (
76
85
tag = "var-naming[pattern]" ,
77
- message = f"Variables names should match { self .re_pattern_str } regex." ,
86
+ message = f"Variables names should match { self .re_pattern_str } regex. ( { ident } ) " ,
78
87
rule = self ,
79
88
)
80
89
@@ -140,7 +149,6 @@ def matchtask(
140
149
results .append (match_error )
141
150
142
151
# If the task uses the 'set_fact' module
143
- # breakpoint()
144
152
ansible_module = task ["action" ]["__ansible_module__" ]
145
153
if ansible_module == "set_fact" :
146
154
for key in filter (
@@ -239,6 +247,7 @@ def test_invalid_var_name_varsfile(
239
247
("var-naming[no-jinja]" , 7 ),
240
248
("var-naming[no-keyword]" , 9 ),
241
249
("var-naming[non-ascii]" , 10 ),
250
+ ("var-naming[no-reserved]" , 11 ),
242
251
)
243
252
assert len (results ) == len (expected_errors )
244
253
for idx , result in enumerate (results ):
0 commit comments