Skip to content

Commit

Permalink
Retrieve files from cephadm-ansible project
Browse files Browse the repository at this point in the history
Signed-off-by: Teoman ONAY <[email protected]>
  • Loading branch information
asm0deuz committed Jun 25, 2024
1 parent 29437e0 commit 0382b0f
Show file tree
Hide file tree
Showing 23 changed files with 2,068 additions and 48 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
name: Release ceph.ansible
name: Release ceph.automation

on: # yamllint disable-line rule:truthy
release:
Expand Down
2 changes: 1 addition & 1 deletion .isort.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[settings]
known_first_party=ansible_collections.ceph.ansible
known_first_party=ansible_collections.ceph.automation
line_length=100
lines_after_imports=2
lines_between_types=1
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Ceph Ansible Collection
# Ceph Automation Collection

This repository contains the `ceph.ansible` Ansible Collection.
This repository contains the `ceph.automation` Ansible Collection.

## Tested with Ansible

Expand All @@ -17,26 +17,26 @@ Please check the included content on the [Ansible Galaxy page for this collectio
## Using this collection

```
ansible-galaxy collection install ceph.ansible
ansible-galaxy collection install ceph.automation
```

You can also include it in a `requirements.yml` file and install it via `ansible-galaxy collection install -r requirements.yml` using the format:

```yaml
collections:
- name: ceph.ansible
- name: ceph.automation
```
To upgrade the collection to the latest available version, run the following command:
```bash
ansible-galaxy collection install ceph.ansible --upgrade
ansible-galaxy collection install ceph.automation --upgrade
```

You can also install a specific version of the collection, for example, if you need to downgrade when something is broken in the latest version (please report an issue in this repository). Use the following syntax where `X.Y.Z` can be any [available version](https://galaxy.ansible.com/ceph/ansible):

```bash
ansible-galaxy collection install ceph.ansible:==X.Y.Z
ansible-galaxy collection install ceph.automation:==X.Y.Z
```

See [Ansible Using collections](https://docs.ansible.com/ansible/latest/user_guide/collections_using.html) for more details.
Expand Down
2 changes: 1 addition & 1 deletion changelogs/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ sections:
- Known Issues
- - doc_changes
- Documentation Changes
title: "Ceph Ansible Collection"
title: "Ceph Automation Collection"
trivial_section_name: trivial
4 changes: 2 additions & 2 deletions docs/docsite/links.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# want this functionality for your collection.
edit_on_github:
# TO-DO: Update this if your collection lives in a different GitHub organization.
repository: ansible-collections/ceph.ansible
repository: ansible-collections/ceph.automation
branch: main
# If your collection root (the directory containing galaxy.yml) does not coincide with your
# repository's root, you have to specify the path to the collection root here. For example,
Expand All @@ -27,7 +27,7 @@ edit_on_github:
extra_links:
- description: Report an issue
# TO-DO: Update this if your collection lives in a different GitHub organization.
url: https://github.com/ansible-collections/ceph.ansible/issues/new/choose
url: https://github.com/ansible-collections/ceph.automation/issues/new/choose

# Specify communication channels for your collection. We suggest to not specify more
# than one place for communication per communication tool to avoid confusion.
Expand Down
6 changes: 3 additions & 3 deletions galaxy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
# See https://docs.ansible.com/ansible/latest/dev_guide/collections_galaxy_meta.html

namespace: "ceph"
name: "ansible"
name: "automation"
version: 1.0.0
readme: README.md
authors:
- your name <example@domain.com>
- Teoman ONAY <tonay@ibm.com>

description: your collection description
description: Ceph automation modules
license_file: LICENSE
# TO-DO: update the tags based on your content type
tags: ["linux", "tools"]
Expand Down
19 changes: 0 additions & 19 deletions plugins/filter/hello_world.py

This file was deleted.

92 changes: 92 additions & 0 deletions plugins/module_utils/ceph_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import datetime
import time
from typing import TYPE_CHECKING, Any, List, Dict, Callable, Type, TypeVar

if TYPE_CHECKING:
from ansible.module_utils.basic import AnsibleModule # type: ignore

ExceptionType = TypeVar('ExceptionType', bound=BaseException)


def retry(exceptions: Type[ExceptionType], retries: int = 20, delay: int = 1) -> Callable:
def decorator(f: Callable) -> Callable:
def _retry(*args: Any, **kwargs: Any) -> Callable:
_tries = retries
while _tries > 1:
try:
print("{}".format(_tries))
return f(*args, **kwargs)
except exceptions:
time.sleep(delay)
_tries -= 1
print("{} has failed after {} tries".format(f, retries))
return f(*args, **kwargs)
return _retry
return decorator


def build_base_cmd(module: "AnsibleModule") -> List[str]:
cmd = ['cephadm']
docker = module.params.get('docker')
image = module.params.get('image')

if docker:
cmd.append('--docker')
if image:
cmd.extend(['--image', image])

return cmd


def build_base_cmd_shell(module: "AnsibleModule") -> List[str]:
cmd = build_base_cmd(module)
fsid = module.params.get('fsid')

cmd.append('shell')

if fsid:
cmd.extend(['--fsid', fsid])

return cmd


def build_base_cmd_orch(module: "AnsibleModule") -> List[str]:
cmd = build_base_cmd_shell(module)
cmd.extend(['ceph', 'orch'])

return cmd


def exit_module(module: "AnsibleModule",
rc: int, cmd: List[str],
startd: datetime.datetime,
out: str = '',
err: str = '',
changed: bool = False,
diff: Dict[str, str] = dict(before="", after="")) -> None:
endd = datetime.datetime.now()
delta = endd - startd

result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)


def fatal(message: str, module: "AnsibleModule") -> None:
'''
Report a fatal error and exit
'''

if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
175 changes: 175 additions & 0 deletions plugins/modules/ceph_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Copyright Red Hat
# SPDX-License-Identifier: Apache-2.0
# Author: Guillaume Abrioux <[email protected]>

from __future__ import absolute_import, division, print_function
from typing import Any, Dict, List, Tuple, Union
__metaclass__ = type

import datetime
import json

from ansible.module_utils.basic import AnsibleModule # type: ignore
try:
from ansible_collections.ceph.automation.plugins.module_utils.ceph_common import exit_module, build_base_cmd_shell, fatal # type: ignore
except ImportError:
from module_utils.ceph_common import exit_module, build_base_cmd_shell, fatal # type: ignore

ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: ceph_config
short_description: set ceph config
version_added: "2.10"
description:
- Set Ceph config options.
options:
fsid:
description:
- the fsid of the Ceph cluster to interact with.
required: false
image:
description:
- The Ceph container image to use.
required: false
action:
description:
- whether to get or set the parameter specified in 'option'
required: false
default: 'set'
who:
description:
- which daemon the configuration should be set to
required: true
option:
description:
- name of the parameter to be set
required: true
value:
description:
- value of the parameter
required: true if action is 'set'
author:
- Guillaume Abrioux <[email protected]>
'''

EXAMPLES = '''
- name: set osd_memory_target for osd.0
ceph_config:
action: set
who: osd.0
option: osd_memory_target
value: 5368709120
- name: set osd_memory_target for host ceph-osd-02
ceph_config:
action: set
who: osd/host:ceph-osd-02
option: osd_memory_target
value: 5368709120
- name: get osd_pool_default_size value
ceph_config:
action: get
who: global
option: osd_pool_default_size
value: 1
'''

RETURN = '''# '''


def set_option(module: "AnsibleModule",
who: str,
option: str,
value: str) -> Tuple[int, List[str], str, str]:
cmd = build_base_cmd_shell(module)
cmd.extend(['ceph', 'config', 'set', who, option, value])

rc, out, err = module.run_command(cmd)

return rc, cmd, out.strip(), err


def get_config_dump(module: "AnsibleModule") -> Tuple[int, List[str], str, str]:
cmd = build_base_cmd_shell(module)
cmd.extend(['ceph', 'config', 'dump', '--format', 'json'])
rc, out, err = module.run_command(cmd)
if rc:
fatal(message=f"Can't get current configuration via `ceph config dump`.Error:\n{err}", module=module)
out = out.strip()
return rc, cmd, out, err


def get_current_value(who: str, option: str, config_dump: List[Dict[str, Any]]) -> Union[str, None]:
for config in config_dump:
if config['section'] == who and config['name'] == option:
return config['value']
return None


def main() -> None:
module = AnsibleModule(
argument_spec=dict(
who=dict(type='str', required=True),
action=dict(type='str', required=False, choices=['get', 'set'], default='set'),
option=dict(type='str', required=True),
value=dict(type='str', required=False),
fsid=dict(type='str', required=False),
image=dict(type='str', required=False)
),
supports_check_mode=True,
required_if=[['action', 'set', ['value']]]
)

# Gather module parameters in variables
who = module.params.get('who')
option = module.params.get('option')
value = module.params.get('value')
action = module.params.get('action')

if module.check_mode:
module.exit_json(
changed=False,
stdout='',
cmd=[],
stderr='',
rc=0,
start='',
end='',
delta='',
)

startd = datetime.datetime.now()
changed = False

rc, cmd, out, err = get_config_dump(module)
config_dump = json.loads(out)
current_value = get_current_value(who, option, config_dump)

if action == 'set':
if value.lower() == current_value:
out = 'who={} option={} value={} already set. Skipping.'.format(who, option, value)
else:
rc, cmd, out, err = set_option(module, who, option, value)
changed = True
else:
if current_value is None:
out = ''
err = 'No value found for who={} option={}'.format(who, option)
else:
out = current_value

exit_module(module=module, out=out, rc=rc,
cmd=cmd, err=err, startd=startd,
changed=changed)


if __name__ == '__main__':
main()
Loading

0 comments on commit 0382b0f

Please sign in to comment.