You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "syedahsn (via GitHub)" <gi...@apache.org> on 2023/02/15 00:45:43 UTC

[GitHub] [airflow] syedahsn opened a new pull request, #29548: Syedahsn/ec2 create terminate operators

syedahsn opened a new pull request, #29548:
URL: https://github.com/apache/airflow/pull/29548

   This PR creates two new operators `EC2CreateInstanceOperator` and `EC2TerminateInstanceOperator` which will be used to create and terminate EC2 instances respectively. The system test has been updated to use the new operators.
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   ---
   **^ Add meaningful description above**
   
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on pull request #29548: Add `EC2CreateInstanceOperator`, `EC2TerminateInstanceOperator`

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on PR #29548:
URL: https://github.com/apache/airflow/pull/29548#issuecomment-1449288429

   Seems like the "Wait for CI images" step failure could be related?
   ```
   ERROR tests/system/providers/amazon/aws/example_ec2.py - botocore.exceptions.NoCredentialsError: Unable to locate credentials
   ```
   ```
   ______ ERROR collecting tests/system/providers/amazon/aws/example_ec2.py _______
   tests/system/providers/amazon/aws/example_ec2.py:91: in <module>
       image_id = _get_latest_ami_id()
   tests/system/providers/amazon/aws/example_ec2.py:52: in _get_latest_ami_id
       Filters=[{"Name": "description", "Values": [image_prefix]}], Owners=["amazon"]
   /usr/local/lib/python3.7/site-packages/botocore/client.py:530: in _api_call
       return self._make_api_call(operation_name, kwargs)
   /usr/local/lib/python3.7/site-packages/botocore/client.py:944: in _make_api_call
       operation_model, request_dict, request_context
   /usr/local/lib/python3.7/site-packages/botocore/client.py:966: in _make_request
       return self._endpoint.make_request(operation_model, request_dict)
   /usr/local/lib/python3.7/site-packages/botocore/endpoint.py:119: in make_request
       return self._send_request(request_dict, operation_model)
   /usr/local/lib/python3.7/site-packages/botocore/endpoint.py:198: in _send_request
       request = self.create_request(request_dict, operation_model)
   /usr/local/lib/python3.7/site-packages/botocore/endpoint.py:137: in create_request
       operation_name=operation_model.name,
   /usr/local/lib/python3.7/site-packages/botocore/hooks.py:412: in emit
       return self._emitter.emit(aliased_event_name, **kwargs)
   /usr/local/lib/python3.7/site-packages/botocore/hooks.py:256: in emit
       return self._emit(event_name, kwargs)
   /usr/local/lib/python3.7/site-packages/botocore/hooks.py:239: in _emit
       response = handler(**kwargs)
   /usr/local/lib/python3.7/site-packages/botocore/signers.py:105: in handler
       return self.sign(operation_name, request)
   /usr/local/lib/python3.7/site-packages/botocore/signers.py:189: in sign
       auth.add_auth(request)
   /usr/local/lib/python3.7/site-packages/botocore/auth.py:418: in add_auth
       raise NoCredentialsError()
   E   botocore.exceptions.NoCredentialsError: Unable to locate credentials
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1113091829


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",

Review Comment:
   Just curious. I don't recall typically seeing booleans as template fields.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] syedahsn commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "syedahsn (via GitHub)" <gi...@apache.org>.
syedahsn commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1110449816


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",

Review Comment:
   I was thinking of a situation where someone wrote a task (say as a TaskFlow task) that would determine if they wanted to wait for the instances to be completed before continuing. Not sure if that is a valid case or not. Is there any harm in having extra templated fields?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1107926635


##########
tests/providers/amazon/aws/operators/test_ec2.py:
##########
@@ -20,23 +20,83 @@
 from moto import mock_ec2
 
 from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook
-from airflow.providers.amazon.aws.operators.ec2 import EC2StartInstanceOperator, EC2StopInstanceOperator
+from airflow.providers.amazon.aws.operators.ec2 import (
+    EC2CreateInstanceOperator,
+    EC2StartInstanceOperator,
+    EC2StopInstanceOperator,
+    EC2TerminateInstanceOperator,
+)
 
 
 class BaseEc2TestClass:
     @classmethod
-    def _create_instance(cls, hook: EC2Hook):
-        """Create Instance and return instance id."""
+    def _get_image_id(cls, hook):
+        """Get a valid image id to create an instance."""
         conn = hook.get_conn()
         try:
             ec2_client = conn.meta.client
         except AttributeError:
             ec2_client = conn
-
-        # We need existed AMI Image ID otherwise `moto` will raise DeprecationWarning.
+        
+        # We need an existing AMI Image ID otherwise `moto` will raise DeprecationWarning.
         images = ec2_client.describe_images()["Images"]
-        response = ec2_client.run_instances(MaxCount=1, MinCount=1, ImageId=images[0]["ImageId"])
-        return response["Instances"][0]["InstanceId"]
+        return images[0]["ImageId"]
+
+class TestEC2CreateInstanceOperator(BaseEc2TestClass):
+    def test_init(self):
+        ec2_operator = EC2CreateInstanceOperator(
+            task_id="test_create_instance",
+            image_id="test_image_id",
+        )
+
+        assert ec2_operator.task_id == "test_create_instance"
+        assert ec2_operator.image_id == "test_image_id"
+        assert ec2_operator.max_count == 1
+        assert ec2_operator.min_count == 1
+        assert ec2_operator.max_attempts == 20
+        assert ec2_operator.poll_interval == 20
+
+    @mock_ec2
+    def test_create_intance(self):
+        ec2_hook = EC2Hook()
+        create_instance = EC2CreateInstanceOperator(
+            image_id=self._get_image_id(ec2_hook),
+            task_id="test_create_instance",
+        )
+        instance_id = create_instance.execute(None)
+
+        assert ec2_hook.get_instance_state(instance_id=instance_id) == "running"
+
+
+class TestEC2TerminateInstanceOperator(BaseEc2TestClass):
+    def test_init(self):
+        ec2_operator = EC2TerminateInstanceOperator(
+            task_id="test_terminate_instance",
+            instance_id="test_image_id",
+        )
+
+        assert ec2_operator.task_id == "test_terminate_instance"
+        assert ec2_operator.max_attempts == 20
+        assert ec2_operator.poll_interval == 20
+
+    @mock_ec2
+    def test_terminate_intance(self):

Review Comment:
   ```suggestion
       def test_terminate_instance(self):
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1107926537


##########
tests/providers/amazon/aws/operators/test_ec2.py:
##########
@@ -20,23 +20,83 @@
 from moto import mock_ec2
 
 from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook
-from airflow.providers.amazon.aws.operators.ec2 import EC2StartInstanceOperator, EC2StopInstanceOperator
+from airflow.providers.amazon.aws.operators.ec2 import (
+    EC2CreateInstanceOperator,
+    EC2StartInstanceOperator,
+    EC2StopInstanceOperator,
+    EC2TerminateInstanceOperator,
+)
 
 
 class BaseEc2TestClass:
     @classmethod
-    def _create_instance(cls, hook: EC2Hook):
-        """Create Instance and return instance id."""
+    def _get_image_id(cls, hook):
+        """Get a valid image id to create an instance."""
         conn = hook.get_conn()
         try:
             ec2_client = conn.meta.client
         except AttributeError:
             ec2_client = conn
-
-        # We need existed AMI Image ID otherwise `moto` will raise DeprecationWarning.
+        
+        # We need an existing AMI Image ID otherwise `moto` will raise DeprecationWarning.
         images = ec2_client.describe_images()["Images"]
-        response = ec2_client.run_instances(MaxCount=1, MinCount=1, ImageId=images[0]["ImageId"])
-        return response["Instances"][0]["InstanceId"]
+        return images[0]["ImageId"]
+
+class TestEC2CreateInstanceOperator(BaseEc2TestClass):

Review Comment:
   Might be wise to add a test for creating multiple instances too. WDYT?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] eladkal commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "eladkal (via GitHub)" <gi...@apache.org>.
eladkal commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1113927353


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",

Review Comment:
   Do we have an issue for this task?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] uranusjr commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1113923418


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",

Review Comment:
   Currently template fields are also used for XComArg, where boolean makes sense. There’re talks to separate those two ideas but for now having the field can be useful.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell merged pull request #29548: Add `EC2CreateInstanceOperator`, `EC2TerminateInstanceOperator`

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell merged PR #29548:
URL: https://github.com/apache/airflow/pull/29548


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1107924100


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",
+    )
+
+    def __init__(
+        self,
+        image_id: str,
+        max_count: int = 1,
+        min_count: int = 1,
+        aws_conn_id: str = "aws_default",
+        region_name: str | None = None,
+        poll_interval: int = 20,
+        max_attempts: int = 20,
+        config: dict | None = None,
+        wait_for_completion: bool = False,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        self.image_id = image_id
+        self.max_count = max_count
+        self.min_count = min_count
+        self.aws_conn_id = aws_conn_id
+        self.region_name = region_name
+        self.poll_interval = poll_interval
+        self.max_attempts = max_attempts
+        self.config = config or {}
+        self.wait_for_completion = wait_for_completion
+
+    def execute(self, context: Context):
+        ec2_hook = EC2Hook(aws_conn_id=self.aws_conn_id, region_name=self.region_name, api_type="client_type")
+        instances = ec2_hook.conn.run_instances(
+            ImageId=self.image_id,
+            MinCount=self.min_count,
+            MaxCount=self.max_count,
+            **self.config,
+        )["Instances"]
+        instance_ids = []
+        for instance in instances:
+            instance_ids.append(instance["InstanceId"])
+            self.log.info("Created EC2 instance %s", instance["InstanceId"])
+
+            if self.wait_for_completion:
+                ec2_hook.get_waiter("instance_running").wait(
+                    InstanceIds=[instance["InstanceId"]],
+                    WaiterConfig={
+                        "Delay": self.poll_interval,
+                        "MaxAttempts": self.max_attempts,
+                    },
+                )
+
+        return instance_ids
+
+
+class EC2TerminateInstanceOperator(BaseOperator):
+    """
+    Terminate an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2TerminateInstanceOperator`
+
+    :instance_id: ID of the instance to be terminated.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `terminated` state before returning.
+    """
+
+    template_fields: Sequence[str] = ("instance_id", "region_name", "aws_conn_id", "wait_for_completion")
+
+    def __init__(
+        self,
+        instance_id: str | list[str],
+        aws_conn_id: str = "aws_default",
+        region_name: str | None = None,
+        poll_interval: int = 20,
+        max_attempts: int = 20,
+        wait_for_completion: bool = False,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        self.instance_ids = [*instance_id]

Review Comment:
   This would unpack a single `instance_id` into each character individually. Probably should check the type of `instance_id` first (i.e. `str` or `list`) and normalize to a list of `instance_id`s.
   ```suggestion
           self.instance_ids = [instance_id] if isinstance(instance_id, str) else instance_id
   ```
   



##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",
+    )
+
+    def __init__(
+        self,
+        image_id: str,
+        max_count: int = 1,
+        min_count: int = 1,
+        aws_conn_id: str = "aws_default",
+        region_name: str | None = None,
+        poll_interval: int = 20,
+        max_attempts: int = 20,
+        config: dict | None = None,
+        wait_for_completion: bool = False,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        self.image_id = image_id
+        self.max_count = max_count
+        self.min_count = min_count
+        self.aws_conn_id = aws_conn_id
+        self.region_name = region_name
+        self.poll_interval = poll_interval
+        self.max_attempts = max_attempts
+        self.config = config or {}
+        self.wait_for_completion = wait_for_completion
+
+    def execute(self, context: Context):
+        ec2_hook = EC2Hook(aws_conn_id=self.aws_conn_id, region_name=self.region_name, api_type="client_type")
+        instances = ec2_hook.conn.run_instances(
+            ImageId=self.image_id,
+            MinCount=self.min_count,
+            MaxCount=self.max_count,
+            **self.config,
+        )["Instances"]
+        instance_ids = []
+        for instance in instances:
+            instance_ids.append(instance["InstanceId"])
+            self.log.info("Created EC2 instance %s", instance["InstanceId"])
+
+            if self.wait_for_completion:
+                ec2_hook.get_waiter("instance_running").wait(
+                    InstanceIds=[instance["InstanceId"]],
+                    WaiterConfig={
+                        "Delay": self.poll_interval,
+                        "MaxAttempts": self.max_attempts,
+                    },
+                )
+
+        return instance_ids
+
+
+class EC2TerminateInstanceOperator(BaseOperator):
+    """
+    Terminate an EC2 Instance using boto3

Review Comment:
   Same, related comment here too. This operator _could_ terminate multiple instances. I think users might like to know that upfront if they read the Python API docs instead of having to read the source code.



##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3

Review Comment:
   Technically this could start multiple instances based on the `max_` and `min_count` args. Let's update this description to account for that behavior too.



##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",

Review Comment:
   Curious to know what a use case would be to have `wait_for_completion` as a template field? What did you have in mind here?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on a diff in pull request #29548: Add `EC2CreateInstanceOperator`, `EC2TerminateInstanceOperator`

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1113095186


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,141 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start a specified number of EC2 Instances using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2CreateInstanceOperator`
+
+    :param image_id: ID of the AMI used to create the instance.
+    :param max_count: Maximum number of instances to launch. Defaults to 1.
+    :param min_count: Minimum number of instances to launch. Defaults to 1.
+    :param aws_conn_id: AWS connection to use
+    :param region_name: AWS region name associated with the client.
+    :param poll_interval: Number of seconds to wait before attempting to
+        check state of instance. Only used if wait_for_completion is True. Default is 20.
+    :param max_attempts: Maximum number of attempts when checking state of instance.
+        Only used if wait_for_completion is True. Default is 20.
+    :param config: Dictionary for arbitrary parameters to the boto3 run_instances call.
+    :param wait_for_completion: If True, the operator will wait for the instance to be
+        in the `running` state before returning.
+    """
+
+    template_fields: Sequence[str] = (
+        "image_id",
+        "max_count",
+        "min_count",
+        "aws_conn_id",
+        "region_name",
+        "config",
+        "wait_for_completion",
+    )
+
+    def __init__(
+        self,
+        image_id: str,
+        max_count: int = 1,
+        min_count: int = 1,
+        aws_conn_id: str = "aws_default",
+        region_name: str | None = None,
+        poll_interval: int = 20,
+        max_attempts: int = 20,
+        config: dict | None = None,
+        wait_for_completion: bool = False,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+        self.image_id = image_id
+        self.max_count = max_count
+        self.min_count = min_count
+        self.aws_conn_id = aws_conn_id
+        self.region_name = region_name
+        self.poll_interval = poll_interval
+        self.max_attempts = max_attempts
+        self.config = config or {}
+        self.wait_for_completion = wait_for_completion
+
+    def execute(self, context: Context):
+        ec2_hook = EC2Hook(aws_conn_id=self.aws_conn_id, region_name=self.region_name, api_type="client_type")
+        instances = ec2_hook.conn.run_instances(
+            ImageId=self.image_id,
+            MinCount=self.min_count,
+            MaxCount=self.max_count,
+            **self.config,
+        )["Instances"]
+        instance_ids = []
+        for instance in instances:
+            instance_ids.append(instance["InstanceId"])
+            self.log.info("Created EC2 instance %s", instance["InstanceId"])
+
+            if self.wait_for_completion:
+                ec2_hook.get_waiter("instance_running").wait(
+                    InstanceIds=[instance["InstanceId"]],
+                    WaiterConfig={
+                        "Delay": self.poll_interval,
+                        "MaxAttempts": self.max_attempts,
+                    },
+                )
+
+        return instance_ids
+
+
+class EC2TerminateInstanceOperator(BaseOperator):
+    """
+    Terminate EC2 Instances using boto3
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the guide:
+        :ref:`howto/operator:EC2TerminateInstanceOperator`
+
+    :instance_id: ID of the instance to be terminated.

Review Comment:
   ```suggestion
       :param instance_ids: ID of the instance to be terminated.
   ```
   Just so this parameter is properly displayed in the Python API docs.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] josh-fell commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "josh-fell (via GitHub)" <gi...@apache.org>.
josh-fell commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1107926793


##########
tests/providers/amazon/aws/operators/test_ec2.py:
##########
@@ -20,23 +20,83 @@
 from moto import mock_ec2
 
 from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook
-from airflow.providers.amazon.aws.operators.ec2 import EC2StartInstanceOperator, EC2StopInstanceOperator
+from airflow.providers.amazon.aws.operators.ec2 import (
+    EC2CreateInstanceOperator,
+    EC2StartInstanceOperator,
+    EC2StopInstanceOperator,
+    EC2TerminateInstanceOperator,
+)
 
 
 class BaseEc2TestClass:
     @classmethod
-    def _create_instance(cls, hook: EC2Hook):
-        """Create Instance and return instance id."""
+    def _get_image_id(cls, hook):
+        """Get a valid image id to create an instance."""
         conn = hook.get_conn()
         try:
             ec2_client = conn.meta.client
         except AttributeError:
             ec2_client = conn
-
-        # We need existed AMI Image ID otherwise `moto` will raise DeprecationWarning.
+        
+        # We need an existing AMI Image ID otherwise `moto` will raise DeprecationWarning.
         images = ec2_client.describe_images()["Images"]
-        response = ec2_client.run_instances(MaxCount=1, MinCount=1, ImageId=images[0]["ImageId"])
-        return response["Instances"][0]["InstanceId"]
+        return images[0]["ImageId"]
+
+class TestEC2CreateInstanceOperator(BaseEc2TestClass):
+    def test_init(self):
+        ec2_operator = EC2CreateInstanceOperator(
+            task_id="test_create_instance",
+            image_id="test_image_id",
+        )
+
+        assert ec2_operator.task_id == "test_create_instance"
+        assert ec2_operator.image_id == "test_image_id"
+        assert ec2_operator.max_count == 1
+        assert ec2_operator.min_count == 1
+        assert ec2_operator.max_attempts == 20
+        assert ec2_operator.poll_interval == 20
+
+    @mock_ec2
+    def test_create_intance(self):
+        ec2_hook = EC2Hook()
+        create_instance = EC2CreateInstanceOperator(
+            image_id=self._get_image_id(ec2_hook),
+            task_id="test_create_instance",
+        )
+        instance_id = create_instance.execute(None)
+
+        assert ec2_hook.get_instance_state(instance_id=instance_id) == "running"
+
+
+class TestEC2TerminateInstanceOperator(BaseEc2TestClass):

Review Comment:
   Same here. WDYT about adding a test for termination multiple instances?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [airflow] syedahsn commented on a diff in pull request #29548: Syedahsn/ec2 create terminate operators

Posted by "syedahsn (via GitHub)" <gi...@apache.org>.
syedahsn commented on code in PR #29548:
URL: https://github.com/apache/airflow/pull/29548#discussion_r1110448364


##########
airflow/providers/amazon/aws/operators/ec2.py:
##########
@@ -116,3 +116,139 @@ def execute(self, context: Context):
             target_state="stopped",
             check_interval=self.check_interval,
         )
+
+
+class EC2CreateInstanceOperator(BaseOperator):
+    """
+    Create and start an EC2 Instance using boto3

Review Comment:
   Good point, I'll update the description. Thanks!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org