본문 바로가기

개발노트/MAC

aws-cli 이용하여 특정 tag 에 해당하는 ec2 instance 의 private IP 알아내기

AWS 매뉴얼을 확인하면 된다

https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html

 

describe-instances — AWS CLI 1.18.97 Command Reference

Note: You are viewing the documentation for an older major version of the AWS CLI (version 1). AWS CLI version 2, the latest major version of AWS CLI, is now stable and recommended for general use. To view this page for the AWS CLI version 2, click here. F

docs.aws.amazon.com

좀 더 편하게 찾고 싶어서 간단한 (z)shell script 함수를 만들어 쓰고 있다.

ec2-ip() {
  # $1 : AppName e.g. cxxxx-api, rxxxx-api
  # $2 : Envirionment e.g. development, test
  echo '$1 : ' $1
  echo '$2 : ' $2

  if [ -z $2 ]; then
    echo "[Error] Environment is required"
    return -1;
  fi

  service_name="fake_service_name"
  aws ec2 describe-instances --filters "Name=tag:AppName,Values=$1" "Name=tag:Environment,Values=$2" "Name=tag:ServiceName,Values=$service_name" | jq '.Reservations[].Instances[].NetworkInterfaces[].PrivateIpAddress' | sed 's/"//g' | head -n 1
}

보안상, API 를 제공하고 있는 ec2 instance 에 접속을 하려면 VDI 를 통해서만 가능하다. CodePipeline 에서 배포될 때 마다 새로운 ec2 인스턴스가 생성되기 때문에 매번 VPC 에서 쓰이는 private IP 가 바뀌는데 이를 확인하려면 매번 MFA 를 거쳐서 aws console web 에 접속해서 클릭 몇번해야 확인할 수 있다. 1password 를 쓰고 있어서 로그인이 크게 불편한 건 아니지만, 매번 하는 이 과정이 다소 번거롭게 느껴지게 돼서 그냥 이렇게 사용해볼까 하고 했는데, 의외로 편하다 ㅎㅎ

반응형