[
  {
    "path": ".github/FUNDING.yml",
    "content": "# aws-ecs-airflow is free to use to improve airflow deployment in AWS\n\ncustom: paypal.com/paypalme/NicolaCorda\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\n# Airflow\nairflow.db\nairflow-webserver.pid\nlogs\npostgres_data/\n\n# IDE\n.idea\n.vscode\n\n# Infrastructure\ninfrastructure/.terraform\ninfrastructure/terraform.tfstate\ninfrastructure/.terraform.tfstate.lock.info\ninfrastructure/terraform.tfstate.backup\n"
  },
  {
    "path": "Dockerfile",
    "content": "# BUILD: docker build --rm -t airflow .\n# ORIGINAL SOURCE: https://github.com/puckel/docker-airflow\n\nFROM python:3.8.5-slim\nLABEL version=\"1.1\"\nLABEL maintainer=\"nicor88\"\n\n# Never prompts the user for choices on installation/configuration of packages\nENV DEBIAN_FRONTEND noninteractive\nENV TERM linux\n\n# Airflow\n# it's possible to use v1-10-stable, but it's a development branch\nARG AIRFLOW_VERSION=1.10.11\nENV AIRFLOW_HOME=/usr/local/airflow\nENV AIRFLOW_GPL_UNIDECODE=yes\n# celery config\nARG CELERY_REDIS_VERSION=4.2.0\nARG PYTHON_REDIS_VERSION=3.2.0\n\nARG TORNADO_VERSION=5.1.1\nARG WERKZEUG_VERSION=0.16.0\n\n# Define en_US.\nENV LANGUAGE en_US.UTF-8\nENV LANG en_US.UTF-8\nENV LC_ALL en_US.UTF-8\nENV LC_CTYPE en_US.UTF-8\nENV LC_MESSAGES en_US.UTF-8\nENV LC_ALL en_US.UTF-8\n\nRUN set -ex \\\n    && buildDeps=' \\\n        python3-dev \\\n        libkrb5-dev \\\n        libsasl2-dev \\\n        libssl-dev \\\n        libffi-dev \\\n        build-essential \\\n        libblas-dev \\\n        liblapack-dev \\\n        libpq-dev \\\n        git \\\n    ' \\\n    && apt-get update -yqq \\\n    && apt-get upgrade -yqq \\\n    && apt-get install -yqq --no-install-recommends \\\n        ${buildDeps} \\\n        sudo \\\n        python3-pip \\\n        python3-requests \\\n        default-mysql-client \\\n        default-libmysqlclient-dev \\\n        apt-utils \\\n        curl \\\n        rsync \\\n        netcat \\\n        locales \\\n    && sed -i 's/^# en_US.UTF-8 UTF-8$/en_US.UTF-8 UTF-8/g' /etc/locale.gen \\\n    && locale-gen \\\n    && update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 \\\n    && useradd -ms /bin/bash -d ${AIRFLOW_HOME} airflow \\\n    && pip install -U pip setuptools wheel \\\n    && pip install --no-cache-dir pytz \\\n    && pip install --no-cache-dir pyOpenSSL \\\n    && pip install --no-cache-dir ndg-httpsclient \\\n    && pip install --no-cache-dir pyasn1 \\\n    && pip install --no-cache-dir typing_extensions \\\n    && pip install --no-cache-dir mysqlclient \\\n    && pip install --no-cache-dir apache-airflow[async,aws,crypto,celery,github_enterprise,kubernetes,jdbc,postgres,password,s3,slack,ssh]==${AIRFLOW_VERSION} \\\n    && pip install --no-cache-dir werkzeug==${WERKZEUG_VERSION} \\\n    && pip install --no-cache-dir redis==${PYTHON_REDIS_VERSION} \\\n    && pip install --no-cache-dir celery[redis]==${CELERY_REDIS_VERSION} \\\n    && pip install --no-cache-dir flask_oauthlib \\\n    && pip install --no-cache-dir SQLAlchemy==1.3.23 \\\n    && pip install --no-cache-dir Flask-SQLAlchemy==2.4.4 \\\n    && pip install --no-cache-dir psycopg2-binary \\\n    && pip install --no-cache-dir tornado==${TORNADO_VERSION} \\\n    && apt-get purge --auto-remove -yqq ${buildDeps} \\\n    && apt-get autoremove -yqq --purge \\\n    && apt-get clean \\\n    && rm -rf \\\n        /var/lib/apt/lists/* \\\n        /tmp/* \\\n        /var/tmp/* \\\n        /usr/share/man \\\n        /usr/share/doc \\\n        /usr/share/doc-base\n\n\nCOPY config/entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\nCOPY config/airflow.cfg ${AIRFLOW_HOME}/airflow.cfg\nCOPY dags ${AIRFLOW_HOME}/dags\nCOPY plugins ${AIRFLOW_HOME}/plugins\n\nRUN chown -R airflow: ${AIRFLOW_HOME}\n\nENV PYTHONPATH ${AIRFLOW_HOME}\n\nUSER airflow\n\nCOPY requirements.txt .\nRUN pip install --user --no-cache-dir -r requirements.txt\n\nEXPOSE 8080 5555 8793\n\nWORKDIR ${AIRFLOW_HOME}\nENTRYPOINT [\"/entrypoint.sh\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 nicor88\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "airflow-up:\n\t@docker-compose up --build\n\nairflow-down:\n\t@docker-compose down\n\ninfra-get:\n\tcd infrastructure && terraform get;\n\ninfra-init: infra-get\n\tcd infrastructure && terraform init -upgrade;\n\ninfra-plan: infra-init\n\tcd infrastructure && terraform plan;\n\ninfra-apply: infra-plan\n\tcd infrastructure && terraform apply;\n\ninfra-destroy:\n\tcd infrastructure && terraform destroy;\n\nclean:\n\trm -rf postgres_data\n"
  },
  {
    "path": "README.md",
    "content": "# airflow-ecs\nSetup to run Airflow in AWS ECS containers\n\n## Requirements\n\n### Local\n* Docker\n\n### AWS\n* AWS IAM User for the infrastructure deployment, with admin permissions\n* [awscli](https://aws.amazon.com/cli/), intall running `pip install awscli`\n* [terraform >= 0.13](https://www.terraform.io/downloads.html)\n* setup your IAM User credentials inside `~/.aws/credentials`\n* setup these env variables in your .zshrc or .bashrc, or in your the terminal session that you are going to use\n  <pre>\n  export AWS_ACCOUNT=your_account_id\n  export AWS_DEFAULT_REGION=us-east-1 # it's the default region that needs to be setup also in infrastructure/config.tf\n  </pre>\n\n\n## Local Development\n* Generate a Fernet Key:\n  <pre>\n  pip install cryptography\n  export AIRFLOW_FERNET_KEY=$(python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\")\n  </pre>\n  More about that [here](https://cryptography.io/en/latest/fernet/)\n\n* Start Airflow locally simply running:\n  <pre>\n  docker-compose up --build\n  </pre\n\nIf everything runs correctly you can reach Airflow navigating to [localhost:8080](http://localhost:8080).\nThe current setup is based on [Celery Workers](https://airflow.apache.org/howto/executor/use-celery.html). You can monitor how many workers are currently active using Flower, visiting [localhost:5555](http://localhost:5555)\n\n## Deploy Airflow on AWS ECS\nTo run Airflow in AWS we will use ECS (Elastic Container Service).\n\n### Deploy Infrastructure using Terraform\nRun the following commands:\n<pre>\nmake infra-init\nmake infra-plan\nmake infra-apply\n</pre>\n\nor alternatively\n<pre>\ncd infrastructure\nterraform get\nterraform init -upgrade;\nterraform plan\nterraform apply\n</pre>\n\nBy default the infrastructure is deployed in `us-east-1`.\n\nWhen the infrastructure is provisioned (the RDS metadata DB will take a while) check the if the ECR repository is created then run:\n<pre>\nbash scripts/push_to_ecr.sh airflow-dev\n</pre>\nBy default the repo name created with terraform is `airflow-dev`\nWithout this command the ECS services will fail to fetch the `latest` image from ECR\n\n### Deploy new Airflow application\nTo deploy an update version of Airflow you need to push a new container image to ECR.\nYou can simply doing that running:\n<pre>\n./scripts/deploy.sh airflow-dev\n</pre>\n\nThe deployment script will take care of:\n* push a new ECR image to your repository\n* re-deploy the new ECS services with the updated image\n\n## TODO\n* Create Private Subnets\n* Move ECS containers to Private Subnets\n* Use ECS private Links for Private Subnets\n* Improve ECS Task and Service Role\n"
  },
  {
    "path": "config/airflow.cfg",
    "content": "[core]\n# The folder where your airflow pipelines live, most likely a\n# subfolder in a code repository\n# This path must be absolute\ndags_folder = /usr/local/airflow/dags\n\n# The folder where airflow should store its log files\n# This path must be absolute\nbase_log_folder = /usr/local/airflow/logs\n\n# Airflow can store logs remotely in AWS S3, Google Cloud Storage or Elastic Search.\n# Users must supply an Airflow connection id that provides access to the storage\n# location. If remote_logging is set to true, see UPDATING.md for additional\n# configuration requirements.\nremote_logging = False\nremote_log_conn_id =\nremote_base_log_folder =\nencrypt_s3_logs = False\n\n# Logging level\nlogging_level = INFO\nfab_logging_level = WARN\n\n# Logging class\n# Specify the class that will specify the logging configuration\n# This class has to be on the python classpath\n# logging_config_class = my.path.default_local_settings.LOGGING_CONFIG\nlogging_config_class =\n\n# Log format\n# Colour the logs when the controlling terminal is a TTY.\ncolored_console_log = True\ncolored_log_format = [%%(blue)s%%(asctime)s%%(reset)s] {{%%(blue)s%%(filename)s:%%(reset)s%%(lineno)d}} %%(log_color)s%%(levelname)s%%(reset)s - %%(log_color)s%%(message)s%%(reset)s\ncolored_formatter_class = airflow.utils.log.colored_log.CustomTTYColoredFormatter\n\n# log_format = [%%(asctime)s] {{%%(filename)s:%%(lineno)d}} %%(levelname)s - %%(message)s\nlog_format = [%%(asctime)s] %%(levelname)s - %%(message)s\nsimple_log_format = %%(asctime)s %%(levelname)s - %%(message)s\n\n# Log filename format\n# we need to escape the curly braces by adding an additional curly brace\nlog_filename_template = {{ ti.dag_id }}/{{ ti.task_id }}/{{ ts }}/{{ try_number }}.log\nlog_processor_filename_template = {{ filename }}.log\ndag_processor_manager_log_location = /usr/local/airflow/logs/dag_processor_manager/dag_processor_manager.log\n\n# Hostname by providing a path to a callable, which will resolve the hostname\nhostname_callable = socket:getfqdn\n\n# Default timezone in case supplied date times are naive\n# can be utc (default), system, or any IANA timezone string (e.g. Europe/Amsterdam)\ndefault_timezone = Europe/Amsterdam\n\n# The executor class that airflow should use. Choices include\n# SequentialExecutor, LocalExecutor, CeleryExecutor, DaskExecutor\nexecutor = CeleryExecutor\n\n# The SqlAlchemy connection string to the metadata database.\n# SqlAlchemy supports many different database engine, more information\n# their website\nsql_alchemy_conn = postgresql+psycopg2://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB\n\n# The encoding for the databases\nsql_engine_encoding = utf-8\n\n# If SqlAlchemy should pool database connections.\nsql_alchemy_pool_enabled = True\n\n# The SqlAlchemy pool size is the maximum number of database connections\n# in the pool. 0 indicates no limit.\nsql_alchemy_pool_size = 5\n\n# The maximum overflow size of the pool.\n# When the number of checked-out connections reaches the size set in pool_size,\n# additional connections will be returned up to this limit.\n# When those additional connections are returned to the pool, they are disconnected and discarded.\n# It follows then that the total number of simultaneous connections the pool will allow is pool_size + max_overflow,\n# and the total number of \"sleeping\" connections the pool will allow is pool_size.\n# max_overflow can be set to -1 to indicate no overflow limit;\n# no limit will be placed on the total number of concurrent connections. Defaults to 10.\nsql_alchemy_max_overflow = 10\n\n# The SqlAlchemy pool recycle is the number of seconds a connection\n# can be idle in the pool before it is invalidated. This config does\n# not apply to sqlite. If the number of DB connections is ever exceeded,\n# a lower config value will allow the system to recover faster.\nsql_alchemy_pool_recycle = 1800\n\n# Check connection at the start of each connection pool checkout.\n# Typically, this is a simple statement like “SELECT 1”.\n# More information here: https://docs.sqlalchemy.org/en/13/core/pooling.html#disconnect-handling-pessimistic\nsql_alchemy_pool_pre_ping = True\n\n# The schema to use for the metadata database\n# SqlAlchemy supports databases with the concept of multiple schemas.\nsql_alchemy_schema =\n\n# The amount of parallelism as a setting to the executor. This defines\n# the max number of task instances that should run simultaneously\n# on this airflow installation\nparallelism = 32\n\n# The number of task instances allowed to run concurrently by the scheduler\ndag_concurrency = 32\n\n# Are DAGs paused by default at creation\ndags_are_paused_at_creation = True\n\n# When not using pools, tasks are run in the \"default pool\",\n# whose size is guided by this config element\nnon_pooled_task_slot_count = 128\n\n# The maximum number of active DAG runs per DAG\nmax_active_runs_per_dag = 1\n\n# Whether to load the examples that ship with Airflow. It's good to\n# get started, but you probably want to set this to False in a production\n# environment\nload_examples = False\n\n# Where your Airflow plugins are stored\nplugins_folder = /usr/local/airflow/plugins\n\n# Secret key to save connection passwords in the db\nfernet_key = $FERNET_KEY\n\n# Whether to disable pickling dags\ndonot_pickle = False\n\n# How long before timing out a python file import while filling the DagBag\ndagbag_import_timeout = 30\n\n# How long before timing out a DagFileProcessor, which processes a dag file\ndag_file_processor_timeout = 30\n\n# The class to use for running task instances in a subprocess\ntask_runner = StandardTaskRunner\n\n# If set, tasks without a `run_as_user` argument will be run with this user\n# Can be used to de-elevate a sudo user running Airflow when executing tasks\ndefault_impersonation =\n\n# What security module to use (for example kerberos):\nsecurity =\n\n# If set to False enables some unsecure features like Charts and Ad Hoc Queries.\n# In 2.0 will default to True.\nsecure_mode = True\n\n# Turn unit test mode on (overwrites many configuration options with test\n# values at runtime)\nunit_test_mode = False\n\n# Name of handler to read task instance logs.\n# Default to use task handler.\ntask_log_reader = task\n\n# Whether to enable pickling for xcom (note that this is insecure and allows for\n# RCE exploits). This will be deprecated in Airflow 2.0 (be forced to False).\nenable_xcom_pickling = True\n\n# When a task is killed forcefully, this is the amount of time in seconds that\n# it has to cleanup after it is sent a SIGTERM, before it is SIGKILLED\nkilled_task_cleanup_time = 60\n\n# Whether to override params with dag_run.conf. If you pass some key-value pairs through `airflow backfill -c` or\n# `airflow trigger_dag -c`, the key-value pairs will override the existing ones in params.\ndag_run_conf_overrides_params = False\n\n# Worker initialisation check to validate Metadata Database connection\nworker_precheck = False\n\n# When discovering DAGs, ignore any files that don't contain the strings `DAG` and `airflow`.\ndag_discovery_safe_mode = False\n\n# The number of retries each task is going to have by default. Can be overridden at dag or task level.\ndefault_task_retries = 1\n\n# Whether to serialises DAGs and persist them in DB.\n# If set to True, Webserver reads from DB instead of parsing DAG files\n# More details: https://airflow.apache.org/howto/enable-dag-serialization.html\nstore_serialized_dags = False\n\n# Updating serialized DAG can not be faster than a minimum interval to reduce database write rate.\nmin_serialized_dag_update_interval = 30\n\n[cli]\n# In what way should the cli access the API. The LocalClient will use the\n# database directly, while the json_client will use the api running on the\n# webserver\napi_client = airflow.api.client.local_client\n\n# If you set web_server_url_prefix, do NOT forget to append it here, ex:\n# endpoint_url = http://localhost:8080/myroot\n# So api will look like: http://localhost:8080/myroot/api/experimental/...\nendpoint_url = http://localhost:8080\n\n[api]\n# How to authenticate users of the API\nauth_backend = airflow.api.auth.backend.default\n\n[lineage]\n# what lineage backend to use\nbackend =\n\n[atlas]\nsasl_enabled = False\nhost =\nport = 21000\nusername =\npassword =\n\n[operators]\n# The default owner assigned to each new operator, unless\n# provided explicitly or passed via `default_args`\ndefault_owner = airflow\ndefault_cpus = 1\ndefault_ram = 512\ndefault_disk = 512\ndefault_gpus = 0\n\n[hive]\n# Default mapreduce queue for HiveOperator tasks\ndefault_hive_mapred_queue =\n\n[webserver]\n# The base url of your website as airflow cannot guess what domain or\n# cname you are using. This is used in automated emails that\n# airflow sends to point links to the right web server\nbase_url = http://localhost:8080\n\n# The ip specified when starting the web server\nweb_server_host = 0.0.0.0\n\n# The port on which to run the web server\nweb_server_port = 8080\n\n# Paths to the SSL certificate and key for the web server. When both are\n# provided SSL will be enabled. This does not change the web server port.\nweb_server_ssl_cert =\nweb_server_ssl_key =\n\n# Number of seconds the webserver waits before killing gunicorn master that doesn't respond\nweb_server_master_timeout = 120\n\n# Number of seconds the gunicorn webserver waits before timing out on a worker\nweb_server_worker_timeout = 120\n\n# Number of workers to refresh at a time. When set to 0, worker refresh is\n# disabled. When nonzero, airflow periodically refreshes webserver workers by\n# bringing up new ones and killing old ones.\nworker_refresh_batch_size = 1\n\n# Number of seconds to wait before refreshing a batch of workers.\nworker_refresh_interval = 30\n\n# Secret key used to run your flask app\nsecret_key = temporary_key\n\n# Number of workers to run the Gunicorn web server\nworkers = 4\n\n# The worker class gunicorn should use. Choices include\n# sync (default), eventlet, gevent\nworker_class = sync\n\n# Log files for the gunicorn webserver. '-' means log to stderr.\naccess_logfile = -\nerror_logfile = -\n\n# Expose the configuration file in the web server\n# This is only applicable for the flask-admin based web UI (non FAB-based).\n# In the FAB-based web UI with RBAC feature,\n# access to configuration is controlled by role permissions.\nexpose_config = True\n\n# Set to true to turn on authentication:\n# https://airflow.apache.org/security.html#web-authentication\nauthenticate = False\n\n# Filter the list of dags by owner name (requires authentication to be enabled)\nfilter_by_owner = False\n\n# Filtering mode. Choices include user (default) and ldapgroup.\n# Ldap group filtering requires using the ldap backend\n#\n# Note that the ldap server needs the \"memberOf\" overlay to be set up\n# in order to user the ldapgroup mode.\nowner_mode = user\n\n# Default DAG view.  Valid values are:\n# tree, graph, duration, gantt, landing_times\ndag_default_view = graph\n\n# Default DAG orientation. Valid values are:\n# LR (Left->Right), TB (Top->Bottom), RL (Right->Left), BT (Bottom->Top)\ndag_orientation = LR\n\n# Puts the webserver in demonstration mode; blurs the names of Operators for\n# privacy.\ndemo_mode = False\n\n# The amount of time (in secs) webserver will wait for initial handshake\n# while fetching logs from other worker machine\nlog_fetch_timeout_sec = 3\n\n# By default, the webserver shows paused DAGs. Flip this to hide paused\n# DAGs by default\nhide_paused_dags_by_default = False\n\n# Consistent page size across all listing views in the UI\npage_size = 50\n\n# Use FAB-based webserver with RBAC feature\nrbac = False\n\n# Define the color of navigation bar\nnavbar_color = #007A87\n\n# Default dagrun to show in UI\ndefault_dag_run_display_number = 25\n\n# Enable werkzeug `ProxyFix` middleware\nenable_proxy_fix = False\n\n# Set secure flag on session cookie\ncookie_secure = False\n\n# Set samesite policy on session cookie\ncookie_samesite =\n\n# Default setting for wrap toggle on DAG code and TI log views.\ndefault_wrap = False\n\n# Send anonymous user activity to your analytics tool\n# analytics_tool = # choose from google_analytics, segment, or metarouter\n# analytics_id = XXXXXXXXXXX\n\n[email]\nemail_backend = airflow.utils.email.send_email_smtp\n\n[smtp]\n# If you want airflow to send emails on retries, failure, and you want to use\n# the airflow.utils.email.send_email_smtp function, you have to configure an\n# smtp server here\nsmtp_host = localhost\nsmtp_starttls = True\nsmtp_ssl = False\n# Uncomment and set the user/pass settings if you want to use SMTP AUTH\n# smtp_user = airflow\n# smtp_password = airflow\nsmtp_port = 25\nsmtp_mail_from = airflow@example.com\n\n[celery]\n# This section only applies if you are using the CeleryExecutor in\n# [core] section above\n\n# The app name that will be used by celery\ncelery_app_name = airflow.executors.celery_executor\n\n# The concurrency that will be used when starting workers with the\n# \"airflow worker\" command. This defines the number of task instances that\n# a worker will take, so size up your workers based on the resources on\n# your worker box and the nature of your tasks\nworker_concurrency = 16\n\n# The maximum and minimum concurrency that will be used when starting workers with the\n# \"airflow worker\" command (always keep minimum processes, but grow to maximum if necessary).\n# Note the value should be \"max_concurrency,min_concurrency\"\n# Pick these numbers based on resources on worker box and the nature of the task.\n# If autoscale option is available, worker_concurrency will be ignored.\n# http://docs.celeryproject.org/en/latest/reference/celery.bin.worker.html#cmdoption-celery-worker-autoscale\n# worker_autoscale = 16,12\n\n# When you start an airflow worker, airflow starts a tiny web server\n# subprocess to serve the workers local log files to the airflow main\n# web server, who then builds pages and sends them to users. This defines\n# the port on which the logs are served. It needs to be unused, and open\n# visible from the main web server to connect into the workers.\nworker_log_server_port = 8793\n\n# The Celery broker URL. Celery supports RabbitMQ, Redis and experimentally\n# a sqlalchemy database. Refer to the Celery documentation for more\n# information.\n# http://docs.celeryproject.org/en/latest/userguide/configuration.html#broker-settings\nbroker_url = redis://redis:6379/1\n\n# The Celery result_backend. When a job finishes, it needs to update the\n# metadata of the job. Therefore it will post a message on a message bus,\n# or insert it into a database (depending of the backend)\n# This status is used by the scheduler to update the state of the task\n# The use of a database is highly recommended\n# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-result-backend-settings\nresult_backend = db+postgresql://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB\n\n# Celery Flower is a sweet UI for Celery. Airflow has a shortcut to start\n# it `airflow flower`. This defines the IP that Celery Flower runs on\nflower_host = 0.0.0.0\n\n# The root URL for Flower\n# Ex: flower_url_prefix = /flower\nflower_url_prefix =\n\n# This defines the port that Celery Flower runs on\nflower_port = 5555\n\n# Securing Flower with Basic Authentication\n# Accepts user:password pairs separated by a comma\n# Example: flower_basic_auth = user1:password1,user2:password2\nflower_basic_auth =\n\n# Default queue that tasks get assigned to and that worker listen on.\ndefault_queue = default\n\n# How many processes CeleryExecutor uses to sync task state.\n# 0 means to use max(1, number of cores - 1) processes.\nsync_parallelism = 0\n\n# Import path for celery configuration options\ncelery_config_options = airflow.config_templates.default_celery.DEFAULT_CELERY_CONFIG\n\n# In case of using SSL\nssl_active = False\nssl_key =\nssl_cert =\nssl_cacert =\n\n# Celery Pool implementation.\n# Choices include: prefork (default), eventlet, gevent or solo.\n# See:\n#   https://docs.celeryproject.org/en/latest/userguide/workers.html#concurrency\n#   https://docs.celeryproject.org/en/latest/userguide/concurrency/eventlet.html\npool = prefork\n\n[celery_broker_transport_options]\n# This section is for specifying options which can be passed to the\n# underlying celery broker transport.  See:\n# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-broker_transport_options\n\n# The visibility timeout defines the number of seconds to wait for the worker\n# to acknowledge the task before the message is redelivered to another worker.\n# Make sure to increase the visibility timeout to match the time of the longest\n# ETA you're planning to use.\n#\n# visibility_timeout is only supported for Redis and SQS celery brokers.\n# See:\n#   http://docs.celeryproject.org/en/master/userguide/configuration.html#std:setting-broker_transport_options\n#\n#visibility_timeout = 21600\n\n[dask]\n# This section only applies if you are using the DaskExecutor in\n# [core] section above\n\n# The IP address and port of the Dask cluster's scheduler.\ncluster_address = 127.0.0.1:8786\n# TLS/ SSL settings to access a secured Dask scheduler.\ntls_ca =\ntls_cert =\ntls_key =\n\n[scheduler]\n# Task instances listen for external kill signal (when you clear tasks\n# from the CLI or the UI), this defines the frequency at which they should\n# listen (in seconds).\njob_heartbeat_sec = 5\n\n# The scheduler constantly tries to trigger new tasks (look at the\n# scheduler section in the docs for more information). This defines\n# how often the scheduler should run (in seconds).\nscheduler_heartbeat_sec = 5\n\n# after how much time should the scheduler terminate in seconds\n# -1 indicates to run continuously (see also num_runs)\nrun_duration = -1\n\n# The number of times to try to schedule each DAG file\n# -1 indicates unlimited number\nnum_runs = -1\n\n# The number of seconds to wait between consecutive DAG file processing\nprocessor_poll_interval = 1\n\n# after how much time (seconds) a new DAGs should be picked up from the filesystem\nmin_file_process_interval = 0\n\n# How often (in seconds) to scan the DAGs directory for new files. Default to 5 minutes.\ndag_dir_list_interval = 180\n\n# How often should stats be printed to the logs\nprint_stats_interval = 30\n\n# If the last scheduler heartbeat happened more than scheduler_health_check_threshold ago (in seconds),\n# scheduler is considered unhealthy.\n# This is used by the health check in the \"/health\" endpoint\n# This is used by the health check in the \"/health\" endpoint\nscheduler_health_check_threshold = 30\n\nchild_process_log_directory = /usr/local/airflow/logs/scheduler\n\n# Local task jobs periodically heartbeat to the DB. If the job has\n# not heartbeat in this many seconds, the scheduler will mark the\n# associated task instance as failed and will re-schedule the task.\nscheduler_zombie_task_threshold = 300\n\n# Turn off scheduler catchup by setting this to False.\n# Default behavior is unchanged and\n# Command Line Backfills still work, but the scheduler\n# will not do scheduler catchup if this is False,\n# however it can be set on a per DAG basis in the\n# DAG definition (catchup)\ncatchup_by_default = False\n\n# This changes the batch size of queries in the scheduling main loop.\n# If this is too high, SQL query performance may be impacted by one\n# or more of the following:\n#  - reversion to full table scan\n#  - complexity of query predicate\n#  - excessive locking\n#\n# Additionally, you may hit the maximum allowable query length for your db.\n#\n# Set this to 0 for no limit (not advised)\nmax_tis_per_query = 512\n\n# Statsd (https://github.com/etsy/statsd) integration settings\nstatsd_on = False\nstatsd_host = localhost\nstatsd_port = 8125\nstatsd_prefix = airflow\n\n# The scheduler can run multiple threads in parallel to schedule dags.\n# This defines how many threads will run.\nmax_threads = 2\n\nauthenticate = False\n\n# Turn off scheduler use of cron intervals by setting this to False.\n# DAGs submitted manually in the web UI or with trigger_dag will still run.\nuse_job_schedule = True\n\n[ldap]\n# set this to ldaps://<your.ldap.server>:<port>\nuri =\nuser_filter = objectClass=*\nuser_name_attr = uid\ngroup_member_attr = memberOf\nsuperuser_filter =\ndata_profiler_filter =\nbind_user = cn=Manager,dc=example,dc=com\nbind_password = insecure\nbasedn = dc=example,dc=com\ncacert = /etc/ca/ldap_ca.crt\nsearch_scope = LEVEL\n\n# This setting allows the use of LDAP servers that either return a\n# broken schema, or do not return a schema.\nignore_malformed_schema = False\n\n[mesos]\n# Mesos master address which MesosExecutor will connect to.\nmaster = localhost:5050\n\n# The framework name which Airflow scheduler will register itself as on mesos\nframework_name = Airflow\n\n# Number of cpu cores required for running one task instance using\n# 'airflow run <dag_id> <task_id> <execution_date> --local -p <pickle_id>'\n# command on a mesos slave\ntask_cpu = 1\n\n# Memory in MB required for running one task instance using\n# 'airflow run <dag_id> <task_id> <execution_date> --local -p <pickle_id>'\n# command on a mesos slave\ntask_memory = 256\n\n# Enable framework checkpointing for mesos\n# See http://mesos.apache.org/documentation/latest/slave-recovery/\ncheckpoint = False\n\n# Failover timeout in milliseconds.\n# When checkpointing is enabled and this option is set, Mesos waits\n# until the configured timeout for\n# the MesosExecutor framework to re-register after a failover. Mesos\n# shuts down running tasks if the\n# MesosExecutor framework fails to re-register within this timeframe.\n# failover_timeout = 604800\n\n# Enable framework authentication for mesos\n# See http://mesos.apache.org/documentation/latest/configuration/\nauthenticate = False\n\n# Mesos credentials, if authentication is enabled\n# default_principal = admin\n# default_secret = admin\n\n# Optional Docker Image to run on slave before running the command\n# This image should be accessible from mesos slave i.e mesos slave\n# should be able to pull this docker image before executing the command.\n# docker_image_slave = puckel/docker-airflow\n\n[kerberos]\nccache = /tmp/airflow_krb5_ccache\n# gets augmented with fqdn\nprincipal = airflow\nreinit_frequency = 3600\nkinit_path = kinit\nkeytab = airflow.keytab\n\n[github_enterprise]\napi_rev = v3\n\n[admin]\n# UI to hide sensitive variable fields when set to True\nhide_sensitive_variable_fields = True\n\n[elasticsearch]\n# Elasticsearch host\nhost =\n# Format of the log_id, which is used to query for a given tasks logs\nlog_id_template = {{dag_id}}-{{task_id}}-{{execution_date}}-{{try_number}}\n# Used to mark the end of a log stream for a task\nend_of_log_mark = end_of_log\n# Qualified URL for an elasticsearch frontend (like Kibana) with a template argument for log_id\n# Code will construct log_id using the log_id template from the argument above.\n# NOTE: The code will prefix the https:// automatically, don't include that here.\nfrontend =\n# Write the task logs to the stdout of the worker, rather than the default files\nwrite_stdout = False\n# Instead of the default log formatter, write the log lines as JSON\njson_format = False\n# Log fields to also attach to the json output, if enabled\njson_fields = asctime, filename, lineno, levelname, message\n\n[elasticsearch_configs]\n\nuse_ssl = False\nverify_certs = True\n\n[kubernetes]\n# The repository, tag and imagePullPolicy of the Kubernetes Image for the Worker to Run\nworker_container_repository =\nworker_container_tag =\nworker_container_image_pull_policy = IfNotPresent\n\n# If True (default), worker pods will be deleted upon termination\ndelete_worker_pods = True\n\n# Number of Kubernetes Worker Pod creation calls per scheduler loop\nworker_pods_creation_batch_size = 1\n\n# The Kubernetes namespace where airflow workers should be created. Defaults to `default`\nnamespace =\n\n# The name of the Kubernetes ConfigMap Containing the Airflow Configuration (this file)\nairflow_configmap =\n\n# For docker image already contains DAGs, this is set to `True`, and the worker will search for dags in dags_folder,\n# otherwise use git sync or dags volume claim to mount DAGs\ndags_in_image = True\n\n# For either git sync or volume mounted DAGs, the worker will look in this subpath for DAGs\ndags_volume_subpath =\n\n# For DAGs mounted via a volume claim (mutually exclusive with git-sync and host path)\ndags_volume_claim =\n\n# For volume mounted logs, the worker will look in this subpath for logs\nlogs_volume_subpath =\n\n# A shared volume claim for the logs\nlogs_volume_claim =\n\n# For DAGs mounted via a hostPath volume (mutually exclusive with volume claim and git-sync)\n# Useful in local environment, discouraged in production\ndags_volume_host =\n\n# A hostPath volume for the logs\n# Useful in local environment, discouraged in production\nlogs_volume_host =\n\n# A list of configMapsRefs to envFrom. If more than one configMap is\n# specified, provide a comma separated list: configmap_a,configmap_b\nenv_from_configmap_ref =\n\n# A list of secretRefs to envFrom. If more than one secret is\n# specified, provide a comma separated list: secret_a,secret_b\nenv_from_secret_ref =\n\n# Git credentials and repository for DAGs mounted via Git (mutually exclusive with volume claim)\ngit_repo =\ngit_branch =\ngit_subpath =\n\n# The specific rev or hash the git_sync init container will checkout\n# This becomes GIT_SYNC_REV environment variable in the git_sync init container for worker pods\ngit_sync_rev =\n\n# Use git_user and git_password for user authentication or git_ssh_key_secret_name and git_ssh_key_secret_key\n# for SSH authentication\ngit_user =\ngit_password =\ngit_sync_root = /git\ngit_sync_dest = repo\n# Mount point of the volume if git-sync is being used.\n# i.e. {AIRFLOW_HOME}/dags\ngit_dags_folder_mount_point =\n\n# To get Git-sync SSH authentication set up follow this format\n#\n# airflow-secrets.yaml:\n# ---\n# apiVersion: v1\n# kind: Secret\n# metadata:\n#   name: airflow-secrets\n# data:\n#   # key needs to be gitSshKey\n#   gitSshKey: <base64_encoded_data>\n# ---\n# airflow-configmap.yaml:\n# apiVersion: v1\n# kind: ConfigMap\n# metadata:\n#   name: airflow-configmap\n# data:\n#   known_hosts: |\n#       github.com ssh-rsa <...>\n#   airflow.cfg: |\n#       ...\n#\n# git_ssh_key_secret_name = airflow-secrets\n# git_ssh_known_hosts_configmap_name = airflow-configmap\ngit_ssh_key_secret_name =\ngit_ssh_known_hosts_configmap_name =\n\n# To give the git_sync init container credentials via a secret, create a secret\n# with two fields: GIT_SYNC_USERNAME and GIT_SYNC_PASSWORD (example below) and\n# add `git_sync_credentials_secret = <secret_name>` to your airflow config under the kubernetes section\n#\n# Secret Example:\n# apiVersion: v1\n# kind: Secret\n# metadata:\n#   name: git-credentials\n# data:\n#   GIT_SYNC_USERNAME: <base64_encoded_git_username>\n#   GIT_SYNC_PASSWORD: <base64_encoded_git_password>\ngit_sync_credentials_secret =\n\n# For cloning DAGs from git repositories into volumes: https://github.com/kubernetes/git-sync\ngit_sync_container_repository = k8s.gcr.io/git-sync\ngit_sync_container_tag = v3.1.1\ngit_sync_init_container_name = git-sync-clone\ngit_sync_run_as_user = 65533\n\n# The name of the Kubernetes service account to be associated with airflow workers, if any.\n# Service accounts are required for workers that require access to secrets or cluster resources.\n# See the Kubernetes RBAC documentation for more:\n#   https://kubernetes.io/docs/admin/authorization/rbac/\nworker_service_account_name =\n\n# Any image pull secrets to be given to worker pods, If more than one secret is\n# required, provide a comma separated list: secret_a,secret_b\nimage_pull_secrets =\n\n# GCP Service Account Keys to be provided to tasks run on Kubernetes Executors\n# Should be supplied in the format: key-name-1:key-path-1,key-name-2:key-path-2\ngcp_service_account_keys =\n\n# Use the service account kubernetes gives to pods to connect to kubernetes cluster.\n# It's intended for clients that expect to be running inside a pod running on kubernetes.\n# It will raise an exception if called from a process not running in a kubernetes environment.\nin_cluster = True\n\n# When running with in_cluster=False change the default cluster_context or config_file\n# options to Kubernetes client. Leave blank these to use default behaviour like `kubectl` has.\n# cluster_context =\n# config_file =\n\n\n# Affinity configuration as a single line formatted JSON object.\n# See the affinity model for top-level key names (e.g. `nodeAffinity`, etc.):\n#   https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.12/#affinity-v1-core\naffinity =\n\n# A list of toleration objects as a single line formatted JSON array\n# See:\n#   https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.12/#toleration-v1-core\ntolerations =\n\n# **kwargs parameters to pass while calling a kubernetes client core_v1_api methods from Kubernetes Executor\n# provided as a single line formatted JSON dictionary string.\n# List of supported params in **kwargs are similar for all core_v1_apis, hence a single config variable for all apis\n# See:\n#   https://raw.githubusercontent.com/kubernetes-client/python/master/kubernetes/client/apis/core_v1_api.py\n# Note that if no _request_timeout is specified, the kubernetes client will wait indefinitely for kubernetes\n# api responses, which will cause the scheduler to hang. The timeout is specified as [connect timeout, read timeout]\nkube_client_request_args = {\"_request_timeout\" : [60,60] }\n\n# Worker pods security context options\n# See:\n#   https://kubernetes.io/docs/tasks/configure-pod-container/security-context/\n\n# Specifies the uid to run the first process of the worker pods containers as\nrun_as_user =\n\n# Specifies a gid to associate with all containers in the worker pods\n# if using a git_ssh_key_secret_name use an fs_group\n# that allows for the key to be read, e.g. 65533\nfs_group =\n\n[kubernetes_node_selectors]\n# The Key-value pairs to be given to worker pods.\n# The worker pods will be scheduled to the nodes of the specified key-value pairs.\n# Should be supplied in the format: key = value\n\n[kubernetes_annotations]\n# The Key-value annotations pairs to be given to worker pods.\n# Should be supplied in the format: key = value\n\n[kubernetes_environment_variables]\n# The scheduler sets the following environment variables into your workers. You may define as\n# many environment variables as needed and the kubernetes launcher will set them in the launched workers.\n# Environment variables in this section are defined as follows\n#     <environment_variable_key> = <environment_variable_value>\n#\n# For example if you wanted to set an environment variable with value `prod` and key\n# `ENVIRONMENT` you would follow the following format:\n#     ENVIRONMENT = prod\n#\n# Additionally you may override worker airflow settings with the AIRFLOW__<SECTION>__<KEY>\n# formatting as supported by airflow normally.\n\n[kubernetes_secrets]\n# The scheduler mounts the following secrets into your workers as they are launched by the\n# scheduler. You may define as many secrets as needed and the kubernetes launcher will parse the\n# defined secrets and mount them as secret environment variables in the launched workers.\n# Secrets in this section are defined as follows\n#     <environment_variable_mount> = <kubernetes_secret_object>=<kubernetes_secret_key>\n#\n# For example if you wanted to mount a kubernetes secret key named `postgres_password` from the\n# kubernetes secret object `airflow-secret` as the environment variable `POSTGRES_PASSWORD` into\n# your workers you would follow the following format:\n#     POSTGRES_PASSWORD = airflow-secret=postgres_credentials\n#\n# Additionally you may override worker airflow settings with the AIRFLOW__<SECTION>__<KEY>\n# formatting as supported by airflow normally.\n\n[kubernetes_labels]\n# The Key-value pairs to be given to worker pods.\n# The worker pods will be given these static labels, as well as some additional dynamic labels\n# to identify the task.\n# Should be supplied in the format: key = value\n"
  },
  {
    "path": "config/entrypoint.sh",
    "content": "#!/usr/bin/env bash\n\nTRY_LOOP=\"20\"\n\n: \"${REDIS_HOST:=\"redis\"}\"\n: \"${REDIS_PORT:=\"6379\"}\"\n\n: \"${POSTGRES_HOST:=\"postgres\"}\"\n: \"${POSTGRES_PORT:=\"5432\"}\"\n\nwait_for_port() {\n  local name=\"$1\" host=\"$2\" port=\"$3\"\n  local j=0\n  while ! nc -z \"$host\" \"$port\" >/dev/null 2>&1 < /dev/null; do\n    j=$((j+1))\n    if [ $j -ge $TRY_LOOP ]; then\n      echo >&2 \"$(date) - $host:$port still not reachable, giving up\"\n      exit 1\n    fi\n    echo \"$(date) - waiting for $name... $j/$TRY_LOOP\"\n    sleep 5\n  done\n}\n\n\nwait_for_port \"Postgres\" \"$POSTGRES_HOST\" \"$POSTGRES_PORT\"\n\nwait_for_port \"Redis\" \"$REDIS_HOST\" \"$REDIS_PORT\"\n\ncase \"$1\" in\n  webserver)\n    airflow initdb\n\t\tsleep 5\n    exec airflow webserver\n    ;;\n  worker|scheduler)\n    sleep 15\n    exec airflow \"$@\"\n    ;;\n  flower)\n    sleep 15\n    exec airflow \"$@\"\n    ;;\n  version)\n    exec airflow \"$@\"\n    ;;\n  *)\n    exec \"$@\"\n    ;;\nesac\n"
  },
  {
    "path": "dags/my_first_dag.py",
    "content": "from datetime import datetime\nimport logging\n\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\n\nimport pandas\nimport toolz\n\nlogger = logging.getLogger(__name__)\n\ndefault_args = {\n    'owner': 'nicor88',\n    'start_date': datetime(2019, 2, 20),\n    'depends_on_past': False,\n    'provide_context': True\n}\n\ndag = DAG('my_first_dag',\n          description='My first Airflow DAG',\n          schedule_interval='*/5 * * * *',\n          catchup=False,\n          default_args=default_args)\n\n\ndef task_1(**kwargs):\n    output = {'output': 'hello world 1', 'execution_time': str(datetime.now())}\n    logger.info(output)\n    logger.info(f'Pandas version: {pandas.__version__}')\n    logger.info(f'Toolz version: {toolz.__version__}')\n    return output\n\n\ndef task_2(**kwargs):\n    ti = kwargs['ti']\n    output_task_1 = ti.xcom_pull(key='return_value', task_ids='task_1')\n    logger.info(output_task_1)\n    return {'output': 'hello world 2', 'execution_time': str(datetime.now())}\n\n\ndef task_3(**kwargs):\n    logger.info('Log from task 3')\n    return {'output': 'hello world 3', 'execution_time': str(datetime.now())}\n\n\nt1 = PythonOperator(\n    task_id='task_1',\n    dag=dag,\n    python_callable=task_1\n)\n\nt2 = PythonOperator(\n    task_id='task_2',\n    dag=dag,\n    python_callable=task_2\n)\n\nt3 = PythonOperator(\n    task_id='task_3',\n    dag=dag,\n    python_callable=task_3\n)\n\nt1 >> [t2, t3]\n"
  },
  {
    "path": "dags/my_second_dag.py",
    "content": "from datetime import datetime\nimport logging\n\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\n\nimport pandas\nimport toolz\n\nlogger = logging.getLogger(__name__)\n\ndefault_args = {\n    'owner': 'nicor88',\n    'start_date': datetime(2019, 2, 20),\n    'depends_on_past': False,\n    'provide_context': True\n}\n\ndag = DAG('my_second_dag',\n          description='My second Airflow DAG',\n          schedule_interval=None,\n          catchup=False,\n          default_args=default_args)\n\n\ndef task_1(**kwargs):\n    output = {'output': 'hello world 1', 'execution_time': str(datetime.now())}\n    logger.info(output)\n    logger.info(f'Pandas version: {pandas.__version__}')\n    logger.info(f'Toolz version: {toolz.__version__}')\n    return output\n\n\ndef task_2(**kwargs):\n    ti = kwargs['ti']\n    output_task_1 = ti.xcom_pull(key='return_value', task_ids='task_1')\n    logger.info(output_task_1)\n    return {'output': 'hello world 2', 'execution_time': str(datetime.now())}\n\n\nt1 = PythonOperator(\n    task_id='task_1',\n    dag=dag,\n    python_callable=task_1\n)\nt2 = PythonOperator(\n    task_id='task_2',\n    dag=dag,\n    python_callable=task_2\n)\n\nt1 >> t2\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '3'\n\nservices:\n  redis:\n    image: 'redis:5.0.3'\n    command: redis-server\n\n  postgres:\n    image: postgres:10.4\n    environment:\n      - POSTGRES_USER=airflow\n      - POSTGRES_PASSWORD=airflow\n      - POSTGRES_DB=airflow\n    volumes:\n      - ./postgres_data:/var/lib/postgresql/data\n    ports:\n      - 5432:5432\n\n  webserver:\n    image: airflow:latest\n    restart: always\n    build: .\n    depends_on:\n      - postgres\n      - redis\n    environment:\n      - REDIS_HOST=redis\n      - REDIS_PORT=6379\n      - POSTGRES_HOST=postgres\n      - POSTGRES_PORT=5432\n      - POSTGRES_USER=airflow\n      - POSTGRES_PASSWORD=airflow\n      - POSTGRES_DB=airflow\n      - FERNET_KEY=${AIRFLOW_FERNET_KEY}\n      - AIRFLOW_BASE_URL=http://localhost:8080\n      - ENABLE_REMOTE_LOGGING=False\n      - STAGE=dev\n      - AIRFLOW__SCHEDULER__DAG_DIR_LIST_INTERVAL=15\n    volumes:\n        - ./dags:/usr/local/airflow/dags\n    ports:\n        - \"8080:8080\"\n    command: webserver\n    healthcheck:\n      test: [\"CMD-SHELL\", \"[ -f /usr/local/airflow/airflow-webserver.pid ]\"]\n      interval: 30s\n      timeout: 30s\n      retries: 3\n\n  flower:\n    image: airflow:latest\n    restart: always\n    depends_on:\n      - redis\n      - webserver\n    environment:\n      - REDIS_HOST=redis\n      - REDIS_PORT=6379\n      - POSTGRES_HOST=postgres\n      - POSTGRES_PORT=5432\n      - POSTGRES_USER=airflow\n      - POSTGRES_PASSWORD=airflow\n      - POSTGRES_DB=airflow\n      - STAGE=dev\n    ports:\n      - \"5555:5555\"\n    command: flower\n\n  scheduler:\n    image: airflow:latest\n    restart: always\n    depends_on:\n      - webserver\n    volumes:\n      - ./dags:/usr/local/airflow/dags\n    environment:\n      - REDIS_HOST=redis\n      - REDIS_PORT=6379\n      - POSTGRES_HOST=postgres\n      - POSTGRES_PORT=5432\n      - POSTGRES_USER=airflow\n      - POSTGRES_PASSWORD=airflow\n      - POSTGRES_DB=airflow\n      - FERNET_KEY=${AIRFLOW_FERNET_KEY}\n      - AIRFLOW_BASE_URL=http://localhost:8080\n      - ENABLE_REMOTE_LOGGING=False\n      - STAGE=dev\n    command: scheduler\n\n  worker:\n    image: airflow:latest\n    restart: always\n    depends_on:\n      - webserver\n      - scheduler\n    volumes:\n      - ./dags:/usr/local/airflow/dags\n    environment:\n      - REDIS_HOST=redis\n      - REDIS_PORT=6379\n      - POSTGRES_HOST=postgres\n      - POSTGRES_PORT=5432\n      - POSTGRES_USER=airflow\n      - POSTGRES_PASSWORD=airflow\n      - POSTGRES_DB=airflow\n      - FERNET_KEY=${AIRFLOW_FERNET_KEY}\n      - AIRFLOW_BASE_URL=http://localhost:8080\n      - ENABLE_REMOTE_LOGGING=False\n      - STAGE=dev\n    command: worker\n\n#  worker2:\n#    image: airflow:latest\n#    restart: always\n#    depends_on:\n#      - webserver\n#      - scheduler\n#    volumes:\n#      - ./dags:/usr/local/airflow/dags\n#    environment:\n#      - REDIS_HOST=redis\n#      - REDIS_PORT=6379\n#      - POSTGRES_HOST=postgres\n#      - POSTGRES_PORT=5432\n#      - POSTGRES_USER=airflow\n#      - POSTGRES_PASSWORD=airflow\n#      - POSTGRES_DB=airflow\n#      - FERNET_KEY=${AIRFLOW_FERNET_KEY}\n#      - AIRFLOW_BASE_URL=http://localhost:8080\n#      - ENABLE_REMOTE_LOGGING=False\n#      - STAGE=dev\n#    command: worker\n"
  },
  {
    "path": "infrastructure/airflow_flower.tf",
    "content": "resource \"aws_security_group\" \"flower\" {\n    name = \"${var.project_name}-${var.stage}-flower-sg\"\n    description = \"Allow all inbound traffic for Flower\"\n    vpc_id = aws_vpc.vpc.id\n\n    ingress {\n        from_port = 5555\n        to_port = 5555\n        protocol = \"tcp\"\n        cidr_blocks = [\"0.0.0.0/0\"]\n    }\n\n    egress {\n        from_port = 0\n        to_port = 0\n        protocol = \"-1\"\n        cidr_blocks = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-flower-sg\"\n    }\n}\n\n\nresource \"aws_ecs_task_definition\" \"flower\" {\n  family = \"${var.project_name}-${var.stage}-flower\"\n  network_mode = \"awsvpc\"\n  execution_role_arn = aws_iam_role.ecs_task_iam_role.arn\n  requires_compatibilities = [\"FARGATE\"]\n  cpu = \"512\" # the valid CPU amount for 2 GB is from from 256 to 1024\n  memory = \"1024\"\n  container_definitions = <<EOF\n[\n  {\n    \"name\": \"airflow_flower\",\n    \"image\": ${replace(jsonencode(\"${aws_ecr_repository.docker_repository.repository_url}:${var.image_version}\"), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")} ,\n    \"essential\": true,\n    \"portMappings\": [\n      {\n        \"containerPort\": 5555,\n        \"hostPort\": 5555\n      }\n    ],\n    \"command\": [\n        \"flower\"\n    ],\n    \"environment\": [\n      {\n        \"name\": \"REDIS_HOST\",\n        \"value\": ${replace(jsonencode(aws_elasticache_cluster.celery_backend.cache_nodes.0.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"REDIS_PORT\",\n        \"value\": \"6379\"\n      },\n      {\n        \"name\": \"POSTGRES_HOST\",\n        \"value\": ${replace(jsonencode(aws_db_instance.metadata_db.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"POSTGRES_PORT\",\n        \"value\": \"5432\"\n      },\n      {\n          \"name\": \"POSTGRES_USER\",\n          \"value\": \"airflow\"\n      },\n      {\n          \"name\": \"POSTGRES_PASSWORD\",\n          \"value\": ${replace(jsonencode(random_string.metadata_db_password.result), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n          \"name\": \"POSTGRES_DB\",\n          \"value\": \"airflow\"\n      },\n      {\n        \"name\": \"FERNET_KEY\",\n        \"value\": \"k8IfvPBpKOoDZSBbqHOQCgJkhXU_Y2wjwLZbJmavcXQ=\"\n      },\n      {\n        \"name\": \"AIRFLOW_BASE_URL\",\n        \"value\": \"http://localhost:8080\"\n      },\n      {\n        \"name\": \"ENABLE_REMOTE_LOGGING\",\n        \"value\": \"False\"\n      },\n      {\n        \"name\": \"STAGE\",\n        \"value\": \"${var.stage}\"\n      }\n    ],\n    \"logConfiguration\": {\n        \"logDriver\": \"awslogs\",\n        \"options\": {\n            \"awslogs-group\": \"${var.log_group_name}/${var.project_name}-${var.stage}\",\n            \"awslogs-region\": \"${var.aws_region}\",\n            \"awslogs-stream-prefix\": \"flower\"\n        }\n    }\n  }\n]\nEOF\n}\n"
  },
  {
    "path": "infrastructure/airflow_scheduler.tf",
    "content": "resource \"aws_security_group\" \"scheduler\" {\n    name = \"${var.project_name}-${var.stage}-scheduler-sg\"\n    description = \"Airflow scheduler security group\"\n    vpc_id = aws_vpc.vpc.id\n\n    egress {\n        from_port       = 0\n        to_port         = 0\n        protocol        = \"-1\"\n        cidr_blocks     = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-scheduler-sg\"\n    }\n}\n\n\nresource \"aws_ecs_task_definition\" \"scheduler\" {\n  family = \"${var.project_name}-${var.stage}-scheduler\"\n  network_mode = \"awsvpc\"\n  execution_role_arn = aws_iam_role.ecs_task_iam_role.arn\n  requires_compatibilities = [\"FARGATE\"]\n  cpu = \"1024\" # the valid CPU amount for 2 GB is from from 256 to 1024\n  memory = \"2048\"\n  container_definitions = <<EOF\n[\n  {\n    \"name\": \"airflow_scheduler\",\n    \"image\": ${replace(jsonencode(\"${aws_ecr_repository.docker_repository.repository_url}:${var.image_version}\"), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")} ,\n    \"essential\": true,\n    \"command\": [\n        \"scheduler\"\n    ],\n    \"environment\": [\n      {\n        \"name\": \"REDIS_HOST\",\n        \"value\": ${replace(jsonencode(aws_elasticache_cluster.celery_backend.cache_nodes.0.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"REDIS_PORT\",\n        \"value\": \"6379\"\n      },\n      {\n        \"name\": \"POSTGRES_HOST\",\n        \"value\": ${replace(jsonencode(aws_db_instance.metadata_db.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"POSTGRES_PORT\",\n        \"value\": \"5432\"\n      },\n      {\n          \"name\": \"POSTGRES_USER\",\n          \"value\": \"airflow\"\n      },\n      {\n          \"name\": \"POSTGRES_PASSWORD\",\n          \"value\": ${replace(jsonencode(random_string.metadata_db_password.result), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n          \"name\": \"POSTGRES_DB\",\n          \"value\": \"airflow\"\n      },\n      {\n        \"name\": \"FERNET_KEY\",\n        \"value\": \"k8IfvPBpKOoDZSBbqHOQCgJkhXU_Y2wjwLZbJmavcXQ=\"\n      },\n      {\n        \"name\": \"AIRFLOW_BASE_URL\",\n        \"value\": \"http://localhost:8080\"\n      },\n      {\n        \"name\": \"ENABLE_REMOTE_LOGGING\",\n        \"value\": \"False\"\n      },\n      {\n        \"name\": \"STAGE\",\n        \"value\": \"${var.stage}\"\n      }\n    ],\n    \"logConfiguration\": {\n        \"logDriver\": \"awslogs\",\n        \"options\": {\n            \"awslogs-group\": \"${var.log_group_name}/${var.project_name}-${var.stage}\",\n            \"awslogs-region\": \"${var.aws_region}\",\n            \"awslogs-stream-prefix\": \"scheduler\"\n        }\n    }\n  }\n]\nEOF\n}\n"
  },
  {
    "path": "infrastructure/airflow_web_server.tf",
    "content": "resource \"aws_security_group\" \"application_load_balancer\" {\n    name = \"${var.project_name}-${var.stage}-alb-web-sg\"\n    description = \"Allow all inbound traffic\"\n    vpc_id = aws_vpc.vpc.id\n\n    ingress {\n        from_port   = 80\n        to_port     = 80\n        protocol    = \"tcp\"\n        cidr_blocks = [\"0.0.0.0/0\"]\n    }\n\n    egress {\n        from_port       = 0\n        to_port         = 0\n        protocol        = \"-1\"\n        cidr_blocks     = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-alb-web-sg\"\n    }\n}\n\n\nresource \"aws_security_group\" \"web_server_ecs_internal\" {\n    name = \"${var.project_name}-${var.stage}-web-server-ecs-internal-sg\"\n    description = \"Allow all inbound traffic\"\n    vpc_id = aws_vpc.vpc.id\n\n    ingress {\n        from_port   = 8080\n        to_port     = 8080\n        protocol    = \"tcp\"\n        security_groups = [aws_security_group.application_load_balancer.id]\n        cidr_blocks = [\"0.0.0.0/0\"]\n    }\n\n    egress {\n        from_port       = 0\n        to_port         = 0\n        protocol        = \"-1\"\n        cidr_blocks     = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-web-server-ecs-internal-sg\"\n    }\n}\n\n\nresource \"aws_ecs_task_definition\" \"web_server\" {\n  family = \"${var.project_name}-${var.stage}-web-server\"\n  # container_definitions = file(\"airflow-components/web_server.json\")\n  network_mode = \"awsvpc\"\n  execution_role_arn = aws_iam_role.ecs_task_iam_role.arn\n  requires_compatibilities = [\"FARGATE\"]\n  cpu = \"1024\" # the valid CPU amount for 2 GB is from from 256 to 1024\n  memory = \"2048\"\n  container_definitions = <<EOF\n[\n  {\n    \"name\": \"airflow_web_server\",\n    \"image\": ${replace(jsonencode(\"${aws_ecr_repository.docker_repository.repository_url}:${var.image_version}\"), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")} ,\n    \"essential\": true,\n    \"portMappings\": [\n      {\n        \"containerPort\": 8080,\n        \"hostPort\": 8080\n      }\n    ],\n    \"command\": [\n        \"webserver\"\n    ],\n    \"environment\": [\n      {\n        \"name\": \"REDIS_HOST\",\n        \"value\": ${replace(jsonencode(aws_elasticache_cluster.celery_backend.cache_nodes.0.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"REDIS_PORT\",\n        \"value\": \"6379\"\n      },\n      {\n        \"name\": \"POSTGRES_HOST\",\n        \"value\": ${replace(jsonencode(aws_db_instance.metadata_db.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"POSTGRES_PORT\",\n        \"value\": \"5432\"\n      },\n      {\n          \"name\": \"POSTGRES_USER\",\n          \"value\": \"airflow\"\n      },\n      {\n          \"name\": \"POSTGRES_PASSWORD\",\n          \"value\": ${replace(jsonencode(random_string.metadata_db_password.result), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n          \"name\": \"POSTGRES_DB\",\n          \"value\": \"airflow\"\n      },\n      {\n        \"name\": \"FERNET_KEY\",\n        \"value\": \"k8IfvPBpKOoDZSBbqHOQCgJkhXU_Y2wjwLZbJmavcXQ=\"\n      },\n      {\n        \"name\": \"AIRFLOW_BASE_URL\",\n        \"value\": \"http://localhost:8080\"\n      },\n      {\n        \"name\": \"ENABLE_REMOTE_LOGGING\",\n        \"value\": \"False\"\n      },\n      {\n        \"name\": \"STAGE\",\n        \"value\": \"${var.stage}\"\n      }\n    ],\n    \"logConfiguration\": {\n        \"logDriver\": \"awslogs\",\n        \"options\": {\n            \"awslogs-group\": \"${var.log_group_name}/${var.project_name}-${var.stage}\",\n            \"awslogs-region\": \"${var.aws_region}\",\n            \"awslogs-stream-prefix\": \"web_server\"\n        }\n    }\n  }\n]\nEOF\n}\n"
  },
  {
    "path": "infrastructure/airflow_web_server_lb.tf",
    "content": "resource \"aws_alb\" \"airflow_alb\" {\n  name            = \"${var.project_name}-${var.stage}-alb\"\n  subnets         = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n  security_groups = [aws_security_group.application_load_balancer.id]\n}\n\nresource \"aws_alb_target_group\" \"airflow_web_server\" {\n    name        = \"${var.project_name}-${var.stage}-web-server\"\n    port        = 8080\n    protocol    = \"HTTP\"\n    vpc_id      = aws_vpc.vpc.id\n    target_type = \"ip\"\n\n    health_check {\n        interval = 10\n        port = 8080\n        protocol = \"HTTP\"\n        path = \"/health\"\n        timeout = 5\n        healthy_threshold = 5\n        unhealthy_threshold = 3\n    }\n}\n\n# port exposed from the application load balancer\nresource \"aws_alb_listener\" \"airflow_web_server\" {\n    load_balancer_arn = aws_alb.airflow_alb.id\n    port = \"80\"\n    protocol = \"HTTP\"\n\n    default_action {\n        target_group_arn = aws_alb_target_group.airflow_web_server.id\n        type = \"forward\"\n    }\n}\n"
  },
  {
    "path": "infrastructure/airflow_workers.tf",
    "content": "resource \"aws_security_group\" \"workers\" {\n    name = \"${var.project_name}-${var.stage}-workers-sg\"\n    description = \"Airflow Celery Workers security group\"\n    vpc_id = aws_vpc.vpc.id\n\n    ingress {\n        from_port = 8793\n        to_port = 8793\n        protocol = \"tcp\"\n        cidr_blocks = [\"${var.base_cidr_block}/16\"]\n    }\n\n    egress {\n        from_port = 0\n        to_port = 0\n        protocol = \"-1\"\n        cidr_blocks = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-workers-sg\"\n    }\n}\n\n\nresource \"aws_ecs_task_definition\" \"workers\" {\n  family = \"${var.project_name}-${var.stage}-workers\"\n  network_mode = \"awsvpc\"\n  execution_role_arn = aws_iam_role.ecs_task_iam_role.arn\n  requires_compatibilities = [\"FARGATE\"]\n  cpu = \"512\"\n  memory = \"2048\" # the valid CPU amount for 2 GB is from from 256 to 1024\n  container_definitions = <<EOF\n[\n  {\n    \"name\": \"airflow_workers\",\n    \"image\": ${replace(jsonencode(\"${aws_ecr_repository.docker_repository.repository_url}:${var.image_version}\"), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")} ,\n    \"essential\": true,\n    \"portMappings\": [\n      {\n        \"containerPort\": 8793,\n        \"hostPort\": 8793\n      }\n    ],\n    \"command\": [\n        \"worker\"\n    ],\n    \"environment\": [\n      {\n        \"name\": \"REDIS_HOST\",\n        \"value\": ${replace(jsonencode(aws_elasticache_cluster.celery_backend.cache_nodes.0.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"REDIS_PORT\",\n        \"value\": \"6379\"\n      },\n      {\n        \"name\": \"POSTGRES_HOST\",\n        \"value\": ${replace(jsonencode(aws_db_instance.metadata_db.address), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n        \"name\": \"POSTGRES_PORT\",\n        \"value\": \"5432\"\n      },\n      {\n          \"name\": \"POSTGRES_USER\",\n          \"value\": \"airflow\"\n      },\n      {\n          \"name\": \"POSTGRES_PASSWORD\",\n          \"value\": ${replace(jsonencode(random_string.metadata_db_password.result), \"/\\\"([0-9]+\\\\.?[0-9]*)\\\"/\", \"$1\")}\n      },\n      {\n          \"name\": \"POSTGRES_DB\",\n          \"value\": \"airflow\"\n      },\n      {\n        \"name\": \"FERNET_KEY\",\n        \"value\": \"k8IfvPBpKOoDZSBbqHOQCgJkhXU_Y2wjwLZbJmavcXQ=\"\n      },\n      {\n        \"name\": \"AIRFLOW_BASE_URL\",\n        \"value\": \"http://localhost:8080\"\n      },\n      {\n        \"name\": \"ENABLE_REMOTE_LOGGING\",\n        \"value\": \"False\"\n      },\n      {\n        \"name\": \"STAGE\",\n        \"value\": \"${var.stage}\"\n      }\n    ],\n    \"logConfiguration\": {\n        \"logDriver\": \"awslogs\",\n        \"options\": {\n            \"awslogs-group\": \"${var.log_group_name}/${var.project_name}-${var.stage}\",\n            \"awslogs-region\": \"${var.aws_region}\",\n            \"awslogs-stream-prefix\": \"workers\"\n        }\n    }\n  }\n]\nEOF\n}\n"
  },
  {
    "path": "infrastructure/config.tf",
    "content": "variable \"aws_region\" {\n   default = \"us-east-1\"\n}\n\nvariable \"availability_zones\" {\n   type    = list(string)\n   default = [\"us-east-1a\", \"us-east-1b\", \"us-east-1c\"]\n}\n\nvariable \"project_name\" {\n   default = \"airflow\"\n}\n\nvariable \"stage\" {\n   default = \"dev\"\n}\n\nvariable \"base_cidr_block\" {\n   default = \"10.0.0.0\"\n}\n\nvariable \"log_group_name\" {\n   default = \"ecs/fargate\"\n}\n\nvariable \"image_version\" {\n   default = \"latest\"\n}\n\nvariable \"metadata_db_instance_type\" {\n   default = \"db.t2.micro\"\n}\n\nvariable \"celery_backend_instance_type\" {\n   default = \"cache.t2.small\"\n}"
  },
  {
    "path": "infrastructure/ecs.tf",
    "content": "resource \"aws_ecr_repository\" \"docker_repository\" {\n    name = \"${var.project_name}-${var.stage}\"\n}\n\nresource \"aws_ecr_lifecycle_policy\" \"docker_repository_lifecycly\" {\n  repository = aws_ecr_repository.docker_repository.name\n\n  policy = <<EOF\n{\n    \"rules\": [\n        {\n            \"rulePriority\": 1,\n            \"description\": \"Keep only the latest 5 images\",\n            \"selection\": {\n                \"tagStatus\": \"any\",\n                \"countType\": \"imageCountMoreThan\",\n                \"countNumber\": 5\n            },\n            \"action\": {\n                \"type\": \"expire\"\n            }\n        }\n    ]\n}\nEOF\n}\n\nresource \"aws_ecs_cluster\" \"ecs_cluster\" {\n  name = \"${var.project_name}-${var.stage}\"\n}\n\nresource \"aws_cloudwatch_log_group\" \"log_group\" {\n  name = \"${var.log_group_name}/${var.project_name}-${var.stage}\"\n  retention_in_days = 5\n}\n\nresource \"aws_iam_role\" \"ecs_task_iam_role\" {\n  name = \"${var.project_name}-${var.stage}-ecs-task-role\"\n  description = \"Allow ECS tasks to access AWS resources\"\n\n  assume_role_policy = <<EOF\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"\",\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"Service\": \"ecs-tasks.amazonaws.com\"\n      },\n      \"Action\": \"sts:AssumeRole\"\n    }\n  ]\n}\nEOF\n}\n\n\nresource \"aws_iam_policy\" \"ecs_task_policy\" {\n  name        = \"${var.project_name}-${var.stage}\"\n\n  policy = <<EOF\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Action\": [\n        \"ecr:GetAuthorizationToken\",\n        \"ecr:BatchCheckLayerAvailability\",\n        \"ecr:GetDownloadUrlForLayer\",\n        \"ecr:BatchGetImage\"\n      ],\n      \"Effect\": \"Allow\",\n      \"Resource\": \"*\"\n    },\n    {\n      \"Action\": [\n        \"logs:CreateLogStream\",\n        \"logs:PutLogEvents\"\n      ],\n      \"Effect\": \"Allow\",\n      \"Resource\": \"*\"\n    }\n  ]\n}\nEOF\n}\n\nresource \"aws_iam_role_policy_attachment\" \"attach_policy\" {\n  role       = aws_iam_role.ecs_task_iam_role.name\n  policy_arn = aws_iam_policy.ecs_task_policy.arn\n}\n"
  },
  {
    "path": "infrastructure/ecs_services.tf",
    "content": "resource \"aws_ecs_service\" \"web_server_service\" {\n    name = \"${var.project_name}-${var.stage}-web-server\"\n    cluster = aws_ecs_cluster.ecs_cluster.id\n    task_definition = aws_ecs_task_definition.web_server.arn\n    desired_count = 1\n    launch_type = \"FARGATE\"\n    deployment_maximum_percent = 200\n    deployment_minimum_healthy_percent = 100\n    health_check_grace_period_seconds = 60\n\n    network_configuration {\n        security_groups = [aws_security_group.web_server_ecs_internal.id]\n        subnets = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n        assign_public_ip = true\n    }\n\n    load_balancer {\n        target_group_arn = aws_alb_target_group.airflow_web_server.id\n        container_name = \"airflow_web_server\"\n        container_port = 8080\n    }\n\n    depends_on = [\n        aws_db_instance.metadata_db,\n        aws_elasticache_cluster.celery_backend,\n        aws_alb_listener.airflow_web_server,\n    ]\n}\n\nresource \"aws_ecs_service\" \"scheduler_service\" {\n    name = \"${var.project_name}-${var.stage}-scheduler\"\n    cluster = aws_ecs_cluster.ecs_cluster.id\n    task_definition = aws_ecs_task_definition.scheduler.arn\n    desired_count = 1 \n    launch_type = \"FARGATE\"\n    \n    network_configuration {\n        security_groups = [aws_security_group.scheduler.id]\n        subnets = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n        assign_public_ip = true # when using a NAT can be put to false, or when ECS Private Link is enabled\n    }\n\n    depends_on = [\n        aws_db_instance.metadata_db,\n        aws_elasticache_cluster.celery_backend,\n    ]\n}\n\nresource \"aws_ecs_service\" \"workers_service\" {\n    name = \"${var.project_name}-${var.stage}-workers\"\n    cluster = aws_ecs_cluster.ecs_cluster.id\n    task_definition = aws_ecs_task_definition.workers.arn\n    desired_count = 2\n    launch_type = \"FARGATE\"\n\n    network_configuration {\n        security_groups = [aws_security_group.workers.id]\n        subnets = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n        assign_public_ip = true # when using a NAT can be put to false, or when ECS Private Link is enabled\n    }\n\n    depends_on = [\n        aws_db_instance.metadata_db,\n        aws_elasticache_cluster.celery_backend,\n    ]\n}\n\nresource \"aws_ecs_service\" \"flower_service\" {\n    name = \"${var.project_name}-${var.stage}-flower\"\n    cluster = aws_ecs_cluster.ecs_cluster.id\n    task_definition = aws_ecs_task_definition.flower.arn\n    desired_count = 1 \n    launch_type = \"FARGATE\"\n\n    network_configuration {\n        security_groups = [aws_security_group.flower.id]\n        subnets = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n        assign_public_ip = true\n    }\n\n    depends_on = [\n        aws_db_instance.metadata_db,\n        aws_elasticache_cluster.celery_backend,\n    ]\n}\n"
  },
  {
    "path": "infrastructure/network.tf",
    "content": "# VPC\nresource \"aws_vpc\" \"vpc\" {\n  cidr_block       = \"${var.base_cidr_block}/16\"\n\n  enable_dns_support = \"true\"\n  enable_dns_hostnames  = \"true\"\n\n  tags = {\n    Name = \"${var.project_name}-${var.stage}-vpc\"\n  }\n}\n\n# Internet Gateway\nresource \"aws_internet_gateway\" \"igw\" {\n  vpc_id = aws_vpc.vpc.id\n\n  tags = {\n    Name = \"${var.project_name}-${var.stage}-igw\"\n  }\n}\n\n# Public routing table\nresource \"aws_route_table\" \"public-route-table\" {\n  vpc_id = aws_vpc.vpc.id\n\n  route {\n    cidr_block = \"0.0.0.0/0\"\n    gateway_id = aws_internet_gateway.igw.id\n  }\n\n  tags = {\n    Name = \"${var.project_name}-${var.stage}-public-route\"\n  }\n}\n\n# Subnets\nresource \"aws_subnet\" \"public-subnet-1\" {\n    vpc_id = aws_vpc.vpc.id\n\n    cidr_block = \"10.0.1.0/24\"\n    availability_zone =  var.availability_zones[0]\n\n    map_public_ip_on_launch = true\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-public-subnet-1\"\n    }\n}\n\nresource \"aws_route_table_association\" \"public-subnet-1-public-route-association\" {\n    subnet_id = aws_subnet.public-subnet-1.id\n    route_table_id = aws_route_table.public-route-table.id\n}\n\nresource \"aws_subnet\" \"public-subnet-2\" {\n    vpc_id = aws_vpc.vpc.id\n\n    cidr_block = \"10.0.2.0/24\"\n    availability_zone =  var.availability_zones[1]\n    map_public_ip_on_launch = true\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-public-subnet-2\"\n    }\n}\n\nresource \"aws_route_table_association\" \"public-subnet-2-public-route-association\" {\n    subnet_id = aws_subnet.public-subnet-2.id\n    route_table_id = aws_route_table.public-route-table.id\n}\n\nresource \"aws_subnet\" \"public-subnet-3\" {\n    vpc_id = aws_vpc.vpc.id\n\n    cidr_block = \"10.0.3.0/24\"\n    availability_zone =  var.availability_zones[2]\n    map_public_ip_on_launch = true\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-public-subnet-3\"\n    }\n}\n\nresource \"aws_route_table_association\" \"public-subnet-3-public-route-association\" {\n    subnet_id = aws_subnet.public-subnet-3.id\n    route_table_id = aws_route_table.public-route-table.id\n}\n"
  },
  {
    "path": "infrastructure/output.tf",
    "content": "output \"metadata_db_postgres_password\" {\n  value = \"${random_string.metadata_db_password.result}\"\n}\n\noutput \"metadata_db_postgres_endpoint\" {\n  value = \"${aws_db_instance.metadata_db.endpoint}\"\n}\n\noutput \"metadata_db_postgres_address\" {\n  value = \"${aws_db_instance.metadata_db.address}\"\n}\n\noutput \"celery_backend_address\" {\n  value = \"${aws_elasticache_cluster.celery_backend.cache_nodes.0.address}\"\n}\n\noutput \"airflow_web_server_endpoint\" {\n  value = \"${aws_alb.airflow_alb.dns_name}\"\n} \n\n"
  },
  {
    "path": "infrastructure/postgres.tf",
    "content": "resource \"random_string\" \"metadata_db_password\" {\n  length = 32\n  upper = true\n  number = true\n  special = false\n}\n\nresource \"aws_security_group\" \"postgres_public\" {\n    name = \"${var.project_name}-${var.stage}-postgres-public-sg\"\n    description = \"Allow all inbound for Postgres\"\n    vpc_id = aws_vpc.vpc.id\n\n    ingress {\n        from_port   = 5432\n        to_port     = 5432\n        protocol    = \"tcp\"\n        cidr_blocks = [\"0.0.0.0/0\"]\n    }\n\n    ingress {\n        from_port   = 5432\n        to_port     = 5432\n        protocol    = \"tcp\"\n        cidr_blocks = [\"${var.base_cidr_block}/16\"]\n    }\n\n    egress {\n        from_port       = 0\n        to_port         = 0\n        protocol        = \"-1\"\n        cidr_blocks     = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-postgres-public-sg\"\n    }\n}\n\nresource \"aws_db_subnet_group\" \"airflow_subnet_group\" {\n    name = \"${var.project_name}-${var.stage}\"\n    subnet_ids = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-subnet-group\"\n    }\n}\n\nresource \"aws_db_instance\" \"metadata_db\" {\n    identifier = \"${var.project_name}-${var.stage}-postgres\"\n    \n    # database name \n    name = var.project_name\n    instance_class = var.metadata_db_instance_type\n    allocated_storage = 20\n    engine = \"postgres\"\n    engine_version = \"10.6\"\n    skip_final_snapshot = true\n    publicly_accessible = true\n    db_subnet_group_name = aws_db_subnet_group.airflow_subnet_group.id\n    vpc_security_group_ids = [aws_security_group.postgres_public.id]\n    username = var.project_name\n    password = random_string.metadata_db_password.result\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-postgres\"\n    }\n}\n"
  },
  {
    "path": "infrastructure/provider.tf",
    "content": "# provider\nprovider \"aws\" {\n  region = var.aws_region\n}\n"
  },
  {
    "path": "infrastructure/redis.tf",
    "content": "resource \"aws_security_group\" \"redis_vpc\" {\n    name = \"${var.project_name}-${var.stage}-redis-vpc-sg\"\n    description = \"Allow all inbound traffic\"\n    vpc_id = aws_vpc.vpc.id\n\n    ingress {\n        from_port   = 6379\n        to_port     = 6379\n        protocol    = \"tcp\"\n        cidr_blocks = [\"${var.base_cidr_block}/16\"]\n    }\n\n    egress {\n        from_port       = 0\n        to_port         = 0\n        protocol        = \"-1\"\n        cidr_blocks     = [\"0.0.0.0/0\"]\n    }\n\n    tags = {\n        Name = \"${var.project_name}-${var.stage}-redis-vpc-sg\"\n    }\n}\n\nresource \"aws_elasticache_subnet_group\" \"airflow_redis_subnet_group\" {\n    name       = \"${var.project_name}-${var.stage}\"\n    subnet_ids = [aws_subnet.public-subnet-1.id, aws_subnet.public-subnet-2.id, aws_subnet.public-subnet-3.id]\n}\n\n\nresource \"aws_elasticache_cluster\" \"celery_backend\" {\n    cluster_id = \"${var.project_name}-${var.stage}\"\n    engine = \"redis\"\n    engine_version = \"4.0.10\"\n    node_type = var.celery_backend_instance_type\n    num_cache_nodes = 1\n    port = \"6379\"\n    subnet_group_name = aws_elasticache_subnet_group.airflow_redis_subnet_group.id\n    security_group_ids = [aws_security_group.redis_vpc.id]\n}\n"
  },
  {
    "path": "plugins/my_first_operator.py",
    "content": "import logging\n\nfrom airflow.models import BaseOperator\nfrom airflow.plugins_manager import AirflowPlugin\nfrom airflow.utils.decorators import apply_defaults\n\nlogger = logging.getLogger('airflow.my_first_operator')\n\nclass MyFirstOperator(BaseOperator):\n\n    @apply_defaults\n    def __init__(self, my_operator_param, *args, **kwargs):\n        self.operator_param = my_operator_param\n        super(MyFirstOperator, self).__init__(*args, **kwargs)\n\n    def execute(self, context):\n        logger.info('Hello World!')\n        logger.info('operator_param: %s', self.operator_param)\n\nclass MyFirstPlugin(AirflowPlugin):\n    name = 'my_first_plugin'\n    operators = [MyFirstOperator]\n"
  },
  {
    "path": "requirements.txt",
    "content": "snowflake-connector-python==2.3.2\ntoolz==0.10.0\ncattrs==1.0.0\n"
  },
  {
    "path": "scripts/deploy.sh",
    "content": "#!/usr/bin/env bash\n\nIMAGE_NAME=$1\n# TODO generate a random string\n\nCOMMIT_HASH=$(hexdump -n 16 -v -e '/1 \"%02X\"' -e '/16 \"\\n\"' /dev/urandom)\n\necho $COMMIT_HASH\n\n### ECR - build images and push to remote repository\n\necho \"Building image: $IMAGE_NAME:latest\"\n\ndocker build --rm -t $IMAGE_NAME:latest .\n\neval $(aws ecr get-login --no-include-email)\n\n# tag and push image using latest\ndocker tag $IMAGE_NAME $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:latest\ndocker push $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:latest\n\n# tag and push image with commit hash\ndocker tag $IMAGE_NAME $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:$COMMIT_HASH\ndocker push $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:$COMMIT_HASH\n\ncd infrastructure\nterraform apply -var \"image_version=$COMMIT_HASH\" -auto-approve\n"
  },
  {
    "path": "scripts/push_to_ecr.sh",
    "content": "#!/usr/bin/env bash\n\nIMAGE_NAME=$1\n\n### ECR - build images and push to remote repository\n\necho \"Building image: $IMAGE_NAME:latest\"\n\ndocker build --rm -t $IMAGE_NAME:latest .\n\neval $(aws ecr get-login --no-include-email)\n\n# tag and push image using latest\ndocker tag $IMAGE_NAME $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:latest\ndocker push $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:latest\n\n# tag and push image with commit hash\nCOMMIT_HASH=\"init\"\ndocker tag $IMAGE_NAME $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:$COMMIT_HASH\ndocker push $AWS_ACCOUNT.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME:$COMMIT_HASH\n"
  }
]