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 a new SSM hook and use it in the System Test context builder #28755

Merged
merged 5 commits into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
53 changes: 53 additions & 0 deletions airflow/providers/amazon/aws/hooks/ssm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from __future__ import annotations

from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
from airflow.utils.types import NOTSET, ArgNotSet


class SsmHook(AwsBaseHook):
"""
Interact with Amazon Systems Manager (SSM) using the boto3 library.
All API calls available through the Boto API are also available here.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#client

Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.

.. seealso::
:class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""

def __init__(self, *args, **kwargs) -> None:
kwargs["client_type"] = "ssm"
super().__init__(*args, **kwargs)

def get_parameter_value(self, parameter: str, default: str | ArgNotSet = NOTSET) -> str:
"""
Returns the value of the provided Parameter or an optional default.

:param parameter: The SSM Parameter name to return the value for.
:param default: Optional default value to return if none is found.
"""
try:
return self.conn.get_parameter(Name=parameter)["Parameter"]["Value"]
except self.conn.exceptions.ParameterNotFound:
if isinstance(default, ArgNotSet):
raise
return default
7 changes: 7 additions & 0 deletions airflow/providers/amazon/provider.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ integrations:
how-to-guide:
- /docs/apache-airflow-providers-amazon/operators/s3.rst
tags: [aws]
- integration-name: Amazon Systems Manager (SSM)
external-doc-url: https://aws.amazon.com/systems-manager/
logo: /integration-logos/aws/AWS-Systems-Manager_light-bg@4x.png
tags: [aws]
- integration-name: Amazon Web Services
external-doc-url: https://aws.amazon.com/
logo: /integration-logos/aws/AWS-Cloud-alt_light-bg@4x.png
Expand Down Expand Up @@ -461,6 +465,9 @@ hooks:
- integration-name: Amazon Simple Email Service (SES)
python-modules:
- airflow.providers.amazon.aws.hooks.ses
- integration-name: Amazon Systems Manager (SSM)
python-modules:
- airflow.providers.amazon.aws.hooks.ssm
- integration-name: Amazon SecretsManager
python-modules:
- airflow.providers.amazon.aws.hooks.secrets_manager
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
67 changes: 67 additions & 0 deletions tests/providers/amazon/aws/hooks/test_ssm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from __future__ import annotations

import botocore.exceptions
import pytest
from moto import mock_ssm
from pytest import param

from airflow.providers.amazon.aws.hooks.ssm import SsmHook

DEFAULT_CONN_ID: str = "aws_default"
REGION: str = "us-east-1"

EXISTING_PARAM_NAME = "parameter"
BAD_PARAM_NAME = "parameter_does_not_exist"
PARAM_VALUE = "value"
DEFAULT_VALUE = "default"


@mock_ssm
class TestSsmHooks:
def setup(self):
self.hook = SsmHook(region_name=REGION)
self.hook.conn.put_parameter(Name=EXISTING_PARAM_NAME, Value=PARAM_VALUE, Overwrite=True)

def test_hook(self) -> None:
assert self.hook.conn is not None
assert self.hook.aws_conn_id == DEFAULT_CONN_ID
assert self.hook.region_name == REGION

@pytest.mark.parametrize(
"param_name, default_value, expected_result",
[
param(EXISTING_PARAM_NAME, None, PARAM_VALUE, id="param_exists_no_default_provided"),
param(EXISTING_PARAM_NAME, DEFAULT_VALUE, PARAM_VALUE, id="param_exists_with_default"),
param(BAD_PARAM_NAME, DEFAULT_VALUE, DEFAULT_VALUE, id="param_does_not_exist_uses_default"),
],
)
def test_get_parameter_value_happy_cases(self, param_name, default_value, expected_result) -> None:
if default_value:
assert self.hook.get_parameter_value(param_name, default=default_value) == expected_result
else:
assert self.hook.get_parameter_value(param_name) == expected_result

def test_get_parameter_value_param_does_not_exist_no_default_provided(self) -> None:
with pytest.raises(botocore.exceptions.ClientError) as raised_exception:
self.hook.get_parameter_value(BAD_PARAM_NAME)

error = raised_exception.value.response["Error"]
assert error["Code"] == "ParameterNotFound"
assert BAD_PARAM_NAME in error["Message"]
7 changes: 4 additions & 3 deletions tests/system/providers/amazon/aws/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from botocore.exceptions import ClientError, NoCredentialsError

from airflow.decorators import task
from airflow.providers.amazon.aws.hooks.ssm import SsmHook

ENV_ID_ENVIRON_KEY: str = "SYSTEM_TESTS_ENV_ID"
ENV_ID_KEY: str = "ENV_ID"
Expand Down Expand Up @@ -92,15 +93,15 @@ def _fetch_from_ssm(key: str, test_name: str | None = None) -> str:
:return: The value of the provided key from SSM
"""
_test_name: str = test_name if test_name else _get_test_name()
ssm_client: BaseClient = boto3.client("ssm")
hook = SsmHook()
Copy link
Contributor

@Taragolis Taragolis Jan 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @ferruzzi I guess the issues with tests here.
Due to the nature of AwsBaseHook by default it use aws_conn_id="aws_default" as result when you try to create SSM Client than hook obtain connection first.

@cached_property
def conn_config(self) -> AwsConnectionWrapper:
"""Get the Airflow Connection object and wrap it in helper (cached)."""
connection = None
if self.aws_conn_id:
try:
connection = self.get_connection(self.aws_conn_id)
except AirflowNotFoundException:
warnings.warn(
f"Unable to find AWS Connection ID '{self.aws_conn_id}', switching to empty. "
"This behaviour is deprecated and will be removed in a future releases. "
"Please provide existed AWS connection ID or if required boto3 credential strategy "
"explicit set AWS Connection ID to None.",
DeprecationWarning,
stacklevel=2,
)
return AwsConnectionWrapper(
conn=connection, region_name=self._region_name, botocore_config=self._config, verify=self._verify
)

I think if you set aws_conn_id to None it should not use Airflow Connection

Suggested change
hook = SsmHook()
hook = SsmHook(aws_conn_id=None)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had two solutions I was playing with and that was not one of them. I'll try that out, if it works it would be a much less intrusive fix than the one I decided to implement.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking this through, that would mean that the connection itself is not being tested. Is that something we want to accept in a system test?

I think it's alright in this case. The system tests are supposed to be testing the specific services, not whether the connection to SSM is working.... but that does mean it's a less-complete system test.

Copy link
Contributor

@Taragolis Taragolis Jan 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking this through, that would mean that the connection itself is not being tested.

We tests connections for AwsBaseHook and all other helpers. Actually there is 3 cases and all of them tested:

  1. aws_conn_id = None
  2. aws_conn_id = not-existed-conn, we know only after we tried connect to DB (one in the future we would remove this one)
  3. aws_conn_id = exists-conn

So we don't need test for all Hooks which based on AwsBaseHook and AwsGenericHook and how they obtain connection from Airflow.

The actual error happen in this test

@pytest.mark.parametrize("example", example_dags_except_db_exception(), ids=relative_path)
def test_should_not_do_database_queries(example):
with assert_queries_count(0):
DagBag(
dag_folder=example,
include_examples=False,
)

I'm not familiar with this test, but seems like it test that example DAGs do not perform queries to Airflow Database during import example dags: #7419

I don't know maybe this test less relevant nowadays

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was digging in that code yesterday and one option I worked on was adding AWS system tests as an exception and to assert that AWS tests make exactly one query, but I don't really know how important that restriction is. so I was trying to look into the restriction and why it's there. It looks like your change does fix the test (this PR is passing now) so maybe let's run with this.

@o-nikolas, can you have a look at this when you get a few minutes and let me know what you think? I think I'm inclined to agree with Taragolis that this is the right solution here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't love changing the "prod" code in this way to make the tests pass (I think the expectations in that unit test should be updated for AWS examples). But on the other hand the "prod" code here is technically also test code, so it's not so bad and it's a clean change 👍 Happy to merge!

value: str = ""

try:
value = json.loads(ssm_client.get_parameter(Name=_test_name)["Parameter"]["Value"])[key]
value = json.loads(hook.get_parameter_value(_test_name))[key]
# Since a default value after the SSM check is allowed, these exceptions should not stop execution.
except NoCredentialsError as e:
log.info("No boto credentials found: %s", e)
except ssm_client.exceptions.ParameterNotFound as e:
except hook.conn.exceptions.ParameterNotFound as e:
log.info("SSM does not contain any parameter for this test: %s", e)
except KeyError as e:
log.info("SSM contains one parameter for this test, but not the requested value: %s", e)
Expand Down