Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add instance_type_list module #300

Merged
merged 7 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ Name | Description |
[linode.cloud.event_list](./docs/modules/event_list.md)|List and filter on Linode events.|
[linode.cloud.image_list](./docs/modules/image_list.md)|List and filter on Linode images.|
[linode.cloud.instance_list](./docs/modules/instance_list.md)|List and filter on Linode Instances.|
[linode.cloud.instance_type_list](./docs/modules/instance_type_list.md)|List and filter on Linode Instance Types.|
[linode.cloud.ssh_key_list](./docs/modules/ssh_key_list.md)|List and filter on SSH keys in the Linode profile.|
[linode.cloud.stackscript_list](./docs/modules/stackscript_list.md)|List and filter on Linode stackscripts.|
[linode.cloud.type_list](./docs/modules/type_list.md)|List and filter on Linode Instance Types.|
Expand Down
76 changes: 76 additions & 0 deletions docs/modules/instance_type_list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# instance_type_list

List and filter on Linode Instance Types.

- [Examples](#examples)
- [Parameters](#parameters)
- [Return Values](#return-values)

## Examples

```yaml
- name: List all of the Linode instance types
linode.cloud.instance_type_list: {}
```

```yaml
- name: Resolve all Linode instance types
linode.cloud.instance_type_list:
filter:
- name: class
values: nanode
```


## Parameters

| Field | Type | Required | Description |
|-----------|------|----------|------------------------------------------------------------------------------|
| `order` | <center>`str`</center> | <center>Optional</center> | The order to list instance types in. **(Choices: `desc`, `asc`; Default: `asc`)** |
| `order_by` | <center>`str`</center> | <center>Optional</center> | The attribute to order instance types by. |
| [`filters` (sub-options)](#filters) | <center>`list`</center> | <center>Optional</center> | A list of filters to apply to the resulting instance types. |
| `count` | <center>`int`</center> | <center>Optional</center> | The number of results 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: linode.com/docs/api/linode-types/#types-list__responses |
| `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

- `instance_types` - The returned instance types.

- Sample Response:
```json
[
{
"addons": {
"backups": {
"price": {
"hourly": 0.008,
"monthly": 5
}
}
},
"class": "standard",
"disk": 81920,
"gpus": 0,
"id": "g6-standard-2",
"label": "Linode 4GB",
"memory": 4096,
"network_out": 1000,
"price": {
"hourly": 0.03,
"monthly": 20
},
"successor": null,
"transfer": 4000,
"vcpus": 2
}
]
```
- See the [Linode API response documentation](https://www.linode.com/docs/api/linode-types/#types-list__response-samples) for a list of returned fields


37 changes: 37 additions & 0 deletions plugins/module_utils/doc_fragments/instance_type_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Documentation fragments for the instance_type_list module"""

specdoc_examples = ['''
- name: List all of the Linode instance types
linode.cloud.instance_type_list: {}''', '''
- name: Resolve all Linode instance types
linode.cloud.instance_type_list:
filter:
- name: class
values: nanode''']

result_instance_type_samples = ['''[
{
"addons": {
"backups": {
"price": {
"hourly": 0.008,
"monthly": 5
}
}
},
"class": "standard",
"disk": 81920,
"gpus": 0,
"id": "g6-standard-2",
"label": "Linode 4GB",
"memory": 4096,
"network_out": 1000,
"price": {
"hourly": 0.03,
"monthly": 20
},
"successor": null,
"transfer": 4000,
"vcpus": 2
}
]''']
99 changes: 99 additions & 0 deletions plugins/modules/instance_type_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""This module allows users to list Linode instance types."""
from __future__ import absolute_import, division, print_function

from typing import Any, Optional, Dict

from ansible_specdoc.objects import SpecDocMeta, SpecReturnValue, FieldType, SpecField

from ansible_collections.linode.cloud.plugins.module_utils.linode_common import LinodeModuleBase
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_docs import global_authors, \
global_requirements

import ansible_collections.linode.cloud.plugins.module_utils.doc_fragments.instance_type_list \
as docs

spec_filter = dict(
name=SpecField(type=FieldType.string, required=True,
description=[
'The name of the field to filter on.',
'Valid filterable attributes can be found here: '
'linode.com/docs/api/linode-types/'
'#types-list__responses',
]),
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 = dict(
# 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 instance types in.'],
default='asc', choices=['desc', 'asc']),
order_by=SpecField(type=FieldType.string,
description=['The attribute to order instance types by.']),
filters=SpecField(type=FieldType.list, element_type=FieldType.dict, suboptions=spec_filter,
description=['A list of filters to apply to the resulting instance types.']),
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 Linode Instance Types.'
],
requirements=global_requirements,
author=global_authors,
options=spec,
examples=docs.specdoc_examples,
return_values=dict(
instance_types=SpecReturnValue(
description='The returned instance types.',
docs_url='https://www.linode.com/docs/api/linode-types/'
'#types-list__response-samples',
type=FieldType.list,
elements=FieldType.dict,
sample=docs.result_instance_type_samples
)
)
)

class Module(LinodeModuleBase):
"""Module for getting a list of Linode instance types"""

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

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

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

filter_dict = construct_api_filter(self.module.params)

self.results['instance_types'] = get_all_paginated(self.client, '/linode/types',
filter_dict, num_results=self.module.params['count'])
return self.results

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


if __name__ == '__main__':
main()
25 changes: 25 additions & 0 deletions tests/integration/targets/instance_type_list/tasks/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
- name: instance_type_list
block:
- name: List instance types with no filter
linode.cloud.instance_type_list:
register: no_filter

- assert:
that:
- no_filter.instance_types | length >= 0

- name: List instance types with filter on class
linode.cloud.instance_type_list:
filters:
- name: class
values: nanode
register: filter

- assert:
that:
- filter.instance_types | length >= 0
- filter.instance_types[0].class == 'nanode'

environment:
LINODE_UA_PREFIX: '{{ ua_prefix }}'
LINODE_API_TOKEN: '{{ api_token }}'