简体   繁体   English

MWAA 启动和停止 EC2 实例

[英]MWAA to start and stop EC2 Instances

I'm new to using the AWS managed Airflow service.我是使用 AWS 托管 Airflow 服务的新手。 I want to use Airflow to start an EC2 instance, make sure it's running and then do some further work in the instance.我想使用 Airflow 启动一个 EC2 实例,确保它正在运行,然后在实例中做一些进一步的工作。

So far i have this dag below which is basically a copy of this .到目前为止,我在下面有这个 dag,它基本上是这个的副本。

This however fails everytime and i'm not adept enough to know why?然而,这每次都失败了,我还不够熟练地知道为什么?

import os
from datetime import datetime

from airflow import DAG
from airflow.models.baseoperator import chain
from airflow.providers.amazon.aws.operators.ec2 import EC2StartInstanceOperator, EC2StopInstanceOperator
from airflow.providers.amazon.aws.sensors.ec2 import EC2InstanceStateSensor

INSTANCE_ID = os.getenv("INSTANCE_ID", "instance-id")

with DAG(
    dag_id='example_ec2',
    schedule_interval=None,
    start_date=datetime(2021, 1, 1),
    tags=['example'],
    catchup=False,
) as dag:
    # [START howto_operator_ec2_start_instance]
    start_instance = EC2StartInstanceOperator(
        task_id="ec2_start_instance",
        instance_id=INSTANCE_ID,
    )
    # [END howto_operator_ec2_start_instance]

    # [START howto_sensor_ec2_instance_state]
    instance_state = EC2InstanceStateSensor(
        task_id="ec2_instance_state",
        instance_id=INSTANCE_ID,
        target_state="running",
    )
    # [END howto_sensor_ec2_instance_state]

chain(start_instance, instance_state)

Just going to answer my own question in case anyone else finds this.只是要回答我自己的问题,以防其他人发现这一点。

The line below doesnt work for whatever reason无论出于何种原因,下面的行都不起作用

INSTANCE_ID = os.getenv("INSTANCE_ID", "instance-id")

The alternative is to do the following另一种方法是执行以下操作

from airflow.models import Variable # import Variable

INSTANCE_ID = Variable.get("INSTANCE_ID") # get INSTANCE_ID

Make sure you have added INSTANCE_ID as a variable by going to Admin -> Variable.确保您已通过转到 Admin -> Variable 将 INSTANCE_ID 添加为变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM