"""Conftest for asset_copy_worker""" from typing import Any import boto3 import pytest from mypy_boto3_ec2.client import EC2Client from src.config import APPLICATION_NAME, ENVIRONMENT @pytest.fixture def get_aws_region() -> str: return "us-east-1" def get_vpc_id(ec2_client: EC2Client) -> str | None: """Get VPC corresponding to environment.""" response = ec2_client.describe_vpcs( Filters=[ { "Name": "tag:Name", "Values": [ "prod", ], }, ], ) if response["Vpcs"]: vpc_id = response["Vpcs"][0]["VpcId"] return vpc_id return None def get_security_group(vpc_id: str, ec2_client: EC2Client) -> str | None: """Returns security group corresponding to service.""" security_group_name = "{}-{}-task-security-group".format( ENVIRONMENT, APPLICATION_NAME ) response = ec2_client.describe_security_groups( Filters=[ { "Name": "group-name", "Values": [ security_group_name, ], }, { "Name": "vpc-id", "Values": [ vpc_id, ], }, ], ) if response["SecurityGroups"]: """ Infrastructure automation enforces uniqueness, but just in case, pick the first returned group """ security_group_id = response["SecurityGroups"][0]["GroupId"] return security_group_id return None def get_subnets(vpc_id: str, ec2_client: EC2Client) -> list[str] | None: """Returns subnet IDs with most available IP addresses.""" response = ec2_client.describe_subnets( Filters=[ { "Name": "tag:Name", "Values": [ "*private*", ], }, { "Name": "tag:tier", "Values": [ "private", ], }, { "Name": "vpc-id", "Values": [ vpc_id, ], }, ], ) if response["Subnets"]: """ Find and return up to two subnets with the most available IP addresses """ sorted_subnets = sorted( response["Subnets"], key=lambda k: k["AvailableIpAddressCount"], reverse=True, ) subnet_ids = [subnet["SubnetId"] for subnet in sorted_subnets] return subnet_ids[0:2] return None @pytest.fixture def get_network_config(get_aws_region: str) -> dict[Any, Any] | None: """Return network configuration for fargate.""" ec2_client = boto3.client("ec2", region_name=get_aws_region) vpc_id = get_vpc_id(ec2_client) if vpc_id: return { "awsvpcConfiguration": { "subnets": get_subnets(vpc_id, ec2_client), "securityGroups": [get_security_group(vpc_id, ec2_client)], "assignPublicIp": "DISABLED", } } return None