배포할 ec2의 IP 가져오기

Glen·2023년 7월 7일
0
post-thumbnail

목적

  • CD 단계에서 빌드한 파일을 전송하려고 할때 jenkins에서 publish 플러그인을 사용한다면 인스턴스마다 일일히 설정해줘야한다.
  • 이때 만약 미리 생성된 인스턴스가 재생성되었을때 설정한 ip를 수정해줘야 한다.
  • 해당 ip를 동적으로 관리할 수 있도록 설정.

조건

  • 인스턴스는의 미리 생성되어있다.
  • VPC와 인스턴스 이름은 변하지 않는다.
    • 변한다면 pipeline script에서 동일하게 수정하면 됨.
  • jenkins와 배포할 환경은 다른 어카운트로 구성되어있다.

jenkins pipeline

  • 먼저 def로 python 실행에 대한 결과를 받도록 함수 선언함.
    • ${vpc} ${Inst}는 evn 변수로 선언해둠.
  • 아래에서 환경변수에 함수 실행결과를 저장.
  • 이후 빌드한 파일을 전송할때 환경변수의 값을 사용
      steps {
                script {
                    def ssh = sh(returnStdout: true, script: 'python3 ~/ip.py ${vpc} ${Inst}').trim()
                    env.host_a = ssh
                    
                    echo "${env.host_a}"
                }
            }
			
			steps {
                sh 'scp -o StrictHostKeyChecking=no -i ${SSH_KEY} -v ./${ARTIFACT_NAME} ${SSH_USER}@${host_a}:${SSH_TARGET_PATH}'
            }

python

  • 사용법
    • python3 search_ip.py <vpc_name> <instance_name>
#search_ip.py
import boto3
from botocore.exceptions import NoCredentialsError
import subprocess
import sys

# AssumeRole을 실행할 클라이언트 생성
sts_client = boto3.client('sts')

# AssumeRole에 필요한 정보 설정
role_arn = 'arn:aws:iam::111111111111:role/<role-name>'  # AssumeRole을 수행할 IAM 역할의 ARN
session_name = 'deploy_worker'  # 생성할 세션의 이름

# AssumeRole 요청 보내기
response = sts_client.assume_role(RoleArn=role_arn, RoleSessionName=session_name)

# AssumeRole 결과에서 임시 보안 자격 증명 가져오기
credentials = response['Credentials']
access_key = credentials['AccessKeyId']
secret_access_key = credentials['SecretAccessKey']
session_token = credentials['SessionToken']
expiration = credentials['Expiration']

# 임시 보안 자격 증명 사용하여 새로운 클라이언트 생성
assumed_role_client = boto3.client('ec2',
    aws_access_key_id=access_key,
    aws_secret_access_key=secret_access_key,
    aws_session_token=session_token
)

def get_vpc_list():
    response = assumed_role_client.describe_vpcs()
    vpc_list = []
    for vpc in response['Vpcs']:
        if 'Tags' in vpc:
            for tag in vpc['Tags']:
                if tag['Key'] == 'Name':
                    vpc_list.append((tag['Value'], vpc['VpcId']))
    return vpc_list

def select_vpc(vpc_list,vpc_name):
    for i, vpc in enumerate(vpc_list):
        if vpc[0] == vpc_name:
            vpc_index = i
    return vpc_list[vpc_index]

def get_instance_list(vpc_id):
    response = assumed_role_client.describe_instances(Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}])
    instance_list = []
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            if 'Tags' in instance:
                for tag in instance['Tags']:
                    if tag['Key'] == 'Name':
                        instance_list.append((tag['Value'], instance['PrivateIpAddress']))
    return instance_list

def main(v_name,i_name):
    vpc_list = get_vpc_list()
    vpc_name, vpc_id = select_vpc(vpc_list,v_name)
    instance_list = get_instance_list(vpc_id)

    # 인스턴스 이름과 일치하는 경우 해당 인스턴스의 IP 주소를 출력
    for instance_name, instance_ip in instance_list:
        if instance_name == i_name:
            #print("Instance Name: ", instance_name)
            print(instance_ip)
            break

if __name__ == "__main__":

#    vpc_name = "wemix-dev-vpc"
    # 변수를 인자로 받아서 실행
    if len(sys.argv) != 3:
        print("Usage: python test.py <vpc_name> <instance_name>")
    else:
        v_name = sys.argv[1]
        i_name = sys.argv[2]
        main(v_name,i_name)
profile
어제보다 더 나은 엔지니어가 되자

0개의 댓글