Skip to content

Commit 7b31bc2

Browse files
Migrated Token-related info and list modules to new framework (#576)
* Migrated token info and list modules * Fixed docs
1 parent 9f3f30c commit 7b31bc2

File tree

6 files changed

+64
-226
lines changed

6 files changed

+64
-226
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ Name | Description |
107107
[linode.cloud.region_list](./docs/modules/region_list.md)|List and filter on Regions.|
108108
[linode.cloud.ssh_key_list](./docs/modules/ssh_key_list.md)|List and filter on SSH keys in the Linode profile.|
109109
[linode.cloud.stackscript_list](./docs/modules/stackscript_list.md)|List and filter on StackScripts.|
110-
[linode.cloud.token_list](./docs/modules/token_list.md)|List and filter on Linode Account tokens.|
110+
[linode.cloud.token_list](./docs/modules/token_list.md)|List and filter on Tokens.|
111111
[linode.cloud.type_list](./docs/modules/type_list.md)|List and filter on Types.|
112112
[linode.cloud.user_list](./docs/modules/user_list.md)|List Users.|
113113
[linode.cloud.vlan_list](./docs/modules/vlan_list.md)|List and filter on Linode VLANs.|

docs/inventory/instance.rst

+4-4
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ Parameters
5858

5959

6060
**strict (type=bool):**
61-
\• If \ :literal:`yes`\ make invalid entries a fatal error, otherwise skip and continue.
61+
\• If :literal:`yes` make invalid entries a fatal error, otherwise skip and continue.
6262

6363
\• Since it is possible to use facts in the expressions they might not always be available and we ignore those errors by default.
6464

@@ -94,13 +94,13 @@ Parameters
9494
**default_value (type=str):**
9595
\• The default value when the host variable's value is an empty string.
9696

97-
\• This option is mutually exclusive with \ :literal:`keyed\_groups[].trailing\_separator`\ .
97+
\• This option is mutually exclusive with :literal:`keyed\_groups[].trailing\_separator`.
9898

9999

100100
**trailing_separator (type=bool, default=True):**
101-
\• Set this option to \ :literal:`False`\ to omit the \ :literal:`keyed\_groups[].separator`\ after the host variable when the value is an empty string.
101+
\• Set this option to :literal:`False` to omit the :literal:`keyed\_groups[].separator` after the host variable when the value is an empty string.
102102

103-
\• This option is mutually exclusive with \ :literal:`keyed\_groups[].default\_value`\ .
103+
\• This option is mutually exclusive with :literal:`keyed\_groups[].default\_value`.
104104

105105

106106

docs/modules/token_info.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,12 @@ Get info about a Linode Personal Access Token.
3131
3232
| Field | Type | Required | Description |
3333
|-----------|------|----------|------------------------------------------------------------------------------|
34-
| `id` | <center>`int`</center> | <center>Optional</center> | The ID of the token. **(Conflicts With: `label`)** |
35-
| `label` | <center>`str`</center> | <center>Optional</center> | The label of the token. **(Conflicts With: `id`)** |
34+
| `label` | <center>`str`</center> | <center>Optional</center> | The label of the Personal Access Token to resolve. **(Conflicts With: `id`)** |
35+
| `id` | <center>`int`</center> | <center>Optional</center> | The ID of the Personal Access Token to resolve. **(Conflicts With: `label`)** |
3636

3737
## Return Values
3838

39-
- `token` - The token in JSON serialized form.
39+
- `token` - The returned Personal Access Token.
4040

4141
- Sample Response:
4242
```json
@@ -49,6 +49,6 @@ Get info about a Linode Personal Access Token.
4949
"token": "abcdefghijklmnop"
5050
}
5151
```
52-
- See the [Linode API response documentation](https://techdocs.akamai.com/linode-api/reference/post-personal-access-token) for a list of returned fields
52+
- See the [Linode API response documentation](https://techdocs.akamai.com/linode-api/reference/get-personal-access-tokens) for a list of returned fields
5353

5454

docs/modules/token_list.md

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# token_list
22

3-
List and filter on Linode Account tokens.
3+
List and filter on Tokens.
44

55
- [Minimum Required Fields](#minimum-required-fields)
66
- [Examples](#examples)
@@ -32,21 +32,21 @@ List and filter on Linode Account tokens.
3232
3333
| Field | Type | Required | Description |
3434
|-----------|------|----------|------------------------------------------------------------------------------|
35-
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list tokens in. **(Choices: `desc`, `asc`; Default: `asc`)** |
36-
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order tokens by. |
37-
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting tokens. |
38-
| `count` | <center>`int`</center> | <center>Optional</center> | The number of results to return. If undefined, all results will be returned. |
35+
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list Tokens in. **(Choices: `desc`, `asc`; Default: `asc`)** |
36+
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order Tokens by. |
37+
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting Tokens. |
38+
| `count` | <center>`int`</center> | <center>Optional</center> | The number of Tokens to return. If undefined, all results will be returned. |
3939

4040
### filters
4141

4242
| Field | Type | Required | Description |
4343
|-----------|------|----------|------------------------------------------------------------------------------|
44-
| `name` | <center>`str`</center> | <center>**Required**</center> | The name of the field to filter on. Valid filterable attributes can be found here: https://techdocs.akamai.com/linode-api/reference/get-profile |
44+
| `name` | <center>`str`</center> | <center>**Required**</center> | The name of the field to filter on. Valid filterable fields can be found [here](https://techdocs.akamai.com/linode-api/reference/get-personal-access-tokens). |
4545
| `values` | <center>`list`</center> | <center>**Required**</center> | A list of values to allow for this field. Fields will pass this filter if at least one of these values matches. |
4646

4747
## Return Values
4848

49-
- `tokens` - The returned tokens.
49+
- `tokens` - The returned Tokens.
5050

5151
- Sample Response:
5252
```json

plugins/modules/token_info.py

+37-98
Original file line numberDiff line numberDiff line change
@@ -5,120 +5,59 @@
55

66
from __future__ import absolute_import, division, print_function
77

8-
from typing import Any, Optional
9-
108
import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.token as docs_parent
119
import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.token_info as docs
12-
from ansible_collections.linode.cloud.plugins.module_utils.linode_common import (
13-
LinodeModuleBase,
14-
)
15-
from ansible_collections.linode.cloud.plugins.module_utils.linode_docs import (
16-
global_authors,
17-
global_requirements,
10+
from ansible_collections.linode.cloud.plugins.module_utils.linode_common_info import (
11+
InfoModule,
12+
InfoModuleAttr,
13+
InfoModuleResult,
1814
)
1915
from ansible_collections.linode.cloud.plugins.module_utils.linode_helper import (
20-
filter_null_values,
21-
)
22-
from ansible_specdoc.objects import (
23-
FieldType,
24-
SpecDocMeta,
25-
SpecField,
26-
SpecReturnValue,
16+
safe_find,
2717
)
18+
from ansible_specdoc.objects import FieldType
2819
from linode_api4 import PersonalAccessToken
2920

30-
spec = {
31-
# Disable the default values
32-
"state": SpecField(type=FieldType.string, required=False, doc_hide=True),
33-
"id": SpecField(
34-
type=FieldType.integer,
35-
description=["The ID of the token."],
36-
conflicts_with=["label"],
21+
module = InfoModule(
22+
primary_result=InfoModuleResult(
23+
field_name="token",
24+
field_type=FieldType.dict,
25+
display_name="Personal Access Token",
26+
docs_url="https://techdocs.akamai.com/linode-api/reference/get-personal-access-tokens",
27+
samples=docs_parent.result_token_samples,
3728
),
38-
"label": SpecField(
39-
type=FieldType.string,
40-
description=["The label of the token."],
41-
conflicts_with=["id"],
42-
),
43-
}
44-
45-
SPECDOC_META = SpecDocMeta(
46-
description=["Get info about a Linode Personal Access Token."],
47-
requirements=global_requirements,
48-
author=global_authors,
49-
options=spec,
29+
attributes=[
30+
InfoModuleAttr(
31+
display_name="ID",
32+
name="id",
33+
type=FieldType.integer,
34+
get=lambda client, params: client.load(
35+
PersonalAccessToken,
36+
params.get("id"),
37+
)._raw_json,
38+
),
39+
InfoModuleAttr(
40+
display_name="label",
41+
name="label",
42+
type=FieldType.string,
43+
get=lambda client, params: safe_find(
44+
client.profile.tokens,
45+
PersonalAccessToken.label == params.get("label"),
46+
raise_not_found=True,
47+
)._raw_json,
48+
),
49+
],
5050
examples=docs.specdoc_examples,
51-
return_values={
52-
"token": SpecReturnValue(
53-
description="The token in JSON serialized form.",
54-
docs_url="https://techdocs.akamai.com/linode-api/reference/post-personal-access-token",
55-
type=FieldType.dict,
56-
sample=docs_parent.result_token_samples,
57-
)
58-
},
5951
)
6052

53+
SPECDOC_META = module.spec
54+
6155
DOCUMENTATION = r"""
6256
"""
6357
EXAMPLES = r"""
6458
"""
6559
RETURN = r"""
6660
"""
6761

68-
69-
class Module(LinodeModuleBase):
70-
"""Module for getting info about a Linode token"""
71-
72-
def __init__(self) -> None:
73-
self.module_arg_spec = SPECDOC_META.ansible_spec
74-
self.results = {"token": None}
75-
76-
super().__init__(
77-
module_arg_spec=self.module_arg_spec,
78-
required_one_of=[("id", "label")],
79-
mutually_exclusive=[("id", "label")],
80-
)
81-
82-
def _get_token_by_label(self, label: str) -> Optional[PersonalAccessToken]:
83-
try:
84-
return self.client.profile.tokens(
85-
PersonalAccessToken.label == label
86-
)[0]
87-
except IndexError:
88-
return self.fail(
89-
msg="failed to get token with label {0}: "
90-
"token does not exist".format(label)
91-
)
92-
except Exception as exception:
93-
return self.fail(
94-
msg="failed to get token {0}: {1}".format(label, exception)
95-
)
96-
97-
def _get_token_by_id(self, token_id: int) -> PersonalAccessToken:
98-
return self._get_resource_by_id(PersonalAccessToken, token_id)
99-
100-
def exec_module(self, **kwargs: Any) -> Optional[dict]:
101-
"""Entrypoint for token info module"""
102-
103-
params = filter_null_values(self.module.params)
104-
105-
if "id" in params:
106-
self.results["token"] = self._get_token_by_id(
107-
params.get("id")
108-
)._raw_json
109-
110-
if "label" in params:
111-
self.results["token"] = self._get_token_by_label(
112-
params.get("label")
113-
)._raw_json
114-
115-
return self.results
116-
117-
118-
def main() -> None:
119-
"""Constructs and calls the module"""
120-
Module()
121-
122-
12362
if __name__ == "__main__":
124-
main()
63+
module.run()

plugins/modules/token_list.py

+11-112
Original file line numberDiff line numberDiff line change
@@ -4,129 +4,28 @@
44
"""This module allows users to list Linode tokens."""
55
from __future__ import absolute_import, division, print_function
66

7-
from typing import Any, Dict, Optional
8-
97
import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.token_list as docs
10-
from ansible_collections.linode.cloud.plugins.module_utils.linode_common import (
11-
LinodeModuleBase,
12-
)
13-
from ansible_collections.linode.cloud.plugins.module_utils.linode_docs import (
14-
global_authors,
15-
global_requirements,
16-
)
17-
from ansible_collections.linode.cloud.plugins.module_utils.linode_helper import (
18-
construct_api_filter,
19-
get_all_paginated,
8+
from ansible_collections.linode.cloud.plugins.module_utils.linode_common_list import (
9+
ListModule,
2010
)
21-
from ansible_specdoc.objects import (
22-
FieldType,
23-
SpecDocMeta,
24-
SpecField,
25-
SpecReturnValue,
26-
)
27-
28-
spec_filter = {
29-
"name": SpecField(
30-
type=FieldType.string,
31-
required=True,
32-
description=[
33-
"The name of the field to filter on.",
34-
"Valid filterable attributes can be found here: "
35-
"https://techdocs.akamai.com/linode-api/reference/get-profile",
36-
],
37-
),
38-
"values": SpecField(
39-
type=FieldType.list,
40-
element_type=FieldType.string,
41-
required=True,
42-
description=[
43-
"A list of values to allow for this field.",
44-
"Fields will pass this filter if at least one of these values matches.",
45-
],
46-
),
47-
}
4811

49-
spec = {
50-
# Disable the default values
51-
"state": SpecField(type=FieldType.string, required=False, doc_hide=True),
52-
"label": SpecField(type=FieldType.string, required=False, doc_hide=True),
53-
"order": SpecField(
54-
type=FieldType.string,
55-
description=["The order to list tokens in."],
56-
default="asc",
57-
choices=["desc", "asc"],
58-
),
59-
"order_by": SpecField(
60-
type=FieldType.string,
61-
description=["The attribute to order tokens by."],
62-
),
63-
"filters": SpecField(
64-
type=FieldType.list,
65-
element_type=FieldType.dict,
66-
suboptions=spec_filter,
67-
description=["A list of filters to apply to the resulting tokens."],
68-
),
69-
"count": SpecField(
70-
type=FieldType.integer,
71-
description=[
72-
"The number of results to return.",
73-
"If undefined, all results will be returned.",
74-
],
75-
),
76-
}
77-
78-
SPECDOC_META = SpecDocMeta(
79-
description=["List and filter on Linode Account tokens."],
80-
requirements=global_requirements,
81-
author=global_authors,
82-
options=spec,
12+
module = ListModule(
13+
result_display_name="Tokens",
14+
result_field_name="tokens",
15+
endpoint_template="/profile/tokens",
16+
result_docs_url="https://techdocs.akamai.com/linode-api/reference/get-personal-access-tokens",
8317
examples=docs.specdoc_examples,
84-
return_values={
85-
"tokens": SpecReturnValue(
86-
description="The returned tokens.",
87-
docs_url="https://techdocs.akamai.com/linode-api/reference/get-personal-access-tokens",
88-
type=FieldType.list,
89-
elements=FieldType.dict,
90-
sample=docs.result_tokens_samples,
91-
),
92-
},
18+
result_samples=docs.result_tokens_samples,
9319
)
9420

21+
SPECDOC_META = module.spec
22+
9523
DOCUMENTATION = r"""
9624
"""
9725
EXAMPLES = r"""
9826
"""
9927
RETURN = r"""
10028
"""
10129

102-
103-
class Module(LinodeModuleBase):
104-
"""Module for getting a list of Linode Account tokens"""
105-
106-
def __init__(self) -> None:
107-
self.module_arg_spec = SPECDOC_META.ansible_spec
108-
self.results: Dict[str, Any] = {"tokens": []}
109-
110-
super().__init__(module_arg_spec=self.module_arg_spec)
111-
112-
def exec_module(self, **kwargs: Any) -> Optional[dict]:
113-
"""Entrypoint for token list module"""
114-
115-
filter_dict = construct_api_filter(self.module.params)
116-
117-
self.results["tokens"] = get_all_paginated(
118-
self.client,
119-
"/profile/tokens",
120-
filter_dict,
121-
num_results=self.module.params["count"],
122-
)
123-
return self.results
124-
125-
126-
def main() -> None:
127-
"""Constructs and calls the module"""
128-
Module()
129-
130-
13130
if __name__ == "__main__":
132-
main()
31+
module.run()

0 commit comments

Comments
 (0)