Skip to content

Commit

Permalink
Migrated SSH-Key-related info and list modules to new framework (#577)
Browse files Browse the repository at this point in the history
* Migrated ssh_key info and list modules

* Fixed docs
  • Loading branch information
ezilber-akamai authored Aug 28, 2024
1 parent 1b2d1a7 commit abd4b35
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 221 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Name | Description |
[linode.cloud.object_cluster_info](./docs/modules/object_cluster_info.md)|**NOTE: This module has been deprecated because it relies on deprecated API endpoints. Going forward, `region` will be the preferred way to designate where Object Storage resources should be created.**|
[linode.cloud.placement_group_info](./docs/modules/placement_group_info.md)|Get info about a Linode Placement Group.|
[linode.cloud.profile_info](./docs/modules/profile_info.md)|Get info about a Linode Profile.|
[linode.cloud.ssh_key_info](./docs/modules/ssh_key_info.md)|Get info about the Linode SSH public key.|
[linode.cloud.ssh_key_info](./docs/modules/ssh_key_info.md)|Get info about a Linode SSH Key.|
[linode.cloud.stackscript_info](./docs/modules/stackscript_info.md)|Get info about a Linode StackScript.|
[linode.cloud.token_info](./docs/modules/token_info.md)|Get info about a Linode Personal Access Token.|
[linode.cloud.type_info](./docs/modules/type_info.md)|Get info about a Linode Type.|
Expand Down Expand Up @@ -105,7 +105,7 @@ Name | Description |
[linode.cloud.object_cluster_list](./docs/modules/object_cluster_list.md)|**NOTE: This module has been deprecated because it relies on deprecated API endpoints. Going forward, `region` will be the preferred way to designate where Object Storage resources should be created.**|
[linode.cloud.placement_group_list](./docs/modules/placement_group_list.md)|List and filter on Placement Groups.|
[linode.cloud.region_list](./docs/modules/region_list.md)|List and filter on Regions.|
[linode.cloud.ssh_key_list](./docs/modules/ssh_key_list.md)|List and filter on SSH keys in the Linode profile.|
[linode.cloud.ssh_key_list](./docs/modules/ssh_key_list.md)|List and filter on SSH Keys.|
[linode.cloud.stackscript_list](./docs/modules/stackscript_list.md)|List and filter on StackScripts.|
[linode.cloud.token_list](./docs/modules/token_list.md)|List and filter on Tokens.|
[linode.cloud.type_list](./docs/modules/type_list.md)|List and filter on Types.|
Expand Down
8 changes: 4 additions & 4 deletions docs/modules/ssh_key_info.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ssh_key_info

Get info about the Linode SSH public key.
Get info about a Linode SSH Key.

- [Minimum Required Fields](#minimum-required-fields)
- [Examples](#examples)
Expand Down Expand Up @@ -31,12 +31,12 @@ Get info about the Linode SSH public key.
| Field | Type | Required | Description |
|-----------|------|----------|------------------------------------------------------------------------------|
| `id` | <center>`int`</center> | <center>Optional</center> | The ID of the SSH key. **(Conflicts With: `label`)** |
| `label` | <center>`str`</center> | <center>Optional</center> | The label of the SSH key. **(Conflicts With: `id`)** |
| `label` | <center>`str`</center> | <center>Optional</center> | The label of the SSH Key to resolve. **(Conflicts With: `id`)** |
| `id` | <center>`int`</center> | <center>Optional</center> | The ID of the SSH Key to resolve. **(Conflicts With: `label`)** |

## Return Values

- `ssh_key` - The SSH key in JSON serialized form.
- `ssh_key` - The returned SSH Key.

- Sample Response:
```json
Expand Down
14 changes: 7 additions & 7 deletions docs/modules/ssh_key_list.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ssh_key_list

List and filter on SSH keys in the Linode profile.
List and filter on SSH Keys.

- [Minimum Required Fields](#minimum-required-fields)
- [Examples](#examples)
Expand Down Expand Up @@ -52,21 +52,21 @@ List and filter on SSH keys in the Linode profile.
| Field | Type | Required | Description |
|-----------|------|----------|------------------------------------------------------------------------------|
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list ssh keys in. **(Choices: `desc`, `asc`; Default: `asc`)** |
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order ssh keys by. |
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting ssh keys. |
| `count` | <center>`int`</center> | <center>Optional</center> | The number of results to return. If undefined, all results will be returned. |
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list SSH Keys in. **(Choices: `desc`, `asc`; Default: `asc`)** |
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order SSH Keys by. |
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting SSH Keys. |
| `count` | <center>`int`</center> | <center>Optional</center> | The number of SSH Keys to return. If undefined, all results will be returned. |

### filters

| Field | Type | Required | Description |
|-----------|------|----------|------------------------------------------------------------------------------|
| `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 |
| `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-ssh-keys). |
| `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. |

## Return Values

- `ssh_keys` - The returned SSH keys.
- `ssh_keys` - The returned SSH Keys.

- Sample Response:
```json
Expand Down
131 changes: 37 additions & 94 deletions plugins/modules/ssh_key_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,115 +5,58 @@

from __future__ import absolute_import, division, print_function

from typing import Any, Optional

import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.ssh_key_info as docs
from ansible_collections.linode.cloud.plugins.module_utils.linode_common import (
LinodeModuleBase,
)
from ansible_collections.linode.cloud.plugins.module_utils.linode_docs import (
global_authors,
global_requirements,
from ansible_collections.linode.cloud.plugins.module_utils.linode_common_info import (
InfoModule,
InfoModuleAttr,
InfoModuleResult,
)
from ansible_collections.linode.cloud.plugins.module_utils.linode_helper import (
filter_null_values,
)
from ansible_specdoc.objects import (
FieldType,
SpecDocMeta,
SpecField,
SpecReturnValue,
safe_find,
)
from ansible_specdoc.objects import FieldType
from linode_api4 import SSHKey

linode_ssh_key_info_spec = {
# Disable the default values
"state": SpecField(type=FieldType.string, required=False, doc_hide=True),
"id": SpecField(
type=FieldType.integer,
conflicts_with=["label"],
description=["The ID of the SSH key."],
module = InfoModule(
primary_result=InfoModuleResult(
field_name="ssh_key",
field_type=FieldType.dict,
display_name="SSH Key",
docs_url="https://techdocs.akamai.com/linode-api/reference/get-ssh-key",
samples=docs.ssh_key_info_response_sample,
),
"label": SpecField(
type=FieldType.string,
conflicts_with=["id"],
description=["The label of the SSH key."],
),
}

SPECDOC_META = SpecDocMeta(
description=["Get info about the Linode SSH public key."],
requirements=global_requirements,
author=global_authors,
options=linode_ssh_key_info_spec,
attributes=[
InfoModuleAttr(
display_name="ID",
name="id",
type=FieldType.integer,
get=lambda client, params: client.load(
SSHKey,
params.get("id"),
)._raw_json,
),
InfoModuleAttr(
display_name="label",
name="label",
type=FieldType.string,
get=lambda client, params: safe_find(
client.profile.ssh_keys,
SSHKey.label == params.get("label"),
raise_not_found=True,
)._raw_json,
),
],
examples=docs.specdoc_examples,
return_values={
"ssh_key": SpecReturnValue(
description="The SSH key in JSON serialized form.",
docs_url="https://techdocs.akamai.com/linode-api/reference/get-ssh-key",
type=FieldType.dict,
sample=docs.ssh_key_info_response_sample,
)
},
)

SPECDOC_META = module.spec

DOCUMENTATION = r"""
"""
EXAMPLES = r"""
"""
RETURN = r"""
"""


class LinodeSSHKeyInfo(LinodeModuleBase):
"""Module for getting Linode SSH public key"""

def __init__(self) -> None:
self.module_arg_spec = SPECDOC_META.ansible_spec
self.results = {"ssh_key": None}

super().__init__(
module_arg_spec=self.module_arg_spec,
required_one_of=[("id", "label")],
mutually_exclusive=[("id", "label")],
)

def _get_ssh_key_by_label(self, label: str) -> Optional[SSHKey]:
try:
ssh_keys = self.client.profile.ssh_keys(SSHKey.label == label)
if not ssh_keys:
return self.fail(
msg=f"failed to get ssh key with label {label}: "
"ssh key does not exist"
)
return ssh_keys[0] # maybe return whole list?
except Exception as exception:
return self.fail(msg=f"failed to get ssh key {label}: {exception}")

def _get_ssh_key_by_id(self, ssh_key_id: int) -> Optional[SSHKey]:
return self._get_resource_by_id(SSHKey, ssh_key_id)

def exec_module(self, **kwargs: Any) -> Optional[dict]:
"""Entrypoint for ssh_key_info module"""

params = filter_null_values(self.module.params)

ssh_key = None

if "id" in params:
ssh_key = self._get_ssh_key_by_id(params.get("id"))
elif "label" in params:
ssh_key = self._get_ssh_key_by_label(params.get("label"))

self.results["ssh_key"] = ssh_key._raw_json

return self.results


def main() -> None:
"""Constructs and calls the module"""
LinodeSSHKeyInfo()


if __name__ == "__main__":
main()
module.run()
125 changes: 11 additions & 114 deletions plugins/modules/ssh_key_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,131 +5,28 @@

from __future__ import absolute_import, division, print_function

from typing import Any, Dict, Optional

import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.ssh_key_list as docs
from ansible_collections.linode.cloud.plugins.module_utils.linode_common import (
LinodeModuleBase,
)
from ansible_collections.linode.cloud.plugins.module_utils.linode_docs import (
global_authors,
global_requirements,
)
from ansible_collections.linode.cloud.plugins.module_utils.linode_helper import (
construct_api_filter,
get_all_paginated,
from ansible_collections.linode.cloud.plugins.module_utils.linode_common_list import (
ListModule,
)
from ansible_specdoc.objects import (
FieldType,
SpecDocMeta,
SpecField,
SpecReturnValue,
)

spec_filter = {
"name": SpecField(
type=FieldType.string,
required=True,
description=[
"The name of the field to filter on.",
(
"Valid filterable attributes can be found here: "
"https://techdocs.akamai.com/linode-api/reference/get-profile"
),
],
),
"values": SpecField(
type=FieldType.list,
element_type=FieldType.string,
required=True,
description=[
"A list of values to allow for this field.",
"Fields will pass this filter if at least one of these values matches.",
],
),
}

spec = {
# Disable the default values
"state": SpecField(type=FieldType.string, required=False, doc_hide=True),
"label": SpecField(type=FieldType.string, required=False, doc_hide=True),
"order": SpecField(
type=FieldType.string,
description=["The order to list ssh keys in."],
default="asc",
choices=["desc", "asc"],
),
"order_by": SpecField(
type=FieldType.string,
description=["The attribute to order ssh keys by."],
),
"filters": SpecField(
type=FieldType.list,
element_type=FieldType.dict,
suboptions=spec_filter,
description=["A list of filters to apply to the resulting ssh keys."],
),
"count": SpecField(
type=FieldType.integer,
description=[
"The number of results to return.",
"If undefined, all results will be returned.",
],
),
}

SPECDOC_META = SpecDocMeta(
description=["List and filter on SSH keys in the Linode profile."],
requirements=global_requirements,
author=global_authors,
options=spec,
module = ListModule(
result_display_name="SSH Keys",
result_field_name="ssh_keys",
endpoint_template="/profile/sshkeys",
result_docs_url="https://techdocs.akamai.com/linode-api/reference/get-ssh-keys",
examples=docs.ssh_key_list_specdoc_examples,
return_values={
"ssh_keys": SpecReturnValue(
description="The returned SSH keys.",
docs_url="https://techdocs.akamai.com/linode-api/reference/get-ssh-keys",
type=FieldType.list,
elements=FieldType.dict,
sample=docs.result_ssh_key_list_samples,
)
},
result_samples=docs.result_ssh_key_list_samples,
)

SPECDOC_META = module.spec

DOCUMENTATION = r"""
"""
EXAMPLES = r"""
"""
RETURN = r"""
"""


class SSHKeyListModule(LinodeModuleBase):
"""Module for getting a list of SSH keys in the Linode profile"""

def __init__(self) -> None:
self.module_arg_spec = SPECDOC_META.ansible_spec
self.results: Dict[str, Any] = {"ssh_keys": []}

super().__init__(module_arg_spec=self.module_arg_spec)

def exec_module(self, **kwargs: Any) -> Optional[dict]:
"""Entrypoint for SSH key list module"""

filter_dict = construct_api_filter(self.module.params)

self.results["ssh_keys"] = get_all_paginated(
self.client,
"/profile/sshkeys",
filter_dict,
num_results=self.module.params["count"],
)
return self.results


def main() -> None:
"""Constructs and calls the module"""
SSHKeyListModule()


if __name__ == "__main__":
main()
module.run()

0 comments on commit abd4b35

Please sign in to comment.