[Hands-On]EventBridge를 이용한 CloudWatch Log Group 백업 자동화

안녕하세요

교보정보통신 클라우드기술팀 SA 김진섭 입니다.

이전 교보라이프플래닛 프로젝트 시 수행했던 로그 중앙화 및 자동화 과제에서 문제가 되었던 CloudWatch Export Log Group to S3 자동화 해결 과정을 설명하고, 핸즈온을 진행해보겠습니다.

과제

Instance 에서 발생하는 각 로그를 CloudWatch Agent를 이용해 CloudWatch Logs에 저장하고, 저장된 로그를 LogAccount 의 S3 Bucket 으로 Export 하는 상황이었습니다.

Cloud Watch Log Export to S3 기능은 스케쥴링 및 자동화 기능이 없어서 매 월 수동으로 Export 해야 했습니다.

수동 Export가 필요한 상황

이러한 상황을 해결하기 위해 Event Bridge 및 Automation 을 사용해 Export to S3 Task를 자동화 하였습니다.

이번 글에선 자동화 구성 과정을 살펴보고, 핸즈온을 진행하겠습니다.

Event Bridge 및 Automation을 통해 Export to S3 작업을 자동으로 트리거

주요 서비스

이번 핸즈온에서 사용될 주요 서비스는 다음과 같습니다.

AWS CloudWatch Logs[1]

EC2 Instance, CloudTrail, Route53 및 다른 원본에서 애플리케이션 및 사용자 지정 로그 파일을 모니터링, 저장 및 엑세스 할 수 있습니다.

이번 핸즈온에서 사용할 주요 기능은 다음과 같습니다.

  • Instance 에 CloudWatch Agent를 설치해 로그를 저장
  • Export to S3 기능을 이용해 버킷에 로그 저장

AWS Event Bridge[2]

코드 작성 없이 AWS 서비스, 자체 애플리케이션 및 SaaS 애플리케이션 데이터의 변경 사항에 대한 실시간 엑세스를 제공하는 서비스입니다.

이번 핸즈온에서 사용할 주요 기능은 다음과 같습니다.

  • EventBridge Scheduler를 사용해 특정 시간(1달)에 Automation Runbook 호출

AWS System Manager Automation[3]

System Manager 의 기능인 Automation 은 AWS 서비스에 대한 일반적인 유지관리, 배포 및 수정 작업을 단순화합니다.

이번 핸즈온에서 사용할 주요 기능은 다음과 같습니다.

  • 사용자 지정 Runbook을 생성해 CloudWatch의 Export to S3 기능을 자동화

AWS S3[4]

단순히 Export 된 데이터를 적재하는 용도로 사용되지만, 서로 다른 계정에서 데이터를 적재하려면 S3 Policy를 추가해야 합니다.

자동화 구성 과정 및 핸즈온

1. CloudWatch Agent 로 Custom Log 저장

테스트를 위해 인스턴스를 생성해 dnf(yum) log를 Cloudwatch Log Group에 저장 해 보겠습니다.

다음 요건에 맞춰 EC2 인스턴스를 생성합니다.

  • 어떤 방법으로든 인스턴스에 연결 가능
  • dnf 사용가능
  • CloudWatchAgentServerPolicy 가 포함된 IAM Role 을 Instance에 연결

아래 명령어는 AmazonLinux2023 기준으로 작성하였습니다.

Instance에 접근해 Cloudwatch Agent를 설치합니다

sudo dnf -y install amazon-cloudwatch-agent

설치 확인 후 아래 명령을 이용해 json 파일을 생성합니다.

해당 json 에는 CloudWatch Agent의 기본 설정 및 /var/log/dnf.log 파일을 CloudWatch Log Group으로 전송하는 설정이 포함되어있습니다.

cat <<EOF | sudo tee -a /opt/aws/amazon-cloudwatch-agent/bin/config.json
{
        "agent": {
                "metrics_collection_interval": 60,
                "run_as_user": "root"
        },
        "metrics": {
                "aggregation_dimensions": [
                        [
                                "InstanceId"
                        ]
                ],
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "disk": {
                                "measurement": [
                                        "used_percent"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        },
                        "statsd": {
                                "metrics_aggregation_interval": 60,
                                "metrics_collection_interval": 10,
                                "service_address": ":8125"
                        }
                }
        },
        "logs": {
                "logs_collected": {
                        "files": {
                                "collect_list": [
                                        {
                                                "file_path": "/var/log/dnf.log",
                                                "log_group_name": "{instance_id}",
                                                "log_stream_name": "dnf.log",
                                                "timezone": "Local"
                                        }
                                ]
                        }
                }
        }
}
EOF

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json

명령어 정상 작동 후 CloudWatch Log groups를 확인하면 instance id로 log group이 생성되고, dnf.log 로그 스트림을 확인할 수 있습니다.

Log Stream “dnf.log” 에 인스턴스에서 사용했던 dnf.log 가 저장됩니다.

이상으로 Export S3 작업을 테스트 할 샘플 로그를 수집했습니다.

2. IAM Role 및 Policy 생성

Log Group Export 작업을 자동화 하기 위해선 2개의 서로 다른 Role 및 Policy가 필요합니다.

  1. Event Bridge Schedule 로 AssumeRole 할 수 있으며 Automation을 실행할 수 있는 Role
  2. System Manager Automation 으로 AssumeRole 할 수 있으며 Log Group Export 작업을 실행할 수 있는 Role

❓ IAM Role 및 Policy를 하나로 생성하여 공용으로 사용할 수 있습니까?
💡 네. 하나의 Role에 모든 Policy를 부여하여 사용할 수 있습니다. 하지만 최소 권한 원칙에 위배되기 때문에 권장하지 않습니다.
더 자세한 사항은 AWS 공식문서 를 참조해주세요.

다음 Policy를 생성합니다.

Schedule에 사용할 Automation 실행 Policy
Policy Name: aws-policy-schedule-exec-an2

{
	"Version": "2012-10-17",
	"Statement": [
		{
            "Effect": "Allow",
            "Action": [
                "ssm:GetAutomationExecution",
                "ssm:StartAutomationExecution"
            ],
            "Resource": [
                "arn:aws:ssm:*:{account_id}:automation-definition/*:*",
                "arn:aws:ssm:*:{account_id}:automation-execution/*"
            ]
        }
	]
}

Schedule에 사용할 Automation 실행 Role 의 신뢰관계
Role Name: aws-role-schedule-exec-an2

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "scheduler.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

Automation에 사용할 Log Group Export 실행 Policy
Name: aws-policy-automation-exec-an2

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::my-exported-logs/*"
        }
    ]
}

Automation에 사용할 Log Group Export 실행 Role 의 신뢰관계
Name: aws-role-automation-exec-an2

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "ssm.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

3. 저장할 S3 생성

동일한 계정의 S3에 저장할 경우 버킷 생성 후 별다른 설정이 필요하지 않습니다.

기본 설정으로 버킷 생성

하지만 Cross Account로 다른 계정의 Bucket에 Log를 저장할 경우 Bucket Policy에 아래 권한을 입력해야 합니다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.ap-northeast-2.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::{bucket name}",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "{export account id}"
                }
            }
        },
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.ap-northeast-2.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::{bucket name}/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "{export account id}",
                    "s3:x-amz-acl": "bucket-owner-full-control"
                }
            }
        },
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::{export account id}:role/{automation execution role name}"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::{bucket name}/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control"
                }
            }
        }
    ]
}

더 자세한 권한 내용은 AWS 공식 문서 를 확인해주세요

4. Automation Runbook

Runbook을 작성하기에 앞서 Automation 및 Export Log Group to S3(이하 Export to S3) 기능에는 몃가지 제약사항이 있습니다.
우리는 해당 사항을 고려해 Runbook을 작성해야합니다.

제약사항

  1. Automation의 executeScript Step은 최대 작업시간은 600초(10분) 입니다.
  2. Automation은 하위 Step에서 상위 Step으로 돌아갈 수 없습니다.
  3. Automation의 executeAutomation Step은 자기 자신을 실행시킬 수 없습니다..
  4. Automation의 executeAutomation Step으로 실행된 Automation은 다른 Automation을 실행시킬 수 없습니다.
  5. Export to S3 기능은 한번에 하나의 작업만 작동하며, 종료될 때 까지 다른 작업을 실행할 수 없습니다.

위 재약사항으로 인해 하나의 Automation 실행으로 모든 Export를 순차적으로 실행시키기는 어렵습니다.
따라서 Automation Runbook은 최소한의 기능으로 구현하여 단일 LogGroup에 대한 Export만 실행하고, 다중 LogGroup에 대한 Export는 실행 단계에서 구현하겠습니다.

Runbook 작성

System Manager의 Documents 에서 Create Document → Automation을 선택합니다.

Name: 자유 (필자는 LogGroupExportToS3 사용)

아래 탭에서 Editor를 선택합니다.

우측 Edit 버튼을 선택합니다.

Document editor에 아래 스크립트를 입력합니다.

Automation Runbook Document

description: export log group to S3
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
  AutomationAssumeRole:
    type: String
    description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
    default: ''
  logGroupName:
    type: String
    description: (Required)The name of the log group.
  destinationBucket:
    type: String
    description: (Required) The name of S3 bucket for the exported log data.
  destinationPrefix:
    type: String
    description: (Optional) The prefix used as the start of the key for every object exported.
    default: ''
  beforeMonth:
    type: Integer
    description: '(Required) Export month set, default = 0(this month)'
    default: 0
  rangeMonth:
    type: Integer
    description: '(Required) Export month range, default = 1(1 month)'
    default: 1
  timeZone:
    type: Integer
    description: '(Required) UTC Base Timezone set, default = 0(UTC)'
    default: 0
mainSteps:
  - name: waitExportTasks
    action: 'aws:waitForAwsResourceProperty'
    timeoutSeconds: 3600
    inputs:
      Service: logs
      Api: DescribeExportTasks
      PropertySelector: '$.exportTasks[0].status.code'
      DesiredValues:
        - COMPLETED
        - CANCELLED
        - FAILED
    nextStep: exportCloudwatchLogGroup
  - name: exportCloudwatchLogGroup
    action: 'aws:executeScript'
    timeoutSeconds: 600
    inputs:
      Runtime: python3.6
      Handler: script_handler
      Script: "import datetime\\r\\nimport sys\\r\\nimport time\\r\\nimport os\\r\\n\\r\\nimport boto3\\r\\nfrom botocore.config import Config\\r\\nfrom dateutil import relativedelta\\r\\n\\r\\n\\r\\n# -----Define exportTask-----\\r\\n# CloudWatch Log Group Export Task\\r\\n# client = boto3.clinet\\r\\n# log_group_name = Export Log Group Name\\r\\n# first_day = start date of export task\\r\\n# last_day = end date of export task\\r\\n# destination_bucket = export target bucket name\\r\\n# destination_prefix = export target prefix\\r\\ndef exportTask(client, log_group_name, first_day, last_day, destination_bucket, destination_prefix):\\r\\n    try:\\r\\n        result = client.create_export_task(\\r\\n            logGroupName=log_group_name,\\r\\n            fromTime=int(time.mktime(first_day.timetuple())*1000),\\r\\n            to=int(time.mktime(last_day.timetuple())*1000),\\r\\n            destination=destination_bucket,\\r\\n            destinationPrefix=destination_prefix\\r\\n        )\\r\\n    except client.exceptions.LimitExceededException:\\r\\n        print('Error: limit exceed exception, continue')\\r\\n        return ('continue')\\r\\n\\r\\n    except Exception as e:\\r\\n        print('Error: Request to AWS CLI failed: {}'.format(e))\\r\\n        return (False)\\r\\n\\r\\n    return (result.get(\\"taskId\\"))\\r\\n\\r\\n# -----Define timeset-----\\r\\n# before_month = REQUIRED, set base export month(0 = now month, 1 = prev month, 2 = -2 month ...)\\r\\n# range_month = REQUIRED, set export range (1 = befare_month-1, 5 = before_month-5 ...)\\r\\n# log_group_name = REQUIRED, set export log group name, it replace '/' to '-'\\r\\n# destination prefix = OPTION, set bucket prefix\\r\\n# timezone = OPTION, insert your timezone\\r\\n\\r\\n\\r\\ndef timeSet(before_month, range_month, log_group_name, destination_prefix, timezone):\\r\\n    nowTime = datetime.datetime.utcnow()\\r\\n\\r\\n    this_month = datetime.datetime(\\r\\n        year=nowTime.year, month=nowTime.month, day=1, hour=0, minute=0, second=0) - relativedelta.relativedelta(months=before_month)\\r\\n    prev_month = this_month - relativedelta.relativedelta(months=range_month)\\r\\n    first_day = prev_month - datetime.timedelta(hours=timezone)\\r\\n    last_day = this_month - \\\\\\r\\n        datetime.timedelta(seconds=1) - datetime.timedelta(hours=timezone)\\r\\n    if(destination_prefix != ''): \\r\\n      destination_prefix = destination_prefix+'/'\\r\\n    destination_prefix_val = destination_prefix+str(\\r\\n        last_day.year)+'/'+str(last_day.month).zfill(2)+'/'+log_group_name.replace('/', '-')\\r\\n\\r\\n    return {\\r\\n        'this_month': this_month,\\r\\n        'prev_month': prev_month,\\r\\n        'first_day': first_day,\\r\\n        'last_day': last_day,\\r\\n        'destination_prefix': destination_prefix_val\\r\\n    }\\r\\n\\r\\n# -----Define export status check-----\\r\\n\\r\\n\\r\\ndef statusCheck(client):\\r\\n    response = client.describe_export_tasks(limit=1)\\r\\n    status = response.get('exportTasks')[0].get('status').get('code')\\r\\n\\r\\n    return status\\r\\n\\r\\n\\r\\n# -----Main-----\\r\\ndef script_handler(events, context):\\r\\n    before_month = events.get('beforeMonth')\\r\\n    range_month = events.get('rangeMonth')\\r\\n    log_group_name = events.get('logGroupName')\\r\\n    destination_bucket = events.get('destinationBucket')\\r\\n    destination_prefix_set = events.get('destinationPrefix')\\r\\n    timezone = events.get('timeZone')\\r\\n    \\r\\n    region = os.environ['AWS_REGION']\\r\\n    config = Config(\\r\\n        retries={\\r\\n            'max_attempts': 5,\\r\\n            'mode': 'standard'\\r\\n        }\\r\\n    )\\r\\n    client = boto3.client(\\"logs\\", region_name=region, config=config)\\r\\n\\r\\n    time_result = timeSet(before_month, range_month, log_group_name,\\r\\n                          destination_prefix_set, timezone)\\r\\n#    print(time_result.get(\\"destination_prefix\\"))\\r\\n\\r\\n    tries = 120\\r\\n    for i in range(0, tries):\\r\\n        task_result = exportTask(client, log_group_name, time_result.get(\\"first_day\\"),\\r\\n                                 time_result.get(\\"last_day\\"), destination_bucket, time_result.get(\\"destination_prefix\\"))\\r\\n        if task_result == 'continue':\\r\\n            time.sleep(30)\\r\\n            continue\\r\\n        elif task_result == False:\\r\\n            sys.exit(1)\\r\\n        else:\\r\\n            print(task_result)\\r\\n            break\\r\\n\\r\\n    return {\\r\\n        'exportTaskID': task_result,\\r\\n        'destinationBucket': destination_bucket,\\r\\n        'destinationPrefix': time_result.get(\\"destination_prefix\\")\\r\\n    }\\r\\n"
      InputPayload:
        beforeMonth: '{{beforeMonth}}'
        rangeMonth: '{{rangeMonth}}'
        logGroupName: '{{logGroupName}}'
        destinationBucket: '{{destinationBucket}}'
        destinationPrefix: '{{destinationPrefix}}'
        timeZone: '{{timeZone}}'
    description: export log group to S3
    outputs:
      - Name: Payload
        Selector: $.Payload
        Type: StringMap
      - Name: exportTaskID
        Selector: $.Payload.exportTaskID
        Type: String
      - Name: destinationBucket
        Selector: $.Payload.destinationBucket
        Type: String
      - Name: destinationPrefix
        Type: String
        Selector: $.Payload.destinationPrefix
    nextStep: describeCloudWatchExport
  - name: describeCloudWatchExport
    action: 'aws:waitForAwsResourceProperty'
    timeoutSeconds: 3600
    inputs:
      Service: logs
      Api: DescribeExportTasks
      taskId: '{{ exportCloudwatchLogGroup.exportTaskID }}'
      PropertySelector: '$.exportTasks[0].status.code'
      DesiredValues:
        - COMPLETED
        - CANCELLED
        - FAILED
    isEnd: true

하단 Create Automation 버튼 선택 시 Automation이 생성됩니다.

System Manager > Documents > Owned by me 에서 생성된 ExportLogGroupToS3를 확인할 수 있습니다.

생성된 Documents를 확인하면 3개의 Step을 확인할 수 있습니다.
각 Step이 하는 일은 다음과 같습니다.

  • Step 1: waitExportTasks 는 이전에 수행중인 Export Task가 있는지 확인합니다. 수행중인 Export Task가 있을 경우 최대 3600초(1시간) 까지 대기합니다.
  • Step 2: exportCloudwatchLogGroup 은 Export Task를 실행하고 TaskID를 반환합니다.
  • Step3: describeCloudWatchExport 는 실행된 Export Task의 상태를 확인합니다. 성공, 취소, 실패를 반환할 때 까지 최대 3600초(1시간) 대기합니다.

이제 우측 상단의 Execute automation 버튼을 선택해 생성된 Automation 테스트를 진행하겠습니다.

Execution을 Rate control로 선택해 여러 로그 그룹에 대한 export를 실행합니다.

💡 단일 Log Group에 대한 Export를 실행할 경우 Simple execution을 사용해도 무방합니다.

Target의 Parameter를 logGroupName으로, Target을 Parameter Values로 설정합니다.

Input Parameters에 아래 설명에 맞춰 변수를 입력합니다.

변수 명타입설명필수
AutomationAssumeRoleStringAutomation 실행 시 사용될 Role 변경X
logGroupNameStringExport 할 Log Group Name 지정O
destinationBucketStringExport 할 대상 Bucket 지정O
destinationPrefixStringExport 할 대상 폴더 지정X
beforeMonthIntegerExport 할 월 지정, (0 = 이번 달)O
rangeMonthIntegerExport 할 범위 지정. (1 = 이전 1달)O
timeZoneIntegerUTC 기반 TimeZone 설정X

작성자의 테스트 Parameters는 다음과 같습니다.

AutomationAssumeRole: arn:aws:iam::{Account-ID}:role/aws-automation-test
logGroupName: i-0f3c4f0ec407ed5e6, i-08ca478079261f82a
destnationPrefix: test
destinationBucket: log-group-export-test-bucket
beforeMonth: 0
rangeMonth: 1
timeZone: 0

2개의 Automation이 정상 실행됨을 확인했습니다.

대상 S3 버킷에도 정상 경로가 생성됨을 확인했습니다.

(대상버킷/prefix/2023/07/LogGroupName/)

5. EventBridge Schedule 생성으로 Export 자동화

EventBridge로 Automation을 트리거 할 때 Rules 및 Schedule을 사용할 수 있습니다.

두 기능에 대한 간략한 차이는 다음과 같습니다.

기능RulesSchedule
Trigger 가능 target사전에 정의된 Target거의 모든 AWS API
변수 입력 방식GUI(기본), Input transformerJSON
이벤트 스케쥴링특정 시간 반복 및 Cron 반복단일 실행 및 Cron 반복
모니터링CloudWatchCloudWatch
로깅Rule 및 Target 수정에 대한 Trail 로깅수정 및 실행에 대한 Trail 로깅

Automation 실행 시 Rate control 옵션을 사용해야 하므로 Rules의 GUI 변수 입력을 사용하지 못합니다.

Input transformer 사용 시 Rate control 옵션을 사용할 수 있을 것으로 보이지만 더 직관적으로 변수 입력이 가능하며, 실행에 대한 Trail 로깅을 지원하여 디버깅이 간편한 Schedule을 사용하기로 했습니다.

Event Bridge > Schedules 에서 Create schedule을 선택해 새로운 스캐쥴을 생성합니다.

Schedule Name 설정 후 Schedule pattern에서 다음을 설정합니다.

  1. Occurrence를 Recurring schedule로 설정해 특정 시간마다 반복되게 합니다.
  2. Schedule Type을 Cron-based 로 설정해 매 월 1일에 실행되도록 하겠습니다.
  3. cron 에 실행 시간을 입력합니다. ex) 15:13 에 실행시키고 싶다면 13 15 * * ? * 을 입력합니다.
    1. cron에 0 0 1 1/1 ? * 을 입력하면 매 월 1일 00:00 에 실행됩니다.
    2. 더 자세한 cron은 AWS 공식 문서를 참조해주세요
  4. Next 10 trigger dates 를 확인해 Cron 식이 정확한지 확인합니다.
  5. Flexible time window는 일정 호출 시간 조정으로 지금은 사용하지 않기 때문에 off로 설정합니다.
  6. Next를 선택합니다.
  1. Target API를 All APIs 로 전환합니다.
  2. AWS Service 검색창에 system를 검색해 System Manager를 선택합니다.
  1. Automation을 검색해 StartAutomationExecution API를 선택합니다.
  2. Input 부분에 아래 JSON을 입력합니다.
{
    "DocumentName": "ExportLogGroupToS3",
    "MaxConcurrency": "1",
    "MaxErrors": "1",
    "Parameters": {
        "AutomationAssumeRole": ["{your_role_arn}"],
        "beforeMonth": ["0"],
        "destinationBucket": ["{your_destination_bucket_name}"],
        "destinationPrefix": ["{your_destination_prefix}"],
        "rangeMonth": ["1"],
        "timeZone": ["9"]
    },
    "TargetParameterName": "logGroupName",
    "Targets": [{
            "Key": "ParameterValues",
            "Values": ["{your_log_group_names_1}", "{your_log_group_names_2}"...]
        }
    ]
}

해당 JSON은 ExportLogGroupToS3 Automation을 Targets의 갯수 만큼 순차적으로 실행시킵니다.
더 자세한 변수 값 확인은 AWS 공식 문서를 참조해주세요

  1. Next 버튼을 선택합니다.
  1. Action after schedule completion 은 None으로 설정해 Automation 이 종료되어도 Schedule이 삭제되지 않도록 합니다.
  2. Permissions 에서 위에서 생성한 Schedule용 Role 을 선택합니다.
  3. Next를 선택햅니다.
  4. Review and create schedule에서 설정값을 확인합니다.
  5. Create schedule을 선택해 Schedule을 생성합니다.

생성된 Schedule은 설정된 시간이 되면 자동으로 실행됩니다.

6. 실행 확인 및 모니터링

Schedule에 대한 모니터링은 다음 서비스로 가능합니다.

CloudWatch Metrics

  • Schedule Group 별로 AttemptCount, DroppedCount, ErrorCount를 기록합니다.

CloudTrail

  • Schedule 실행에 대한 API 로그를 기록합니다.
  • 실행 성공, 실패, 상세로그를 확인할 수 있습니다.

System Manager Automation

  • Schedule의 실행 대상이 Automation 이므로 System Manager Automation에서도 실행 정보를 확인할 수 있습니다.

CloudWatch Log groups

  • Automation의 실행 대상이 CloudWatch Log Group Export 임으로 Log Group에서도 Export Task를 확인할 수 있습니다.

S3 Bucket

  • Export 대상 버킷을 직접 확인할 수 있습니다.

7. 마무리

이상으로 EventBridge 및 Automation을 활용한 Log Group Export To S3 자동화 구성에 대해 살펴보았습니다.

EventBridge Schedule 을 이용하여 AWS API를 지원하는 대부분의 작업을 자동화 할 수 있으며 이번 사례와 같이 대기 시간과 경로 등 추가 설정이 필요한 경우 Automation 을 이용하여 자세한 제어가 가능함을 확인했습니다.

이를 응용하면 앞으로 고객의 상황에 맞는 다양한 자동화 적용이 가능할 것으로 생각됩니다.

감사합니다.

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다