[AWS] Lambda에서 ElastiCache 접근 시 Timeout
문의 사항
안녕하십니까?
Lambda에서 ElastiCache(Redis)로 연결하는데 timeout 오류가 발생합니다.
VPC 및 Security Group 설정 문제인지 확인 부탁드립니다.
답변
안녕하세요.
■ 문의내용
Lambda 와 ElastiCache 구성 후 연결 간 timeout 이 발생하는 부분에 대해 문의 주신 것으로 확인하였습니다.
■ 답변내용
우선 구성을 먼저 살펴보았습니다.
Lambda 의 경우 VPC 구성이 되어 있지 않으며
ElastiCache 의 경우 vpc-0000, nat가 붙은 Private subnet, sg-0000 / dev-was-sg 에 대해서만 허용된 보안 그룹으로 셋팅 되어 있습니다.
Lambda 와 VPC 내부의 리소스를 연결하기 위해서는 Lambda 또한 VPC 에 연결이 되어야 하며 관련 자료가 있는 re:post 링크를 전달 드리니 참고하여 진행해보시기 바랍니다.[1]
VPC 설정 중 아래와 같은 오류가 발생할 수 있습니다.
The provided execution role does not have permissions to call CreateNetworkInterface on EC2
해당 에러의 경우 권한 탭 아래의 Lambda 실행 역할에 사용자 지정 인라인 정책을 추가하면 이 문제를 해결할 수 있습니다.
다음을 추가하세요.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeNetworkInterfaces",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeInstances",
"ec2:AttachNetworkInterface"
],
"Resource": "*"
}
]
}
이후 Connection closed by server 에러가 발생한다면 전송 중 암호화 가 설정되어 있는지 확인 하고 설정되어 있다면 redis 연결시 ssl 옵션을 설정해 보시기 바랍니다.
r = redis.Redis(host=redis_host, port=redis_port, ssl=True, decode_responses=True)
{
"errorMessage": "Connection closed by server.",
"errorType": "ConnectionError",
"requestId": "-",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 12, in lambda_handler\n value = r.get('SYSTEM_SHUTDOWN')\n",
" File \"/opt/python/redis/commands/core.py\", line 1829, in get\n return self.execute_command(\"GET\", name)\n",
" File \"/opt/python/redis/client.py\", line 533, in execute_command\n conn = self.connection or pool.get_connection(command_name, **options)\n",
" File \"/opt/python/redis/connection.py\", line 1086, in get_connection\n connection.connect()\n",
" File \"/opt/python/redis/connection.py\", line 276, in connect\n self.on_connect()\n",
" File \"/opt/python/redis/connection.py\", line 379, in on_connect\n self.read_response()\n",
" File \"/opt/python/redis/connection.py\", line 500, in read_response\n response = self._parser.read_response(disable_decoding=disable_decoding)\n",
" File \"/opt/python/redis/_parsers/resp2.py\", line 15, in read_response\n result = self._read_response(disable_decoding=disable_decoding)\n",
" File \"/opt/python/redis/_parsers/resp2.py\", line 25, in _read_response\n raw = self._buffer.readline()\n",
" File \"/opt/python/redis/_parsers/socket.py\", line 115, in readline\n self._read_from_socket()\n",
" File \"/opt/python/redis/_parsers/socket.py\", line 68, in _read_from_socket\n raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)\n"
]
}
■ 참고
[1] https://repost.aws/ko/knowledge-center/connect-lambda-to-an-rds-instance
감사합니다.