목적
- 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>
import boto3
from botocore.exceptions import NoCredentialsError
import subprocess
import sys
sts_client = boto3.client('sts')
role_arn = 'arn:aws:iam::111111111111:role/<role-name>'
session_name = 'deploy_worker'
response = sts_client.assume_role(RoleArn=role_arn, RoleSessionName=session_name)
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)
for instance_name, instance_ip in instance_list:
if instance_name == i_name:
print(instance_ip)
break
if __name__ == "__main__":
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)