안녕하세요, heyjee 입니다 .

두번째 순서로 AWS SDK 를 활용해 보안그룹 (Security Group) 제어 메소드들을 구현해 보도록 하겠습니다 .

 

SDK 를 활용한 AWS 보안그룹 제어 소스는 공통 > utils 디렉토리에서 관리하는 것으로 하겠습니다 .

/common/utils/AwsSecurityGroup.java

 

총 6 개의 메소드를 구현해 보았습니다 .

 > 보안그룹 추가
 > 보안그룹 삭제
 > 인바운드 룰 추가
 > 인바운드 룰 삭제
 > 보안그룹 가져오기
 > IP Permission 객체 생성

주의할 점은 보안그룹의 인바운드 룰을 제어 (추가[add], 삭제[revoke])하는 메소드를 정의할 때,

IP 포트와 주소 정보 등을 setIpPermission 메소드를 통해 IpPermission 타입으로 객체화 후, 이를 request 객체에 담아 response 를 리턴해야 한다는 점입니다 .

 

작성해본 코드는 다음과 같습니다 

package com.common.utils;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;

@Slf4j
@Component
public class AwsSecurityGroup {

   private static final String SECURITY_GROUP_REGION = "";
   private static final String SECURITY_GROUP_ID = "";
   private static final String AWS_ACCESS_KEY = "";
   private static final String AWS_SECRET_KEY = "";
   private static final AmazonEC2 EC2 = AmazonEC2Client.builder()
           .withRegion(SECURITY_GROUP_REGION)
           .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY)))
           .build();

   public void addSecurityGroup (String groupName, String groupDescription, String vpcId) {
   
       try {
           // Request
           CreateSecurityGroupRequest request = new CreateSecurityGroupRequest()
                   .withGroupName(groupName)
                   .withDescription(groupDescription)
                   .withVpcId(vpcId);
                   
           // Result
           CreateSecurityGroupResult result = EC2.createSecurityGroup(request);
           log.info("##### CreateSecurityGroupResult : " + result.getSdkResponseMetadata());
       } catch (Exception e) {
           e.printStackTrace();
       }
       
   }

   public void deleteSecurityGroup (String groupId) {
   
       try {
           // Request
           DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest()
                   .withGroupId(groupId);
                   
           // Result
           DeleteSecurityGroupResult result = EC2.deleteSecurityGroup(request);
           log.info("##### DeleteSecurityGroupResult : " + result.getSdkResponseMetadata());
       } catch (Exception e) {
           e.printStackTrace();
       }
       
   }

   public void addInboundRule (String ipProtocolType, Integer toPort, Integer fromPort, String ipAddress) {
   
       try {
           // Request
           AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest()
                   .withGroupId(SECURITY_GROUP_ID)
                   .withIpPermissions(setIpPermission(ipProtocolType, toPort, fromPort, ipAddress));
                   
           // Result
           AuthorizeSecurityGroupIngressResult result = EC2.authorizeSecurityGroupIngress(request);
           log.info("##### AuthorizeSecurityGroupIngressResult : " + result.getSdkResponseMetadata());
       } catch (Exception e) {
           e.printStackTrace();
       }
       
   }

   public void revokeInboundRule (String ipProtocolType, Integer toPort, Integer fromPort, String ipAddress) {
   
       try {
           // Request
           RevokeSecurityGroupIngressRequest request = new RevokeSecurityGroupIngressRequest()
                   .withGroupId(SECURITY_GROUP_ID)
                   .withIpPermissions(setIpPermission(ipProtocolType, toPort, fromPort, ipAddress));
                   
           // Result
           RevokeSecurityGroupIngressResult result = EC2.revokeSecurityGroupIngress(request);
           log.info("##### RevokeSecurityGroupIngressResult : " + result.getSdkResponseMetadata());
       } catch (Exception e) {
           e.printStackTrace();
       }
       
   }

   public List<SecurityGroup> describeSecurityGroup (String groupId) {
   
       DescribeSecurityGroupsRequest request;
       DescribeSecurityGroupsResult result = new DescribeSecurityGroupsResult();
       
       try {
           // Request
           request = new DescribeSecurityGroupsRequest();
           if(!"all".equals(groupId)) {
               request = request.withGroupIds(groupId);
               }
           
           // Result
           result = EC2.describeSecurityGroups(request);
       } catch (Exception e) {
           e.printStackTrace();
       }
       
       return result.getSecurityGroups();
   
   }

   private static IpPermission setIpPermission (String ipProtocolType, Integer toPort, Integer fromPort, String ipAddress) {
       
       return new IpPermission().withIpProtocol(ipProtocolType)
               .withToPort(toPort)
               .withFromPort(fromPort)
               .withIpv4Ranges(new IpRange().withCidrIp(ipAddress + "/32"));
   
   }
}
 Line 5 ~ 7 : AWS Security Group 관련 클래스를 사용하기 위한 util 패키지
 Line 16 : EC2 의 리전 정의 (e.g. eu-central-1)
 Line 17 : 인바운드 룰을 추가 or 삭제할 대상의 특정 보안그룹 ID 정의 (e.g. sg-XXXXXXXXXXXX)
 Line 20 ~ 23 : 보안그룹 제어 대상 EC2 의 Configuration (리전, 인증) 정의
 Line 25 ~ 41 : 보안그룹 추가
 Line 43 ~ 57 : 보안그룹 삭제
 Line 59 ~ 74 : 지정된 보안그룹 (Line 17)에 Inbound Rule 추가
 Line 76 ~ 91 : 지정된 보안그룹 (Line 17)의 Inbound Rule 취소
 Line 93 ~ 113 : 보안그룹 목록 가져오기
 Line 101 ~ 103 : 특정 보안그룹 정보만 가져오기 위한 조건문
 Line 115 ~ 122 : IP 정보 객체 생성
 Line 120 : CIDR 값을 32 로 하드코딩

 

혹시 수정이 되어야 할 부분이 있다면 얼마든지 코멘트 대환영입니다 . 감사합니다 :)

'Java' 카테고리의 다른 글

1. Apply @Transactional Annotation in Spring Framework  (0) 2021.11.28

안녕하세요, heyjee 입니다 .

첫 순서로 Spring Framework 에서 서비스로직에 트랜잭션 어노테이션을 적용하는 방법을 알아보겠습니다 .

 

트랜잭션의 포인트는 모두 처리하면 성공 - 그렇지 않으면 실패  입니다 .

이 포인트를 적용해 작성해본 코드는 다음과 같습니다 .

@Service
public class UserMgmtSvc {

    @Autowired
    UserMgmtMapper userMgmtMapper;

    @Transactional(rollbackFor = { Exception.class })
    public void removeLongTermNoUseUserInfo (String guid) throws Exception {
        try {
            userMgmtMapper.deleteUserInfo(guid);
            userMgmtMapper.deleteUserRegionAuthority(guid);
            userMgmtMapper.deleteUserServiceAuthority(guid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }

}
 Line 7 : Transactional 어노테이션을 선언해줌으로써 removeLongTermNoUseUserInfo 메소드를 트랜잭션으로 처리
 이 때, rollbackFor 속성을 추가함으로써 트랜잭션 실행 중 어떠한 Exception 이라도 발생한다면 진행중인 트랜잭션을 취소하고 롤백
 Line 9 ~ 16 : 세 개의 mapper 메소드 트랜잭션 처리에 대해 try-catch 구문을 적용
 Line 15 : 발생한 Exception 을 catch 할 때, 명시적으로 해당 Exception 을 throw 처리 (중요)
 > 해당 구문이 없으면 트랜잭션 처리 중 Exception 발생 시, 롤백을 실패하게 됨

 

혹시 수정이 되어야 할 부분이 있다면 얼마든지 코멘트 대환영입니다 . 감사합니다 :)

'Java' 카테고리의 다른 글

2. Implement AWS Security Group control methods using SDK  (0) 2021.12.04

+ Recent posts