chaostoolkit-aws


Namechaostoolkit-aws JSON
Version 0.35.1 PyPI version JSON
download
home_pageNone
SummaryAWS extension for the Chaos Toolkit
upload_time2024-06-15 20:51:26
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <h2 align="center">
  <br>
  <p align="center"><img src="https://avatars.githubusercontent.com/u/32068152?s=200&v=4"></p>
</h2>

<h4 align="center">AWS extension for the Chaos Toolkit</h4>

<p align="center">
   <a href="https://pypi.org/project/chaostoolkit-aws/">
   <img alt="Release" src="https://img.shields.io/pypi/v/chaostoolkit-aws.svg">
   <a href="#">
   <img alt="Build" src="https://github.com/chaostoolkit-incubator/chaostoolkit-aws/actions/workflows/build-and-test.yaml/badge.svg">
   <a href="https://github.com/chaostoolkit-incubator/chaostoolkit-aws/issues">
   <img alt="GitHub issues" src="https://img.shields.io/github/issues/chaostoolkit-incubator/chaostoolkit-aws?style=flat-square&logo=github&logoColor=white">
   <a href="https://github.com/chaostoolkit-incubator/chaostoolkit-aws/blob/master/LICENSE.md">
   <img alt="License" src="https://img.shields.io/github/license/chaostoolkit-incubator/chaostoolkit-aws">
   <a href="#">
   <img alt="Python version" src="https://img.shields.io/pypi/pyversions/chaostoolkit-aws.svg">
   <a href="https://pkg.go.dev/github.com/chaostoolkit-incubator/chaostoolkit-aws">
</p>

<p align="center">
  <a href="https://join.slack.com/t/chaostoolkit/shared_invite/zt-22c5isqi9-3YjYzucVTNFFVIG~Kzns8g">Community</a> •
  <a href="https://github.com/chaostoolkit-incubator/chaostoolkit-aws/blob/master/CHANGELOG.md">ChangeLog</a>
</p>

---

Welcome to the Amazon Web Services (AWS) extension for Chaos Toolkit. The
package aggregates activities to target your AWS infrastructure and explore
your resilience via Chaos Engineering experiments.

## Install

This package requires Python 3.8+

To be used from your experiment, this package must be installed in the Python
environment where [chaostoolkit][] already lives.

```
$ pip install -U chaostoolkit-aws
```

## Usage

To use the probes and actions from this package, add the following to your
experiment file:

```json
{
    "name": "stop-an-ec2-instance",
    "provider": {
        "type": "python",
        "module": "chaosaws.ec2.actions",
        "func": "stop_instance",
        "arguments": {
            "instance_id": "i-123456"
        }
    }
},
{
    "name": "create-a-new-policy",
    "provider": {
        "type": "python",
        "module": "chaosaws.iam.actions",
        "func": "create_policy",
        "arguments": {
            "name": "mypolicy",
            "path": "user/Jane",
            "policy": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": [
                            "s3:ListAllMyBuckets",
                            "s3:GetBucketLocation"
                        ],
                        "Resource": "arn:aws:s3:::*"
                    }
                ]
            }
        }
    }
}
```

Or select one at random from an AZ:


```json
{
    "name": "stop-an-ec2-instance-in-az-at-random",
    "provider": {
        "type": "python",
        "module": "chaosaws.ec2.actions",
        "func": "stop_instance",
        "arguments": {
            "az": "us-west-1"
        }
    }
}
```

That's it!

Please explore the code to see existing probes and actions.

## Configuration

### Credentials

This extension uses the [boto3][] library under the hood. This library expects
that you have properly [configured][creds] your environment to connect and
authenticate with the AWS services.

[boto3]: https://boto3.readthedocs.io
[creds]: https://boto3.readthedocs.io/en/latest/guide/configuration.html

#### Use default profile from `~/.aws/credentials` or `~/.aws/config`

This is the most basic case, assuming your `default` profile is properly
[configured][default] in `~/.aws/credentials` (or `~/.aws/config`),
then you do not need to pass any specific credentials to the experiment.

[default]: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html#shared-credentials-file

#### Use a non-default profile from `~/.aws/credentials` or `~/.aws/config`

Assuming you have configure a profile in your `~/.aws/credentials`
(or `~/.aws/config`) file, you may declare it in your experiment as follows:

```json
{
    "configuration": {
        "aws_profile_name": "dev"
    }
}
```

Your `~/.aws/credentials` should look like this:

```
[dev]
aws_access_key_id = XYZ
aws_secret_access_key = UIOPIY
```

Or, your `~/.aws/config` should look like this:

```
[profile dev]
output = json
aws_access_key_id = XYZ
aws_secret_access_key = UIOPIY
```

#### Assume an ARN role from a non-default profile

Assuming you have configure a profile in your `~/.aws/config` file with
a specific [ARN role][role] you want to assume during the run:

[role]: https://boto3.readthedocs.io/en/latest/guide/configuration.html#aws-config-file

```json
{
    "configuration": {
        "aws_profile_name": "dev"
    }
}
```

Your `~/.aws/config` should look like this:

```
[default]
output = json

[profile dev]
role_arn = arn:aws:iam::XXXXXXX:role/role-name
source_profile = default
```

#### Assume an ARN role from within the experiment

You mays also assume a role by declaring the role ARN in the experiment
directly. In that case, the profile has no impact if you also set it.

```json
    "configuration": {
        "aws_assume_role_arn": "arn:aws:iam::XXXXXXX:role/role-name",
        "aws_assume_role_session_name": "my-chaos"
    }
```

The `aws_assume_role_session_name` key is optional and will be set to
`"ChaosToolkit"` when not provided.

When this approach is used, the extension performs a [assume role][assumerole]
call against the [AWS STS][sts] service to fetch credentials dynamically.

[assumerole]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.assume_role
[sts]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html

#### Pass credentials explicitely

You can pass the credentials as a secret to the experiment definition as
follows:

```json
{
    "secrets": {
        "aws": {
            "aws_access_key_id": "your key",
            "aws_secret_access_key": "access key",
            "aws_session_token": "token",
        }
    }
}
```
Note that the token is optional.

Then, use it as follows:

```json
{
    "name": "stop-an-ec2-instance",
    "provider": {
        "type": "python",
        "module": "chaosaws.ec2.actions",
        "func": "stop_instance",
        "secrets": ["aws"],
        "arguments": {
            "instance_id": "i-123456"
        }
    }
}
```

[sources]: https://boto3.readthedocs.io/en/latest/guide/configuration.html#configuring-credentials

### Setting the region

In additon to the authentication credentials, you must configure the region
against which you want to use.

You can either declare it at the top level of the experiment, add:

```json
{
    "configuration": {
        "aws_region": "us-east-1"
    }
}
```

or

```json
{
    "configuration": {
        "aws_region": {
            "type": "env",
            "key": "AWS_REGION"
        }
    }
}
```

But you can also simply set either `AWS_REGION` or `AWS_DEFAULT_REGION` in
your terminal session without declaring anything in the experiment.

If none of these are set, your experiment will likely fail.

## Contribute

If you wish to contribute more functions to this package, you are more than
welcome to do so. Please, fork this project, write unit tests to cover the proposed changes,
implement the changes, ensure they meet the formatting standards by running
`pdm run format` and `pdm run lint`.

The Chaos Toolkit projects require all contributors must sign a
[Developer Certificate of Origin][dco] on each commit they would like to merge
into the master branch of the repository. Please, make sure you can abide by
the rules of the DCO before submitting a PR.

[dco]: https://github.com/probot/dco#how-it-works

### Develop

If you wish to develop on this project, make sure to install the development
dependencies. First installk [PDM](https://pdm-project.org/latest/).

```console
$ pdm install --dev
```

Now, you can edit the files and they will be automatically be seen by your
environment, even when running from the `chaos` command locally.

### Tests

To run the tests for the project execute the following:

```console
$ pdm run test
```

### Formatting and Linting

We use [ruff][ruff] to lint and format the code.

[ruff]: https://github.com/astral-sh/ruff

Before raising a Pull Request, we recommend you run formatting against your code with:

```console
$ pdm run format
```

This will automatically format any code that doesn't adhere to the formatting standards.

As some things are not picked up by the formatting, we also recommend you run:

```console
$ pdm run lint
```

To ensure that any unused import statements/strings that are too long, etc. are also picked up.

### Add new AWS API Support

Once you have setup your environment, you can start adding new
[AWS API support][awsapi] by adding new actions, probes and entire sub-packages
for those.

[awsapi]: https://boto3.readthedocs.io/en/latest/reference/services/index.html

#### Services supported by boto

This package relies on [boto3][] to wrap the API calls into a fluent Python
API. Some newer AWS services are not yet available in boto3, in that case,
you should read the next section.

[boto3]: https://boto3.readthedocs.io/en/latest/reference/services/index.html

Let's say you want to support a new action in the EC2 sub-package.

Start by creating a new function in `ec2/actions.py`:

```python
from chaoslib.types import Configuration, Secrets

from chaosaws import aws_client
from chaosaws.types import AWSResponse

def reboot_instance(instance_id: str, dry_run: bool=False,
                    configuration: Configuration=None,
                    secrets: Secrets=None) -> AWSResponse:
    """
    Reboot a given EC2 instance.
    """
    client = aws_client('ec2', configuration, secrets)
    return client.reboot_instances(InstanceIds=[instance_id], DryRun=dry_run)
```

As you can see, the actual code is straightforward. You first create a
[EC2 client][ec2client] and simply call the appropriate method on that client
with the expected arguments. We return the action as-is so that it can be
logged by the chaostoolkit, or even be used as part of a steady-state
hypothesis probe (if this was a probe, not action that is).

You could decide to make more than one AWS API call but, it is better to keep
it simple so that composition is easier from the experiment. Nonetheless,
you may also compose those directly into a single action as well for specific
use-cases.

Please refer to the Chaos Toolkit documentation to learn more about the
[configuration][] and [secrets][] objects.

[ec2client]: https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#client
[configuration]: http://chaostoolkit.org/reference/api/experiment/#configuration
[secrets]: http://chaostoolkit.org/reference/api/experiment/#secrets

Once you have implemented that action, you must create at least one unit test
for it in the `tests/ec2/test_ec2_actions.py` test module. For example:

```python
from chaosaws.ec2.actions import reboot_instancex

@patch('chaosaws.ec2.actions.aws_client', autospec=True)
def test_reboot_instance(aws_client):
    client = MagicMock()
    aws_client.return_value = client
    inst_id = "i-1234567890abcdef0"
    response = reboot_instance(inst_id)
    client.reboot_instances.assert_called_with(
        InstanceIds=[inst_id], DryRun=False)
```

By using the [built-in Python module to mock objects][pymock], we can mock the
EC2 client and assert that we do indeed call the appropriate method with the right
arguments. You are encouraged to write more than a single test for various
conditions.

[pymock]: https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock

Finally, should you choose to add support for a new AWS API resource altogether,
you should create the according sub-package.

#### Services not supported by boto (new AWS features)

If the support you want to provide is for a new AWS service that [boto][] does
not support yet, this requires direct call to the API endpoint via the
[requests][] package. Say we have a new service, not yet supported by boto3

[eks]: https://aws.amazon.com/eks/
[boto]: https://boto3.readthedocs.io/en/latest/index.html
[requests]: http://docs.python-requests.org/en/master/

```python
from chaoslib.types import Configuration, Secrets

from chaosaws import signed_api_call
from chaosaws.types import AWSResponse

def terminate_worker_node(worker_node_id: str,
                          configuration: Configuration=None,
                          secrets: Secrets=None) -> AWSResponse:
    """
    Terminate a worker node.
    """
    params = {
        "DryRun": True,
        "WorkerNodeId.1": worker_node_id
    }
    response = signed_api_call(
        'some-new-service-name', path='/2018-01-01/worker/terminate',
        method='POST', params=params,
        configuration=configuration, secrets=secrets)
    return response.json()
```

Here is an example on existing API call (as a more concrete snippet):

```python
from chaoslib.types import Configuration, Secrets

from chaosaws import signed_api_call

def stop_instance(instance_id: str, configuration: Configuration=None,
                  secrets: Secrets=None) -> str:
    response = signed_api_call(
        'ec2',
        configuration=configuration,
        secrets=secrets,
        params={
            "Action": "StopInstances",
            "InstanceId.1": instance_id,
            "Version": "2013-06-15"
        }
    )

    # this API returns XML, not JSON
    return response.text
```

When using the `signed_api_call`, you are responsible for the right way of
passing the parameters. Basically, look at the AWS documentation for each
API call.

**WARNING:** It should be noted that, whenever boto3 implements an API, this
package should be updated accordingly, as boto3 is much more versatile and
solid.

#### Make your new sub-package discoverable

Finally, if you have created a new sub-package entirely, you need to make its
capability discoverable by the chaos toolkit. Simply amend the `discover`
function in the `chaosaws/__init__.py`. For example, assuming a new `eks`
sub-package, with actions and probes:

```python
    activities.extend(discover_actions("chaosaws.eks.actions"))
    activities.extend(discover_probes("chaosaws.eks.probes"))
```


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "chaostoolkit-aws",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "Chaos Toolkit <contact@chaostoolkit.org>, Sylvain Hellegouarch <sh@defuze.org>",
    "download_url": "https://files.pythonhosted.org/packages/d5/4c/33848158679b58e6de1b79739832ce313144d81442751282d239bf705d07/chaostoolkit_aws-0.35.1.tar.gz",
    "platform": null,
    "description": "<h2 align=\"center\">\n  <br>\n  <p align=\"center\"><img src=\"https://avatars.githubusercontent.com/u/32068152?s=200&v=4\"></p>\n</h2>\n\n<h4 align=\"center\">AWS extension for the Chaos Toolkit</h4>\n\n<p align=\"center\">\n   <a href=\"https://pypi.org/project/chaostoolkit-aws/\">\n   <img alt=\"Release\" src=\"https://img.shields.io/pypi/v/chaostoolkit-aws.svg\">\n   <a href=\"#\">\n   <img alt=\"Build\" src=\"https://github.com/chaostoolkit-incubator/chaostoolkit-aws/actions/workflows/build-and-test.yaml/badge.svg\">\n   <a href=\"https://github.com/chaostoolkit-incubator/chaostoolkit-aws/issues\">\n   <img alt=\"GitHub issues\" src=\"https://img.shields.io/github/issues/chaostoolkit-incubator/chaostoolkit-aws?style=flat-square&logo=github&logoColor=white\">\n   <a href=\"https://github.com/chaostoolkit-incubator/chaostoolkit-aws/blob/master/LICENSE.md\">\n   <img alt=\"License\" src=\"https://img.shields.io/github/license/chaostoolkit-incubator/chaostoolkit-aws\">\n   <a href=\"#\">\n   <img alt=\"Python version\" src=\"https://img.shields.io/pypi/pyversions/chaostoolkit-aws.svg\">\n   <a href=\"https://pkg.go.dev/github.com/chaostoolkit-incubator/chaostoolkit-aws\">\n</p>\n\n<p align=\"center\">\n  <a href=\"https://join.slack.com/t/chaostoolkit/shared_invite/zt-22c5isqi9-3YjYzucVTNFFVIG~Kzns8g\">Community</a> \u2022\n  <a href=\"https://github.com/chaostoolkit-incubator/chaostoolkit-aws/blob/master/CHANGELOG.md\">ChangeLog</a>\n</p>\n\n---\n\nWelcome to the Amazon Web Services (AWS) extension for Chaos Toolkit. The\npackage aggregates activities to target your AWS infrastructure and explore\nyour resilience via Chaos Engineering experiments.\n\n## Install\n\nThis package requires Python 3.8+\n\nTo be used from your experiment, this package must be installed in the Python\nenvironment where [chaostoolkit][] already lives.\n\n```\n$ pip install -U chaostoolkit-aws\n```\n\n## Usage\n\nTo use the probes and actions from this package, add the following to your\nexperiment file:\n\n```json\n{\n    \"name\": \"stop-an-ec2-instance\",\n    \"provider\": {\n        \"type\": \"python\",\n        \"module\": \"chaosaws.ec2.actions\",\n        \"func\": \"stop_instance\",\n        \"arguments\": {\n            \"instance_id\": \"i-123456\"\n        }\n    }\n},\n{\n    \"name\": \"create-a-new-policy\",\n    \"provider\": {\n        \"type\": \"python\",\n        \"module\": \"chaosaws.iam.actions\",\n        \"func\": \"create_policy\",\n        \"arguments\": {\n            \"name\": \"mypolicy\",\n            \"path\": \"user/Jane\",\n            \"policy\": {\n                \"Version\": \"2012-10-17\",\n                \"Statement\": [\n                    {\n                        \"Effect\": \"Allow\",\n                        \"Action\": [\n                            \"s3:ListAllMyBuckets\",\n                            \"s3:GetBucketLocation\"\n                        ],\n                        \"Resource\": \"arn:aws:s3:::*\"\n                    }\n                ]\n            }\n        }\n    }\n}\n```\n\nOr select one at random from an AZ:\n\n\n```json\n{\n    \"name\": \"stop-an-ec2-instance-in-az-at-random\",\n    \"provider\": {\n        \"type\": \"python\",\n        \"module\": \"chaosaws.ec2.actions\",\n        \"func\": \"stop_instance\",\n        \"arguments\": {\n            \"az\": \"us-west-1\"\n        }\n    }\n}\n```\n\nThat's it!\n\nPlease explore the code to see existing probes and actions.\n\n## Configuration\n\n### Credentials\n\nThis extension uses the [boto3][] library under the hood. This library expects\nthat you have properly [configured][creds] your environment to connect and\nauthenticate with the AWS services.\n\n[boto3]: https://boto3.readthedocs.io\n[creds]: https://boto3.readthedocs.io/en/latest/guide/configuration.html\n\n#### Use default profile from `~/.aws/credentials` or `~/.aws/config`\n\nThis is the most basic case, assuming your `default` profile is properly\n[configured][default] in `~/.aws/credentials` (or `~/.aws/config`),\nthen you do not need to pass any specific credentials to the experiment.\n\n[default]: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html#shared-credentials-file\n\n#### Use a non-default profile from `~/.aws/credentials` or `~/.aws/config`\n\nAssuming you have configure a profile in your `~/.aws/credentials`\n(or `~/.aws/config`) file, you may declare it in your experiment as follows:\n\n```json\n{\n    \"configuration\": {\n        \"aws_profile_name\": \"dev\"\n    }\n}\n```\n\nYour `~/.aws/credentials` should look like this:\n\n```\n[dev]\naws_access_key_id = XYZ\naws_secret_access_key = UIOPIY\n```\n\nOr, your `~/.aws/config` should look like this:\n\n```\n[profile dev]\noutput = json\naws_access_key_id = XYZ\naws_secret_access_key = UIOPIY\n```\n\n#### Assume an ARN role from a non-default profile\n\nAssuming you have configure a profile in your `~/.aws/config` file with\na specific [ARN role][role] you want to assume during the run:\n\n[role]: https://boto3.readthedocs.io/en/latest/guide/configuration.html#aws-config-file\n\n```json\n{\n    \"configuration\": {\n        \"aws_profile_name\": \"dev\"\n    }\n}\n```\n\nYour `~/.aws/config` should look like this:\n\n```\n[default]\noutput = json\n\n[profile dev]\nrole_arn = arn:aws:iam::XXXXXXX:role/role-name\nsource_profile = default\n```\n\n#### Assume an ARN role from within the experiment\n\nYou mays also assume a role by declaring the role ARN in the experiment\ndirectly. In that case, the profile has no impact if you also set it.\n\n```json\n    \"configuration\": {\n        \"aws_assume_role_arn\": \"arn:aws:iam::XXXXXXX:role/role-name\",\n        \"aws_assume_role_session_name\": \"my-chaos\"\n    }\n```\n\nThe `aws_assume_role_session_name` key is optional and will be set to\n`\"ChaosToolkit\"` when not provided.\n\nWhen this approach is used, the extension performs a [assume role][assumerole]\ncall against the [AWS STS][sts] service to fetch credentials dynamically.\n\n[assumerole]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.assume_role\n[sts]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html\n\n#### Pass credentials explicitely\n\nYou can pass the credentials as a secret to the experiment definition as\nfollows:\n\n```json\n{\n    \"secrets\": {\n        \"aws\": {\n            \"aws_access_key_id\": \"your key\",\n            \"aws_secret_access_key\": \"access key\",\n            \"aws_session_token\": \"token\",\n        }\n    }\n}\n```\nNote that the token is optional.\n\nThen, use it as follows:\n\n```json\n{\n    \"name\": \"stop-an-ec2-instance\",\n    \"provider\": {\n        \"type\": \"python\",\n        \"module\": \"chaosaws.ec2.actions\",\n        \"func\": \"stop_instance\",\n        \"secrets\": [\"aws\"],\n        \"arguments\": {\n            \"instance_id\": \"i-123456\"\n        }\n    }\n}\n```\n\n[sources]: https://boto3.readthedocs.io/en/latest/guide/configuration.html#configuring-credentials\n\n### Setting the region\n\nIn additon to the authentication credentials, you must configure the region\nagainst which you want to use.\n\nYou can either declare it at the top level of the experiment, add:\n\n```json\n{\n    \"configuration\": {\n        \"aws_region\": \"us-east-1\"\n    }\n}\n```\n\nor\n\n```json\n{\n    \"configuration\": {\n        \"aws_region\": {\n            \"type\": \"env\",\n            \"key\": \"AWS_REGION\"\n        }\n    }\n}\n```\n\nBut you can also simply set either `AWS_REGION` or `AWS_DEFAULT_REGION` in\nyour terminal session without declaring anything in the experiment.\n\nIf none of these are set, your experiment will likely fail.\n\n## Contribute\n\nIf you wish to contribute more functions to this package, you are more than\nwelcome to do so. Please, fork this project, write unit tests to cover the proposed changes,\nimplement the changes, ensure they meet the formatting standards by running\n`pdm run format` and `pdm run lint`.\n\nThe Chaos Toolkit projects require all contributors must sign a\n[Developer Certificate of Origin][dco] on each commit they would like to merge\ninto the master branch of the repository. Please, make sure you can abide by\nthe rules of the DCO before submitting a PR.\n\n[dco]: https://github.com/probot/dco#how-it-works\n\n### Develop\n\nIf you wish to develop on this project, make sure to install the development\ndependencies. First installk [PDM](https://pdm-project.org/latest/).\n\n```console\n$ pdm install --dev\n```\n\nNow, you can edit the files and they will be automatically be seen by your\nenvironment, even when running from the `chaos` command locally.\n\n### Tests\n\nTo run the tests for the project execute the following:\n\n```console\n$ pdm run test\n```\n\n### Formatting and Linting\n\nWe use [ruff][ruff] to lint and format the code.\n\n[ruff]: https://github.com/astral-sh/ruff\n\nBefore raising a Pull Request, we recommend you run formatting against your code with:\n\n```console\n$ pdm run format\n```\n\nThis will automatically format any code that doesn't adhere to the formatting standards.\n\nAs some things are not picked up by the formatting, we also recommend you run:\n\n```console\n$ pdm run lint\n```\n\nTo ensure that any unused import statements/strings that are too long, etc. are also picked up.\n\n### Add new AWS API Support\n\nOnce you have setup your environment, you can start adding new\n[AWS API support][awsapi] by adding new actions, probes and entire sub-packages\nfor those.\n\n[awsapi]: https://boto3.readthedocs.io/en/latest/reference/services/index.html\n\n#### Services supported by boto\n\nThis package relies on [boto3][] to wrap the API calls into a fluent Python\nAPI. Some newer AWS services are not yet available in boto3, in that case,\nyou should read the next section.\n\n[boto3]: https://boto3.readthedocs.io/en/latest/reference/services/index.html\n\nLet's say you want to support a new action in the EC2 sub-package.\n\nStart by creating a new function in `ec2/actions.py`:\n\n```python\nfrom chaoslib.types import Configuration, Secrets\n\nfrom chaosaws import aws_client\nfrom chaosaws.types import AWSResponse\n\ndef reboot_instance(instance_id: str, dry_run: bool=False,\n                    configuration: Configuration=None,\n                    secrets: Secrets=None) -> AWSResponse:\n    \"\"\"\n    Reboot a given EC2 instance.\n    \"\"\"\n    client = aws_client('ec2', configuration, secrets)\n    return client.reboot_instances(InstanceIds=[instance_id], DryRun=dry_run)\n```\n\nAs you can see, the actual code is straightforward. You first create a\n[EC2 client][ec2client] and simply call the appropriate method on that client\nwith the expected arguments. We return the action as-is so that it can be\nlogged by the chaostoolkit, or even be used as part of a steady-state\nhypothesis probe (if this was a probe, not action that is).\n\nYou could decide to make more than one AWS API call but, it is better to keep\nit simple so that composition is easier from the experiment. Nonetheless,\nyou may also compose those directly into a single action as well for specific\nuse-cases.\n\nPlease refer to the Chaos Toolkit documentation to learn more about the\n[configuration][] and [secrets][] objects.\n\n[ec2client]: https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#client\n[configuration]: http://chaostoolkit.org/reference/api/experiment/#configuration\n[secrets]: http://chaostoolkit.org/reference/api/experiment/#secrets\n\nOnce you have implemented that action, you must create at least one unit test\nfor it in the `tests/ec2/test_ec2_actions.py` test module. For example:\n\n```python\nfrom chaosaws.ec2.actions import reboot_instancex\n\n@patch('chaosaws.ec2.actions.aws_client', autospec=True)\ndef test_reboot_instance(aws_client):\n    client = MagicMock()\n    aws_client.return_value = client\n    inst_id = \"i-1234567890abcdef0\"\n    response = reboot_instance(inst_id)\n    client.reboot_instances.assert_called_with(\n        InstanceIds=[inst_id], DryRun=False)\n```\n\nBy using the [built-in Python module to mock objects][pymock], we can mock the\nEC2 client and assert that we do indeed call the appropriate method with the right\narguments. You are encouraged to write more than a single test for various\nconditions.\n\n[pymock]: https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock\n\nFinally, should you choose to add support for a new AWS API resource altogether,\nyou should create the according sub-package.\n\n#### Services not supported by boto (new AWS features)\n\nIf the support you want to provide is for a new AWS service that [boto][] does\nnot support yet, this requires direct call to the API endpoint via the\n[requests][] package. Say we have a new service, not yet supported by boto3\n\n[eks]: https://aws.amazon.com/eks/\n[boto]: https://boto3.readthedocs.io/en/latest/index.html\n[requests]: http://docs.python-requests.org/en/master/\n\n```python\nfrom chaoslib.types import Configuration, Secrets\n\nfrom chaosaws import signed_api_call\nfrom chaosaws.types import AWSResponse\n\ndef terminate_worker_node(worker_node_id: str,\n                          configuration: Configuration=None,\n                          secrets: Secrets=None) -> AWSResponse:\n    \"\"\"\n    Terminate a worker node.\n    \"\"\"\n    params = {\n        \"DryRun\": True,\n        \"WorkerNodeId.1\": worker_node_id\n    }\n    response = signed_api_call(\n        'some-new-service-name', path='/2018-01-01/worker/terminate',\n        method='POST', params=params,\n        configuration=configuration, secrets=secrets)\n    return response.json()\n```\n\nHere is an example on existing API call (as a more concrete snippet):\n\n```python\nfrom chaoslib.types import Configuration, Secrets\n\nfrom chaosaws import signed_api_call\n\ndef stop_instance(instance_id: str, configuration: Configuration=None,\n                  secrets: Secrets=None) -> str:\n    response = signed_api_call(\n        'ec2',\n        configuration=configuration,\n        secrets=secrets,\n        params={\n            \"Action\": \"StopInstances\",\n            \"InstanceId.1\": instance_id,\n            \"Version\": \"2013-06-15\"\n        }\n    )\n\n    # this API returns XML, not JSON\n    return response.text\n```\n\nWhen using the `signed_api_call`, you are responsible for the right way of\npassing the parameters. Basically, look at the AWS documentation for each\nAPI call.\n\n**WARNING:** It should be noted that, whenever boto3 implements an API, this\npackage should be updated accordingly, as boto3 is much more versatile and\nsolid.\n\n#### Make your new sub-package discoverable\n\nFinally, if you have created a new sub-package entirely, you need to make its\ncapability discoverable by the chaos toolkit. Simply amend the `discover`\nfunction in the `chaosaws/__init__.py`. For example, assuming a new `eks`\nsub-package, with actions and probes:\n\n```python\n    activities.extend(discover_actions(\"chaosaws.eks.actions\"))\n    activities.extend(discover_probes(\"chaosaws.eks.probes\"))\n```\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "AWS extension for the Chaos Toolkit",
    "version": "0.35.1",
    "project_urls": {
        "Changelog": "https://github.com/chaostoolkit-incubator/chaostoolkit-aws/blob/main/CHANGELOG.md",
        "Documentation": "https://chaostoolkit.org/drivers/aws/",
        "Homepage": "https://chaostoolkit.org/",
        "Repository": "https://github.com/chaostoolkit-incubator/chaostoolkit-aws"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d5acb7192da3d16afe2af18627c0a41b71644ebe192a0a1f7018108fcfac447d",
                "md5": "2b193af5e28af1a21773eae58bb52296",
                "sha256": "a43d8dfc6330a1b644a4e0017f470977ca424f979bb6e387a3472a76398c1852"
            },
            "downloads": -1,
            "filename": "chaostoolkit_aws-0.35.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2b193af5e28af1a21773eae58bb52296",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 79119,
            "upload_time": "2024-06-15T20:51:24",
            "upload_time_iso_8601": "2024-06-15T20:51:24.193672Z",
            "url": "https://files.pythonhosted.org/packages/d5/ac/b7192da3d16afe2af18627c0a41b71644ebe192a0a1f7018108fcfac447d/chaostoolkit_aws-0.35.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d54c33848158679b58e6de1b79739832ce313144d81442751282d239bf705d07",
                "md5": "d6f6973f9a4152fc4eda5e5e981d7590",
                "sha256": "462292c9a6bfa32dd29fc9c8cd4aa7e37d7bc7fe38c219f2345739957df24ee2"
            },
            "downloads": -1,
            "filename": "chaostoolkit_aws-0.35.1.tar.gz",
            "has_sig": false,
            "md5_digest": "d6f6973f9a4152fc4eda5e5e981d7590",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 94360,
            "upload_time": "2024-06-15T20:51:26",
            "upload_time_iso_8601": "2024-06-15T20:51:26.134537Z",
            "url": "https://files.pythonhosted.org/packages/d5/4c/33848158679b58e6de1b79739832ce313144d81442751282d239bf705d07/chaostoolkit_aws-0.35.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-15 20:51:26",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "chaostoolkit-incubator",
    "github_project": "chaostoolkit-aws",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "chaostoolkit-aws"
}
        
Elapsed time: 0.48106s