๐Ÿ•ฐ๏ธ ์ž‘์„ฑ์ผ : 2025.02.18

Q : VPC์— ๋งคํ•‘๋˜์ง€ ์•Š์€ Lambda์˜ ๊ณต์ธ IP ์ฃผ์†Œ๋Š” ์–ด๋–ป๊ฒŒ ๋˜๋‚˜์š”? ๋งŒ์•ฝ ๊ณต์ธ IP๊ฐ€ ๋ณ€๊ฒฝ๋œ๋‹ค๋ฉด ๋ณ€๊ฒฝ ์ฃผ๊ธฐ๋Š” ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?

A-1. Lambda์˜ ๊ณต์ธ IP ์ฃผ์†Œ ๋Œ€์—ญ

The IP 3.34.124.213 belongs to the AWS service: AMAZON

A-2. Lambda์˜ IP ๋ณ€๊ฒฝ์€ ์ƒˆ๋กœ์šด ์ปดํ“จํŒ… ๋ฆฌ์†Œ์Šค๊ฐ€ ์ƒ์„ฑ๋˜๋Š” Cold Start ๋ฐœ์ƒ ์‹œ IP๊ฐ€ ๋ฐ”๋€Œ๋Š” ์‚ฌํ•ญ์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ƒํ™ฉ 1 - 1๋ถ„ ๋งˆ๋‹ค Lambda๋ฅผ ํ˜ธ์ถœ ํ–ˆ์„ ๊ฒฝ์šฐ(Warm Start)

image.png

์ƒํ™ฉ 2 - 10๋ถ„ ๋งˆ๋‹ค Lambda๋ฅผ ํ˜ธ์ถœ ํ–ˆ์„ ๊ฒฝ์šฐ(Cold Start)

image.png

์ฐธ๊ณ  - Lambda์—์„œ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ

import json
from urllib.request import urlopen
import requests
import json
import ipaddress
import os

def get_ip():
    response = urlopen('<https://api.ipify.org>').read().decode('utf8')
    print(f"Your IP Address is: {response}")

    return response

def check_ip_in_range(ip, ip_range):
    return ipaddress.ip_address(ip) in ipaddress.ip_network(ip_range)

def get_service_for_ip(ip, region):
    # Download the AWS IP ranges file
    response = requests.get('<https://ip-ranges.amazonaws.com/ip-ranges.json>')
    ip_ranges = json.loads(response.text)

    # Check each prefix in the specified region
    for prefix in ip_ranges['prefixes']:
        if prefix['region'] == region:
            if check_ip_in_range(ip, prefix['ip_prefix']):
                return prefix['service']

    # If no match is found
    return "No matching service found"

def lambda_handler(event, context):

    if not os.path.exists('/tmp/warm.txt'):
        print("This is a cold start")
        with open('/tmp/warm.txt', 'w') as f:
            f.write('warm')
    else:
        print("This is a warm start")
        
    ip_to_check = get_ip();
    region = "ap-northeast-2"

    service = get_service_for_ip(ip_to_check, region)
    print(f"The IP {ip_to_check} belongs to the AWS service: {service}")