<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by MZC_Global on Medium]]></title>
        <description><![CDATA[Stories by MZC_Global on Medium]]></description>
        <link>https://medium.com/@sa_globalblog?source=rss-d9957cf2c6c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ss6QOLXdzvivAcbIipJbww.png</url>
            <title>Stories by MZC_Global on Medium</title>
            <link>https://medium.com/@sa_globalblog?source=rss-d9957cf2c6c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:03:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sa_globalblog/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Terraform 기반 AWS CodePipeline을 포함한 AWS Fargate자동 디플로이 (Blue/Green)]]></title>
            <link>https://medium.com/cloudvillains/terraform-%EA%B8%B0%EB%B0%98-aws-codepipeline%EC%9D%84-%ED%8F%AC%ED%95%A8%ED%95%9C-aws-fargate%EC%9E%90%EB%8F%99-%EB%94%94%ED%94%8C%EB%A1%9C%EC%9D%B4-blue-green-72eb90bd898f?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/72eb90bd898f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-fargate]]></category>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[megazonecloud]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 04:58:51 GMT</pubDate>
            <atom:updated>2024-02-13T04:58:51.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>개요</h3><p>이번에 Terraform을 사용하여 AWS Fragate와 AWS CodePipeline(AWS CodeCommit + AWS CodeBuild + AWS CodeDeploy(Blue/Green))의 구축 및 배포 프로세스를 자동화 해 보았습니다.</p><p>구성은 다음 그림과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MNHmJSqVsQ4MAHp-" /></figure><p>먼저 동작 메커니즘은 개발자가 AWS CodeCommit의 Main Branch에 Push를 트리거하여 AWS CodePipeline을 실행합니다. 그 후, AWS CodeCommit에서 소스 코드를 순차적으로 검색하여 Amazon S3에 저장합니다.</p><p>AWS CodeBuild가 시작되어 Amazon S3에서 소스 코드를 가져오고 ECR로 docker push를 수행 합니다.</p><p>최종적으로 AWS CodeDeploy는 AWS Fargate의 서비스를 새로운 Task Definition으로 업데이트 합니다. 참고로 이번 디플로이 작업은 Blue/Green 디플로이로 실시했습니다.</p><p>Hands-on의 전제 조건은 다음과 같습니다. (설치 방법은 생략하겠습니다.)</p><ul><li>Local 환경</li><li>Terraform v1.5.4 (~&gt; 1.5.0)</li><li>aws-cli</li><li>docker</li><li>Git</li><li>AWS 환경</li><li>Terraform state file 관리를 위한 Amazon S3 Bucket</li></ul><p>Hands-on의 절차는 다음과 같습니다.</p><ol><li>Terraform main.tf 생성 및 구축</li><li>AWS Network의 Terraform 생성 및 구축</li><li>AWS ECR의 Terraform 생성 및 구축</li><li>AWS ALB의 Terraform 생성 및 구축</li><li>AWS ECS의 Terraform 생성 및 구축</li><li>AWS CodeCommit의 Terraform 생성 및 구축</li><li>AWS CodeBuild의 Terraform 생성 및 구축</li><li>AWS CodeDeploy의 Terraform 생성 및 구축</li><li>AWS CodePipeline의 Terraform 생성 및 구축</li></ol><p>※본 Hands-on에서는 AWS나 Terraform의 상세 사양에 대해서는 기재 하지 않았습니다.</p><h3>Hands-on</h3><h4>1. Terraform main.tf 생성 및 구축</h4><p>Terraform에서 사용하는 변수는 다음과 같습니다. 필요한 경우 변수 값을 다시 기재해도 됩니다.</p><pre>variable &quot;region&quot; {<br>  type        = string<br>  default     = &quot;ap-northeast-1&quot;<br>  description = &quot;AWS tokyo region&quot;<br>}<br><br>variable &quot;shared_credentials&quot; {<br>  type        = list(string)<br>  default     = [&quot;~/.aws/credentials&quot;]<br>  description = &quot;Path of the AWS credentials&quot;<br>}<br><br>variable &quot;tags&quot; {<br>  type = map(string)<br>  default = {<br>    env = &quot;fargate_cicd_dev&quot;<br>  }<br>  description = &quot;AWS tags&quot;<br>}<br><br>variable &quot;cidr&quot; {<br>  type        = string<br>  default     = &quot;10.0.0.0/16&quot;<br>  description = &quot;VPC cidr&quot;<br>}<br><br>variable &quot;cloudwatch_log_group_name&quot; {<br>  type        = string<br>  default     = &quot;/ecs/logs/terraform/nginx&quot;<br>  description = &quot;AWS Fargate CloudWatch Log Group Name&quot;<br>}<br><br>variable &quot;container_port&quot; {<br>  type        = number<br>  default     = 80<br>  description = &quot;Ingres and egress port of the container&quot;<br>}<br><br>variable &quot;container_name&quot; {<br>  type        = string<br>  default     = &quot;nginx_container&quot;<br>  description = &quot;Container Name&quot;<br>}</pre><p>main.tf 에서는</p><ul><li>Terraform Version</li><li>사용할 Providers</li><li>tfstate 파일을 관리하는 방법</li></ul><p>을 만들었습니다. 그리고 terraform init 작업 공간을 초기화 해 두겠습니다.</p><pre>#--------------------------------------------------------------<br># terraform<br>#--------------------------------------------------------------<br>terraform {<br>  required_version = &quot;~&gt; 1.5.0&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>  backend &quot;s3&quot; {<br>    bucket  = &quot;&quot; # s3 bucket name<br>    region  = &quot;ap-northeast-1&quot;<br>    key     = &quot;fargate-codepipeline/terraform.tfstate&quot;<br>    encrypt = true<br>  }<br>}<br><br>#--------------------------------------------------------------<br># Provider<br>#--------------------------------------------------------------<br>provider &quot;aws&quot; {<br>  shared_credentials_files = var.shared_credentials<br>  region                   = var.region<br>}</pre><h3>2. AWS Network의 Terraform 생성 및 구축</h3><p>구성도에도 있지만 AWS Network 부분은 이하의 리소스를 구축합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*FyFV3fyDnCToBjROcewImA.png" /></figure><pre>#--------------------------------------------------------------<br># VPC<br>#--------------------------------------------------------------<br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = var.cidr<br>  tags       = merge(var.tags, { &quot;Name&quot; = &quot;vpc-fargate-cicd&quot; })<br>}<br><br>#--------------------------------------------------------------<br># Subnet<br>#--------------------------------------------------------------<br>resource &quot;aws_subnet&quot; &quot;prv_a1&quot; {<br>  vpc_id            = aws_vpc.main.id<br>  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, 0) // 10.0.0.0/24<br>  availability_zone = &quot;${var.region}a&quot;<br>  tags              = merge(var.tags, { &quot;Name&quot; = &quot;prv-sub-a1&quot; })<br>}<br>resource &quot;aws_subnet&quot; &quot;prv_c1&quot; {<br>  vpc_id            = aws_vpc.main.id<br>  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, 2) // 10.0.2.0/24<br>  availability_zone = &quot;${var.region}c&quot;<br>  tags              = merge(var.tags, { &quot;Name&quot; = &quot;prv-sub-c1&quot; })<br>}<br><br>resource &quot;aws_subnet&quot; &quot;pub_a1&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, 1) // 10.0.1.0/24<br>  availability_zone       = &quot;${var.region}a&quot;<br>  map_public_ip_on_launch = true<br>  tags                    = merge(var.tags, { &quot;Name&quot; = &quot;pub-sub-a1&quot; })<br>}<br>resource &quot;aws_subnet&quot; &quot;pub_c1&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, 3) // 10.0.3.0/24<br>  availability_zone       = &quot;${var.region}c&quot;<br>  map_public_ip_on_launch = true<br>  tags                    = merge(var.tags, { &quot;Name&quot; = &quot;pub-sub-c1&quot; })<br>}<br><br>#--------------------------------------------------------------<br># Internet Gateway<br>#--------------------------------------------------------------<br>resource &quot;aws_internet_gateway&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, { &quot;Name&quot; = &quot;igw-fargate-cicd&quot; })<br>}<br><br>#--------------------------------------------------------------<br># Elastic IP<br>#--------------------------------------------------------------<br>resource &quot;aws_eip&quot; &quot;ngw1&quot; {<br>  vpc  = true<br>  tags = merge(var.tags, { &quot;Name&quot; = &quot;eip-ngw1&quot; })<br>}<br><br><br>resource &quot;aws_eip&quot; &quot;ngw2&quot; {<br>  vpc  = true<br>  tags = merge(var.tags, { &quot;Name&quot; = &quot;eip-ngw2&quot; })<br>}<br><br>#--------------------------------------------------------------<br># NAT Gateway<br>#--------------------------------------------------------------<br>resource &quot;aws_nat_gateway&quot; &quot;a1&quot; {<br>  allocation_id = aws_eip.ngw1.id<br>  subnet_id     = aws_subnet.pub_a1.id<br>  depends_on    = [aws_internet_gateway.main]<br>  tags          = merge(var.tags, { &quot;Name&quot; = &quot;ngw1&quot; })<br>}<br>resource &quot;aws_nat_gateway&quot; &quot;c1&quot; {<br>  allocation_id = aws_eip.ngw2.id<br>  subnet_id     = aws_subnet.pub_c1.id<br>  depends_on    = [aws_internet_gateway.main]<br>  tags          = merge(var.tags, { &quot;Name&quot; = &quot;ngw2&quot; })<br>}<br><br>#--------------------------------------------------------------<br># Route Table<br>#--------------------------------------------------------------<br>resource &quot;aws_route_table&quot; &quot;igw&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, { &quot;Name&quot; = &quot;rt-igw&quot; })<br>}<br>resource &quot;aws_route&quot; &quot;igw&quot; {<br>  route_table_id         = aws_route_table.igw.id<br>  destination_cidr_block = &quot;0.0.0.0/0&quot;<br>  gateway_id             = aws_internet_gateway.main.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;igw1&quot; {<br>  subnet_id      = aws_subnet.pub_a1.id<br>  route_table_id = aws_route_table.igw.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;igw2&quot; {<br>  subnet_id      = aws_subnet.pub_c1.id<br>  route_table_id = aws_route_table.igw.id<br>}<br><br>resource &quot;aws_route_table&quot; &quot;ngw1&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, { &quot;Name&quot; = &quot;rt-ngw1&quot; })<br>}<br>resource &quot;aws_route&quot; &quot;ngw1&quot; {<br>  route_table_id         = aws_route_table.ngw1.id<br>  destination_cidr_block = &quot;0.0.0.0/0&quot;<br>  nat_gateway_id         = aws_nat_gateway.a1.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;ngw1&quot; {<br>  subnet_id      = aws_subnet.prv_a1.id<br>  route_table_id = aws_route_table.ngw1.id<br>}<br><br>resource &quot;aws_route_table&quot; &quot;ngw2&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, { &quot;Name&quot; = &quot;rt-ngw2&quot; })<br>}<br>resource &quot;aws_route&quot; &quot;ngw2&quot; {<br>  route_table_id         = aws_route_table.ngw2.id<br>  destination_cidr_block = &quot;0.0.0.0/0&quot;<br>  nat_gateway_id         = aws_nat_gateway.c1.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;ngw2&quot; {<br>  subnet_id      = aws_subnet.prv_c1.id<br>  route_table_id = aws_route_table.ngw2.id<br>}<br><br>#--------------------------------------------------------------<br># Security Group<br>#--------------------------------------------------------------<br><br>resource &quot;aws_security_group&quot; &quot;alb&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, { &quot;Name&quot; = &quot;sg-alb&quot; })<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;allow_http_inbound&quot; {<br>  type              = &quot;ingress&quot;<br>  from_port         = 80<br>  to_port           = 80<br>  protocol          = &quot;tcp&quot;<br>  security_group_id = aws_security_group.alb.id<br>  cidr_blocks       = [&quot;0.0.0.0/0&quot;]<br>}<br>resource &quot;aws_security_group_rule&quot; &quot;allow_app_sg_outbound&quot; {<br>  type                     = &quot;egress&quot;<br>  from_port                = 80<br>  to_port                  = 80<br>  protocol                 = &quot;tcp&quot;<br>  security_group_id        = aws_security_group.alb.id<br>  source_security_group_id = aws_security_group.app.id<br>}<br><br>resource &quot;aws_security_group&quot; &quot;app&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, { &quot;Name&quot; = &quot;sg-app&quot; })<br>}<br>resource &quot;aws_security_group_rule&quot; &quot;allow_alb_sg_inbound&quot; {<br>  type                     = &quot;ingress&quot;<br>  from_port                = 80<br>  to_port                  = 80<br>  protocol                 = &quot;tcp&quot;<br>  security_group_id        = aws_security_group.app.id<br>  source_security_group_id = aws_security_group.alb.id<br>}<br>resource &quot;aws_security_group_rule&quot; &quot;allow_every_outbound&quot; {<br>  type              = &quot;egress&quot;<br>  from_port         = 0<br>  to_port           = 0<br>  protocol          = &quot;-1&quot;<br>  security_group_id = aws_security_group.app.id<br>  cidr_blocks       = [&quot;0.0.0.0/0&quot;]<br>}</pre><p>nw.tf를 만든 후 terraform plan 하여 문제가 없다면 terraform apply 를 실행합니다.</p><h3>3. AWS ECR의 Terraform 생성 및 구축</h3><p>AWS ECS Fargate에서 컨테이너를 시작하려면 먼저 Docker Image를 AWS ECR로 푸시합니다.<br>먼저 AWS ECR을 생성하고, terraform apply 까지 실행합니다.</p><pre>#--------------------------------------------------------------<br># ECR<br>#--------------------------------------------------------------<br>resource &quot;aws_ecr_repository&quot; &quot;main&quot; {<br>  name                 = &quot;ecr-fargate-cicd&quot;<br>  image_tag_mutability = &quot;MUTABLE&quot;<br>  tags                 = merge(var.tags, {})<br>}<br><br>resource &quot;aws_ecr_lifecycle_policy&quot; &quot;main&quot; {<br>  repository = aws_ecr_repository.main.name<br><br>  policy = jsonencode({<br>    rules = [{<br>      rulePriority = 1<br>      description  = &quot;keep last 10 images&quot;<br>      action = {<br>        type = &quot;expire&quot;<br>      }<br>      selection = {<br>        tagStatus   = &quot;any&quot;<br>        countType   = &quot;imageCountMoreThan&quot;<br>        countNumber = 10<br>      }<br>    }]<br>  })<br>}</pre><p>그 후 Docker Image를 생성합니다. Dockerfile은 간단한 nginx를 사용하였으며, 이하를 참고 해 주시길 바랍니다.</p><pre>.<br>├── Dockerfile<br>├── src<br>│   └── index.html</pre><p>Dockerfile</p><pre>FROM &#39;nginx:latest&#39;<br>RUN service nginx start<br>COPY src /usr/share/nginx/html<br>VOLUME /usr/share/nginx/html</pre><p>src/index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;title&gt;Welcome to nginx!&lt;/title&gt;<br>&lt;style&gt;<br>html { color-scheme: light dark; }<br>body { width: 35em; margin: 0 auto;<br>font-family: Tahoma, Verdana, Arial, sans-serif; }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Welcome to nginx!&lt;/h1&gt;<br>&lt;p&gt;If you see this page, the nginx web server is successfully installed and<br>working. Further configuration is required.&lt;/p&gt;<br><br>&lt;p&gt;For online documentation and support please refer to<br>&lt;a href=&quot;http://nginx.org/&quot;&gt;nginx.org&lt;/a&gt;.&lt;br/&gt;<br>Commercial support is available at<br>&lt;a href=&quot;http://nginx.com/&quot;&gt;nginx.com&lt;/a&gt;.&lt;/p&gt;<br><br>&lt;p&gt;&lt;em&gt;Thank you for using nginx.&lt;/em&gt;&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>다음은 이 Dockerfile을 AWS ECR로 푸시 하는 작업이 필요합니다. 방법에 대해서는 AWS ECR 상세 화면의 “View push commands”에서 확인할 수 있으므로 해당 페이지(아래 이미지)를 참조하시길 바랍니다.<br>참고로, macOS의 Apple silicon을 사용하는 경우, docker build 할 때, <em>docker build — platform linux/amd64 -t ${YOUR_ECR_NAME} .</em>명령처럼<em> — platform</em> 옵션을 사용 해야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aeAksET8VT6A7s3o" /></figure><h3>4. AWS ALB의 Terraform 생성 및 구축</h3><p>AWS ECS에는 Load Balancer가 필요하므로 AWS ALB를 구축합니다.<br>마찬가지로 terraform apply까지 실행합니다.</p><pre>#--------------------------------------------------------------<br># Application Load Balancer<br>#--------------------------------------------------------------<br>resource &quot;aws_lb&quot; &quot;main&quot; {<br>  name               = &quot;alb-fargate-cicd&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.alb.id]<br>  subnets            = [aws_subnet.pub_a1.id, aws_subnet.pub_c1.id]<br><br>  enable_deletion_protection = false<br>  tags                       = merge(var.tags, {})<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;blue&quot; {<br>  name        = &quot;lb-tg-blue&quot;<br>  port        = 80<br>  protocol    = &quot;HTTP&quot;<br>  vpc_id      = aws_vpc.main.id<br>  target_type = &quot;ip&quot;<br><br>  health_check {<br>    healthy_threshold   = &quot;3&quot;<br>    interval            = &quot;30&quot;<br>    protocol            = &quot;HTTP&quot;<br>    matcher             = &quot;200&quot;<br>    timeout             = &quot;3&quot;<br>    path                = &quot;/&quot;<br>    unhealthy_threshold = &quot;2&quot;<br>  }<br>  tags = merge(var.tags, {})<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;green&quot; {<br>  name        = &quot;lb-tg-green&quot;<br>  port        = 80<br>  protocol    = &quot;HTTP&quot;<br>  vpc_id      = aws_vpc.main.id<br>  target_type = &quot;ip&quot;<br><br>  health_check {<br>    healthy_threshold   = &quot;3&quot;<br>    interval            = &quot;30&quot;<br>    protocol            = &quot;HTTP&quot;<br>    matcher             = &quot;200&quot;<br>    timeout             = &quot;3&quot;<br>    path                = &quot;/&quot;<br>    unhealthy_threshold = &quot;2&quot;<br>  }<br>  tags = merge(var.tags, {})<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;http&quot; {<br>  load_balancer_arn = aws_lb.main.arn<br>  port              = &quot;80&quot;<br>  protocol          = &quot;HTTP&quot;<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.blue.arn<br>  }<br><br>  lifecycle {<br>    ignore_changes = [default_action]<br>  }<br>  tags = merge(var.tags, {})<br>}</pre><p>추후 AWS ECS를 구축한 후, AWS ALB DNS를 사용하므로 Output으로 기재 해 두겠습니다.</p><pre>output &quot;alb_dns_name&quot; {<br>  description = &quot;ALB DNS Name&quot;<br>  value       = try(aws_lb.main.dns_name, &quot;&quot;)<br>}</pre><h3>5. AWS ECS의 Terraform 생성 및 구축</h3><p>다음은 AWS ECS를 구축합니다. 지금까지의 File과 코드의 양이 늘어나므로, 현재의 File구성은 이하와 같이 될 것으로 예상 됩니다. (File명은 아래와 같이 맞추지 않아도 OK)<br>그럼 <em>← add</em>부분을 작성해 보겠습니다.</p><pre>.<br>├── Dockerfile<br>├── alb.tf<br>├── ecr.tf<br>├── ecs.tf &lt;-- add<br>├── files  &lt;-- add<br>│   ├── assumerole.json.tpl  &lt;-- add<br>│   ├── container_definitions.json.tpl  &lt;-- add<br>├── locals.tf &lt;-- add<br>├── main.tf<br>├── nw.tf<br>├── output.tf<br>├── src<br>│   └── index.html<br>└── vars.tf</pre><p>assumrole과 Task definition은 다음과 같이 작성 합니다.</p><p>files/assumerole.json.tpl</p><pre>{<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>   {<br>     &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>     &quot;Principal&quot;: {<br>       &quot;Service&quot;: &quot;${resource}.amazonaws.com&quot;<br>     },<br>     &quot;Effect&quot;: &quot;Allow&quot;,<br>     &quot;Sid&quot;: &quot;&quot;<br>   }<br> ]<br>}</pre><p>files/container_definitions.json.tpl</p><pre>[<br>    {<br>        &quot;name&quot;: &quot;${container_name}&quot;,<br>        &quot;image&quot;: &quot;${container_image}&quot;,<br>        &quot;cpu&quot;: 256,<br>        &quot;essential&quot;: true,<br>        &quot;memory&quot;: 512,<br>        &quot;portMappings&quot;: [<br>            {<br>                &quot;protocol&quot;: &quot;tcp&quot;,<br>                &quot;containerPort&quot;: ${container_port},<br>                &quot;hostPort&quot;: ${container_port}<br>            }<br>        ],<br>        &quot;LogConfiguration&quot;: {<br>            &quot;logDriver&quot;: &quot;awslogs&quot;,<br>            &quot;options&quot;: {<br>                &quot;awslogs-group&quot;: &quot;${cloudwatch_log_group_name}&quot;,<br>                &quot;awslogs-region&quot;: &quot;ap-northeast-1&quot;,<br>                &quot;awslogs-stream-prefix&quot;: &quot;terraform&quot;<br>            }<br>        }<br>    }<br>]</pre><p>이 후 다른 값을 참조하는 경우가 있으므로 Locals를 이용합니다.</p><pre>data &quot;aws_caller_identity&quot; &quot;current&quot; {}<br><br>locals {<br>  container_image = &quot;${aws_ecr_repository.main.repository_url}:latest&quot;<br>  account_id      = data.aws_caller_identity.current.account_id<br>}</pre><p>AWS ECS는 다음과 같이 생성하여 terraform apply 까지 실행합니다.</p><pre>#--------------------------------------------------------------<br># IAM<br>#--------------------------------------------------------------<br>resource &quot;aws_iam_role&quot; &quot;ecs_task_execution_role&quot; {<br>  name               = &quot;MyECS-TaskExecutionRole&quot;<br>  assume_role_policy = templatefile(&quot;./files/assumerole.json.tpl&quot;, { resource = &quot;ecs-tasks&quot; })<br>}<br># Provides access to other AWS service resources that are required to run Amazon ECS tasks<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs-task-execution-role-policy-attachment&quot; {<br>  role       = aws_iam_role.ecs_task_execution_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy&quot;<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;task_role&quot; {<br>  name               = &quot;MyECS-TaskRole&quot;<br>  assume_role_policy = templatefile(&quot;./files/assumerole.json.tpl&quot;, { resource = &quot;ecs-tasks&quot; })<br>}<br># Allow the containers in your task to assume an IAM role to call AWS APIs without having to use AWS Credentials inside the containers.<br>resource &quot;aws_iam_role_policy&quot; &quot;task-policy&quot; {<br>  role   = aws_iam_role.task_role.name<br>  policy = templatefile(&quot;./files/ecs_task_policy.json.tpl&quot;, {})<br>}<br><br>#--------------------------------------------------------------<br># Cloudwatch Log Group<br>#--------------------------------------------------------------<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;nginx&quot; {<br>  name              = var.cloudwatch_log_group_name<br>  retention_in_days = 1<br>}<br><br>#--------------------------------------------------------------<br># ECS<br>#--------------------------------------------------------------<br>resource &quot;aws_ecs_cluster&quot; &quot;main&quot; {<br>  name = &quot;ecs-fargate-cicd&quot;<br>  tags = merge(var.tags, {})<br>}<br><br>resource &quot;aws_ecs_cluster_capacity_providers&quot; &quot;main&quot; {<br>  cluster_name       = aws_ecs_cluster.main.name<br>  capacity_providers = [&quot;FARGATE&quot;]<br>}<br><br>resource &quot;aws_ecs_task_definition&quot; &quot;main&quot; {<br>  family                   = &quot;my-task-def&quot;<br>  network_mode             = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;FARGATE&quot;]<br>  cpu                      = 256<br>  memory                   = 512<br>  execution_role_arn       = aws_iam_role.ecs_task_execution_role.arn<br>  task_role_arn            = aws_iam_role.task_role.arn<br><br>  container_definitions = templatefile(&quot;./files/container_definitions.json.tpl&quot;, {<br>    container_name            = var.container_name,<br>    container_port            = var.container_port,<br>    container_image           = local.container_image,<br>    cloudwatch_log_group_name = var.cloudwatch_log_group_name<br>  })<br>}<br><br>resource &quot;aws_ecs_service&quot; &quot;main&quot; {<br>  name                               = &quot;service-fargate-cicd&quot;<br>  cluster                            = aws_ecs_cluster.main.id<br>  task_definition                    = aws_ecs_task_definition.main.arn<br>  desired_count                      = 2<br>  deployment_minimum_healthy_percent = 50<br>  deployment_maximum_percent         = 200<br>  launch_type                        = &quot;FARGATE&quot;<br>  scheduling_strategy                = &quot;REPLICA&quot;<br>  enable_execute_command             = true<br><br>  network_configuration {<br>    security_groups = [aws_security_group.app.id]<br>    subnets         = [aws_subnet.prv_a1.id, aws_subnet.prv_c1.id]<br><br>    assign_public_ip = false<br>  }<br><br>  load_balancer {<br>    target_group_arn = aws_lb_target_group.blue.arn<br>    container_name   = var.container_name<br>    container_port   = var.container_port<br>  }<br><br>  deployment_controller {<br>    type = &quot;CODE_DEPLOY&quot;<br>  }<br><br>  lifecycle {<br>    ignore_changes = [task_definition, desired_count, load_balancer]<br>  }<br>  depends_on = [aws_lb.main]<br><br>}</pre><p>AWS ECS까지 구축한 후 ALB DNS 이름으로 액세스하여 index.html이 표시되는지 확인합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MxLgnd0bideVonho" /></figure><p>다음은 디플로이 프로세스를 자동화 해 봅시다.</p><h3>6. AWS CodeCommit의 Terraform 생성 및 구축</h3><p>AWS CodePipeline을 구축할 때 AWS CodeCommit, CodeBuild, CodeDeploy를 구축합니다.<br>AWS CodePipeline을 terraform apply할 때 AWS CodePipeline이 실행되므로 사전에 AWS CodeCommit에 Dockerfile 등 배포에 필요한 File을 git push해 둡니다.</p><pre>#--------------------------------------------------------------<br># CodeCommit<br>#--------------------------------------------------------------<br>resource &quot;aws_codecommit_repository&quot; &quot;main&quot; {<br>  repository_name = &quot;codecommit-fargate-cicd&quot;<br>}</pre><p>terraform apply까지 실행한 다음 AWS CodeCommit에서 git clone합니다.<br>방법에 대해서는 다음과 같이 AWS CodeCommit을 생성하고 상세 페이지로 이동하면 Connetion steps에서 설명하므로 환경에 맞게 설정합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cH7HL2B6WbqA6gnL" /></figure><p>그 후, 이하의 파일을 AWS CodeCommit으로 git push합니다. Dockerfile과 src/는 위의 AWS ECR 빌드 중에 설명했으므로 나머지 파일을 생성합니다. (다른 .tf files도 push해도 괜찮습니다)</p><pre>.<br>├── Dockerfile &lt;-- 조금 전 AWS ECR에 이용한 File<br>├── appspec.yml<br>├── buildspec.yml<br>├── imageDetail.json<br>├── src &lt;-- 조금 전 AWS ECR에 이용한 File<br>│   └── index.html<br>└── taskdef.json</pre><p>appspec.yml은 애플리케이션 사양을 설정하는 File입니다. 기본적으로 Blue/Green에서 사용합니다.<br>변수에 관해서는</p><ul><li><em>&lt;TASK_DEFINITION&gt; </em>: Task Definition의 ARN으로 자동으로 대체됩니다. (프로바이더가 CodeDeployToECS이기 때문에)</li><li><em>&lt;CONTAINER_NAME&gt;</em> : AWS CodeBuild에서 설정합니다.</li></ul><pre>version: 0.0<br>Resources:<br>  - TargetService:<br>      Type: AWS::ECS::Service<br>      Properties:<br>        TaskDefinition: &lt;TASK_DEFINITION&gt;<br>        LoadBalancerInfo:<br>          ContainerName: &lt;CONTAINER_NAME&gt;<br>          ContainerPort: 80</pre><p>buildspec.yml은 AWS CodeBuild 사양을 설정하는 File입니다. 여기서 수행하는 작업은 AWS ECR에서 수동으로 docker push를 수행한 것을 스크립트에서 수행하는 것입니다.</p><p>변수에 관해서는</p><ul><li><em>$AWS_ACCOUNT_ID</em>: 기밀 정보이므로 AWS SSM Parameter store에서 가져옵니다.</li><li>다른 변수는 AWS CodeBuild에서 설정합니다.</li></ul><pre>version: 0.2<br><br>env:<br>  parameter-store:<br>    AWS_ACCOUNT_ID: &quot;MY_ACCOUNT_ID&quot;<br>phases:<br>  pre_build:<br>    commands:<br>      - echo Logging in to Amazon ECR...<br>      - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com<br>  build:<br>    commands:<br>      - echo Build started on `date`<br>      - echo Building the Docker image...<br>      - docker build -t $ECR_NAME:$IMAGE_TAG .<br>      - docker tag $ECR_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$ECR_NAME:$IMAGE_TAG      <br>  post_build:<br>    commands:<br>      - echo Build completed on `date`<br>      - echo Pushing the Docker image...<br>      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$ECR_NAME:$IMAGE_TAG<br>      - printf &#39;{&quot;ImageURI&quot;:&quot;%s&quot;}&#39; $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$ECR_NAME:$IMAGE_TAG  &gt; imageDetail.json<br>      - echo &quot;$(cat imageDetail.json)&quot;<br>      - echo Rewriting task definitions file...<br>      - sed -i -e &quot;s#&lt;ECR_NAME&gt;#$ECR_NAME#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;IMAGE_TAG&gt;#$IMAGE_TAG#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;LOGS_GROUP&gt;#$LOGS_GROUP#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;TASK_FAMILY&gt;#$TASK_FAMILY#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;TASK_ROLE_NAME&gt;#$TASK_ROLE_NAME#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;CONTAINER_NAME&gt;#$CONTAINER_NAME#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;AWS_ACCOUNT_ID&gt;#$AWS_ACCOUNT_ID#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;EXECUTION_ROLE_NAME&gt;#$EXECUTION_ROLE_NAME#&quot; taskdef.json<br>      - sed -i -e &quot;s#&lt;AWS_DEFAULT_REGION&gt;#$AWS_DEFAULT_REGION#&quot; taskdef.json<br>      - echo &quot;$(cat taskdef.json)&quot;<br>      - echo Rewriting appspec file...<br>      - sed -i -e &quot;s#&lt;CONTAINER_NAME&gt;#$CONTAINER_NAME#&quot; appspec.yml<br>      - echo &quot;$(cat appspec.yml)&quot;<br><br>artifacts:<br>  files: <br>    - imageDetail.json<br>    - taskdef.json<br>    - appspec.yml</pre><p>imageDetail.json은 File만 작성합니다. 이것은 이미지 정의 파일 입니다.<br>참고로, Rolling과 Blue/Green으로 취급하고 있는 File명이 다르기 때문에, 1회차를 통해 해 주시면 좋을 것 같습니다. <a href="https://docs.aws.amazon.com/ko_kr/codepipeline/latest/userguide/file-reference.html">이미지 정의 파일 참조에 대해</a></p><p>taskdef.json은 AWS ECS의 Task Definition 파일입니다.<br>변수에 관해서는</p><ul><li><em>&lt;AWS_ACCOUNT_ID&gt;</em>: 기밀 정보이므로 AWS SSM Parameter store에서 가져옵니다.</li><li><em>&lt;IMAGE1_NAME&gt;</em>: imageDetail.json에서 얻은 Image URL로 자동으로 바뀝니다. (프로바이더가 CodeDeployToECS이기 때문에)</li><li>다른 변수는 AWS CodeBuild에서 설정 합니다.</li></ul><pre>{<br> &quot;containerDefinitions&quot;: [{<br>  &quot;name&quot;: &quot;&lt;CONTAINER_NAME&gt;&quot;,<br>  &quot;image&quot;: &quot;&lt;IMAGE1_NAME&gt;&quot;,<br>  &quot;essential&quot;: true,<br>  &quot;cpu&quot;: 256,<br>                &quot;memory&quot;: 512,<br>  &quot;portMappings&quot;: [{<br>   &quot;hostPort&quot;: 80,<br>   &quot;protocol&quot;: &quot;tcp&quot;,<br>   &quot;containerPort&quot;: 80<br>  }],<br>  &quot;logConfiguration&quot;: {<br>   &quot;logDriver&quot;: &quot;awslogs&quot;,<br>   &quot;options&quot;: {<br>    &quot;awslogs-group&quot;: &quot;&lt;LOGS_GROUP&gt;&quot;,<br>    &quot;awslogs-region&quot;: &quot;&lt;AWS_DEFAULT_REGION&gt;&quot;,<br>    &quot;awslogs-stream-prefix&quot;: &quot;terraform&quot;<br>   }<br>  }<br> }],<br> &quot;cpu&quot;: &quot;256&quot;,<br> &quot;memory&quot;: &quot;512&quot;,<br> &quot;taskRoleArn&quot;: &quot;arn:aws:iam::&lt;AWS_ACCOUNT_ID&gt;:role/&lt;TASK_ROLE_NAME&gt;&quot;,<br> &quot;executionRoleArn&quot;: &quot;arn:aws:iam::&lt;AWS_ACCOUNT_ID&gt;:role/&lt;EXECUTION_ROLE_NAME&gt;&quot;,<br> &quot;family&quot;: &quot;&lt;TASK_FAMILY&gt;&quot;,<br> &quot;networkMode&quot;: &quot;awsvpc&quot;,<br> &quot;requiresCompatibilities&quot;: [<br>  &quot;FARGATE&quot;<br> ]<br>}</pre><p>그렇다면 이하의 파일이 생겼을 것이므로 AWS CodeCommit에 git push합니다.</p><pre>.<br>├── Dockerfile<br>├── appspec.yml<br>├── buildspec.yml<br>├── imageDetail.json<br>├── src<br>│   └── index.html<br>└── taskdef.json</pre><h3>7. AWS CodeBuild의 Terraform 생성 및 구축</h3><p>AWS CodeBuild에 필요한 Policy를 생성합니다.</p><p>files/codebuild_policy.json.tpl</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:logs:${region}:${account_id}:log-group:/aws/codebuild/${codebuild_name}&quot;,<br>                &quot;arn:aws:logs:${region}:${account_id}:log-group:/aws/codebuild/${codebuild_name}:*&quot;<br>            ],<br>            &quot;Action&quot;: [<br>                &quot;logs:CreateLogGroup&quot;,<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::${bucket_name}/*&quot;<br>            ],<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:GetObjectVersion&quot;,<br>                &quot;s3:GetBucketAcl&quot;,<br>                &quot;s3:GetBucketLocation&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ecr:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ssm:GetParametersByPath&quot;,<br>                &quot;ssm:GetParameters&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:ssm:${region}:${account_id}:parameter/${param_store_name}&quot;<br>        }<br>    ]<br>}</pre><p>다음은 처리의 산출물을 저장하기 위해 Artifact용 Amazon S3 및 AWS Account ID를 관리하는 AWS SSM Parameter store를 생성합니다.<br>또한 AWS CodeBuild를 생성한 후, terraform apply까지 실행합니다.</p><pre>#--------------------------------------------------------------<br># S3<br>#--------------------------------------------------------------<br>resource &quot;aws_s3_bucket&quot; &quot;artifact&quot; {<br>  bucket = &quot;my-artifact2023&quot;<br><br>  tags = merge(var.tags, { &quot;Name&quot; = &quot;MyArtifact&quot; })<br>}<br><br>#--------------------------------------------------------------<br># SSM Parameter Store<br>#--------------------------------------------------------------<br>resource &quot;aws_ssm_parameter&quot; &quot;id&quot; {<br>  name  = &quot;MY_ACCOUNT_ID&quot;<br>  type  = &quot;String&quot;<br>  value = local.account_id<br>}<br><br>#--------------------------------------------------------------<br># CodeBuild<br>#--------------------------------------------------------------<br>resource &quot;aws_iam_role&quot; &quot;codebuild-role&quot; {<br>  name               = &quot;MyCodebuild-Role&quot;<br>  assume_role_policy = templatefile(&quot;./files/assumerole.json.tpl&quot;, { resource = &quot;codebuild&quot; })<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;codebuild-policy&quot; {<br>  role = aws_iam_role.codebuild-role.name<br>  policy = templatefile(&quot;./files/codebuild_policy.json.tpl&quot;, {<br>    region           = var.region<br>    account_id       = local.account_id<br>    codebuild_name   = aws_codebuild_project.main.name<br>    bucket_name      = aws_s3_bucket.artifact.id<br>    param_store_name = aws_ssm_parameter.id.name<br>  })<br>}<br><br>resource &quot;aws_codebuild_project&quot; &quot;main&quot; {<br>  name         = &quot;codebuild-fargate-cicd&quot;<br>  service_role = aws_iam_role.codebuild-role.arn<br><br>  artifacts {<br>    type = &quot;NO_ARTIFACTS&quot;<br>  }<br><br>  source {<br>    type     = &quot;CODECOMMIT&quot;<br>    location = aws_codecommit_repository.main.clone_url_http<br>  }<br><br>  source_version = &quot;main&quot;<br><br>  environment {<br>    compute_type    = &quot;BUILD_GENERAL1_SMALL&quot;<br>    image           = &quot;aws/codebuild/standard:5.0&quot;<br>    type            = &quot;LINUX_CONTAINER&quot;<br>    privileged_mode = true<br><br>    environment_variable {<br>      name  = &quot;AWS_DEFAULT_REGION&quot;<br>      value = var.region<br>    }<br><br>    environment_variable {<br>      name  = &quot;IMAGE_TAG&quot;<br>      value = &quot;latest&quot;<br>    }<br><br>    environment_variable {<br>      name  = &quot;ECR_NAME&quot;<br>      value = aws_ecr_repository.main.name<br>    }<br><br>    environment_variable {<br>      name  = &quot;CONTAINER_NAME&quot;<br>      value = var.container_name<br>    }<br><br>    environment_variable {<br>      name  = &quot;TASK_FAMILY&quot;<br>      value = aws_ecs_task_definition.main.family<br>    }<br><br>    environment_variable {<br>      name  = &quot;TASK_ROLE_NAME&quot;<br>      value = aws_iam_role.task_role.name<br>    }<br><br>    environment_variable {<br>      name  = &quot;EXECUTION_ROLE_NAME&quot;<br>      value = aws_iam_role.ecs_task_execution_role.name<br>    }<br><br>    environment_variable {<br>      name  = &quot;LOGS_GROUP&quot;<br>      value = var.cloudwatch_log_group_name<br>    }<br>  }<br>}</pre><h3>8. AWS CodeDeploy의 Terraform 생성 및 구축</h3><p>AWS CodeDeploy에 필요한 Policy를 생성합니다.</p><p>files/codedeploy_policy.json.tpl</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Action&quot;: [<br>                &quot;ecs:DescribeServices&quot;,<br>                &quot;ecs:CreateTaskSet&quot;,<br>                &quot;ecs:UpdateServicePrimaryTaskSet&quot;,<br>                &quot;ecs:DeleteTaskSet&quot;,<br>                &quot;cloudwatch:DescribeAlarms&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;sns:Publish&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:sns:*:*:CodeDeployTopic_*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:DescribeTargetGroups&quot;,<br>                &quot;elasticloadbalancing:DescribeListeners&quot;,<br>                &quot;elasticloadbalancing:ModifyListener&quot;,<br>                &quot;elasticloadbalancing:DescribeRules&quot;,<br>                &quot;elasticloadbalancing:ModifyRule&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;lambda:InvokeFunction&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:lambda:*:*:function:CodeDeployHook_*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:GetObjectVersion&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;s3:ExistingObjectTag/UseWithCodeDeploy&quot;: &quot;true&quot;<br>                }<br>            },<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;iam:PassRole&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;iam:PassedToService&quot;: [<br>                        &quot;ecs-tasks.amazonaws.com&quot;<br>                    ]<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>다음은 AWS CodeDeploy를 생성한 후, terraform apply까지 실행합니다.</p><pre>#--------------------------------------------------------------<br># CodeDeploy<br>#--------------------------------------------------------------<br>resource &quot;aws_iam_role&quot; &quot;codedeploy-role&quot; {<br>  name               = &quot;MyCodedeploy-Role&quot;<br>  assume_role_policy = templatefile(&quot;./files/assumerole.json.tpl&quot;, { resource = &quot;codedeploy&quot; })<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;codedeploy-policy&quot; {<br>  role   = aws_iam_role.codedeploy-role.name<br>  policy = templatefile(&quot;./files/codedeploy_policy.json.tpl&quot;, {})<br>}<br><br>resource &quot;aws_codedeploy_app&quot; &quot;main&quot; {<br>  compute_platform = &quot;ECS&quot;<br>  name             = &quot;codedeploy-fargate-cicd&quot;<br>}<br><br>resource &quot;aws_codedeploy_deployment_group&quot; &quot;main&quot; {<br>  app_name               = aws_codedeploy_app.main.name<br>  deployment_group_name  = &quot;codedeployGroup-fg&quot;<br>  deployment_config_name = &quot;CodeDeployDefault.ECSAllAtOnce&quot;<br>  service_role_arn       = aws_iam_role.codedeploy-role.arn<br><br>  blue_green_deployment_config {<br>    deployment_ready_option {<br>      action_on_timeout = &quot;CONTINUE_DEPLOYMENT&quot;<br>    }<br><br>    terminate_blue_instances_on_deployment_success {<br>      action                           = &quot;TERMINATE&quot;<br>      termination_wait_time_in_minutes = 1<br>    }<br>  }<br><br>  ecs_service {<br>    cluster_name = aws_ecs_cluster.main.name<br>    service_name = aws_ecs_service.main.name<br>  }<br><br>  deployment_style {<br>    deployment_option = &quot;WITH_TRAFFIC_CONTROL&quot;<br>    deployment_type   = &quot;BLUE_GREEN&quot;<br>  }<br>  auto_rollback_configuration {<br>    enabled = true<br>    events  = [&quot;DEPLOYMENT_FAILURE&quot;]<br>  }<br><br>  load_balancer_info {<br>    target_group_pair_info {<br>      prod_traffic_route {<br>        listener_arns = [aws_lb_listener.http.arn]<br>      }<br><br>      target_group {<br>        name = aws_lb_target_group.blue.name<br>      }<br><br>      target_group {<br>        name = aws_lb_target_group.green.name<br>      }<br>    }<br>  }<br><br>}</pre><h3>9. AWS CodePipeline의 Terraform 생성 및 구축</h3><p>AWS CodeCommit, CodeBuild, CodeDeploy를 빌드 했으므로 AWS CodePipeline을 구축합니다.<br>먼저 AWS CodePipeline에 필요한 Policy를 생성합니다.</p><p>files/codepipeline_policy.json.tpl</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Action&quot;: [<br>                &quot;iam:PassRole&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEqualsIfExists&quot;: {<br>                    &quot;iam:PassedToService&quot;: [<br>                        &quot;cloudformation.amazonaws.com&quot;,<br>                        &quot;elasticbeanstalk.amazonaws.com&quot;,<br>                        &quot;ec2.amazonaws.com&quot;,<br>                        &quot;ecs-tasks.amazonaws.com&quot;<br>                    ]<br>                }<br>            }<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codecommit:CancelUploadArchive&quot;,<br>                &quot;codecommit:GetBranch&quot;,<br>                &quot;codecommit:GetCommit&quot;,<br>                &quot;codecommit:GetUploadArchiveStatus&quot;,<br>                &quot;codecommit:UploadArchive&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codedeploy:CreateDeployment&quot;,<br>                &quot;codedeploy:GetApplication&quot;,<br>                &quot;codedeploy:GetApplicationRevision&quot;,<br>                &quot;codedeploy:GetDeployment&quot;,<br>                &quot;codedeploy:GetDeploymentConfig&quot;,<br>                &quot;codedeploy:RegisterApplicationRevision&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;elasticbeanstalk:*&quot;,<br>                &quot;ec2:*&quot;,<br>                &quot;elasticloadbalancing:*&quot;,<br>                &quot;autoscaling:*&quot;,<br>                &quot;cloudwatch:*&quot;,<br>                &quot;s3:*&quot;,<br>                &quot;sns:*&quot;,<br>                &quot;cloudformation:*&quot;,<br>                &quot;rds:*&quot;,<br>                &quot;sqs:*&quot;,<br>                &quot;ecs:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;lambda:InvokeFunction&quot;,<br>                &quot;lambda:ListFunctions&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;opsworks:CreateDeployment&quot;,<br>                &quot;opsworks:DescribeApps&quot;,<br>                &quot;opsworks:DescribeCommands&quot;,<br>                &quot;opsworks:DescribeDeployments&quot;,<br>                &quot;opsworks:DescribeInstances&quot;,<br>                &quot;opsworks:DescribeStacks&quot;,<br>                &quot;opsworks:UpdateApp&quot;,<br>                &quot;opsworks:UpdateStack&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;cloudformation:CreateStack&quot;,<br>                &quot;cloudformation:DeleteStack&quot;,<br>                &quot;cloudformation:DescribeStacks&quot;,<br>                &quot;cloudformation:UpdateStack&quot;,<br>                &quot;cloudformation:CreateChangeSet&quot;,<br>                &quot;cloudformation:DeleteChangeSet&quot;,<br>                &quot;cloudformation:DescribeChangeSet&quot;,<br>                &quot;cloudformation:ExecuteChangeSet&quot;,<br>                &quot;cloudformation:SetStackPolicy&quot;,<br>                &quot;cloudformation:ValidateTemplate&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;codebuild:BatchGetBuilds&quot;,<br>                &quot;codebuild:StartBuild&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;devicefarm:ListProjects&quot;,<br>                &quot;devicefarm:ListDevicePools&quot;,<br>                &quot;devicefarm:GetRun&quot;,<br>                &quot;devicefarm:GetUpload&quot;,<br>                &quot;devicefarm:CreateUpload&quot;,<br>                &quot;devicefarm:ScheduleRun&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;servicecatalog:ListProvisioningArtifacts&quot;,<br>                &quot;servicecatalog:CreateProvisioningArtifact&quot;,<br>                &quot;servicecatalog:DescribeProvisioningArtifact&quot;,<br>                &quot;servicecatalog:DeleteProvisioningArtifact&quot;,<br>                &quot;servicecatalog:UpdateProduct&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cloudformation:ValidateTemplate&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ecr:DescribeImages&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>그 후 AWS CodePipeline을 생성하여 terraform apply까지 실행합니다.</p><pre>#--------------------------------------------------------------<br># CodePipeline<br>#--------------------------------------------------------------<br>resource &quot;aws_iam_role&quot; &quot;codepipeline-role&quot; {<br>  name               = &quot;MyCodePipeline-Role&quot;<br>  assume_role_policy = templatefile(&quot;./files/assumerole.json.tpl&quot;, { resource = &quot;codepipeline&quot; })<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;codepipeline-policy&quot; {<br>  role   = aws_iam_role.codepipeline-role.name<br>  policy = templatefile(&quot;./files/codepipeline_policy.json.tpl&quot;, {})<br>}<br><br>resource &quot;aws_codepipeline&quot; &quot;main&quot; {<br>  name     = &quot;codepipeline-fargate-cicd&quot;<br>  role_arn = aws_iam_role.codepipeline-role.arn<br><br>  artifact_store {<br>    location = aws_s3_bucket.artifact.bucket<br>    type     = &quot;S3&quot;<br>  }<br>  # SOURCE<br>  stage {<br>    name = &quot;Source&quot;<br>    action {<br>      name             = &quot;Source&quot;<br>      category         = &quot;Source&quot;<br>      owner            = &quot;AWS&quot;<br>      provider         = &quot;CodeCommit&quot;<br>      version          = &quot;1&quot;<br>      output_artifacts = [&quot;SourceArtifact&quot;]<br><br>      configuration = {<br>        RepositoryName = aws_codecommit_repository.main.repository_name<br>        BranchName     = &quot;main&quot;<br>      }<br>    }<br>  }<br>  # BUILD<br>  stage {<br>    name = &quot;Build&quot;<br>    action {<br>      name             = &quot;Build&quot;<br>      category         = &quot;Build&quot;<br>      owner            = &quot;AWS&quot;<br>      provider         = &quot;CodeBuild&quot;<br>      version          = &quot;1&quot;<br>      input_artifacts  = [&quot;SourceArtifact&quot;]<br>      output_artifacts = [&quot;BuildArtifact&quot;]<br><br>      configuration = {<br>        ProjectName = aws_codebuild_project.main.name<br>      }<br>    }<br>  }<br>  # DEPLOY<br>  stage {<br>    name = &quot;Deploy&quot;<br>    action {<br>      name            = &quot;Deploy&quot;<br>      category        = &quot;Deploy&quot;<br>      owner           = &quot;AWS&quot;<br>      provider        = &quot;CodeDeployToECS&quot;<br>      version         = &quot;1&quot;<br>      input_artifacts = [&quot;BuildArtifact&quot;]<br><br>      configuration = {<br>        ApplicationName                = aws_codedeploy_app.main.name<br>        DeploymentGroupName            = aws_codedeploy_deployment_group.main.deployment_group_name<br>        AppSpecTemplateArtifact        = &quot;BuildArtifact&quot;<br>        AppSpecTemplatePath            = &quot;appspec.yml&quot;<br>        TaskDefinitionTemplateArtifact = &quot;BuildArtifact&quot;<br>        TaskDefinitionTemplatePath     = &quot;taskdef.json&quot;<br>        Image1ArtifactName             = &quot;BuildArtifact&quot;<br>        Image1ContainerName            = &quot;IMAGE1_NAME&quot;<br>      }<br>    }<br>  }<br>}</pre><p>AWS CodePipeline이 구축되면 바로 움직이기 시작하지만, 아래와 같이 Source에서 Deploy까지 실행하고 있는지 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*EruGrF6LBmfGaAOB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UlGCacoVVV9jy2tp" /></figure><p>AWS ALB DNS로 액세스하면 이전에 git push한 index.html이 표시됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaBRjElJkpI1uPHv" /></figure><p>이제 실제로 git push로 디플로이 자동화를 시도해 보겠습니다.<br>index.html의 배경을 Green으로 설정하고 git push origin main을 실행 합니다.</p><pre><br>&lt;-- 생략--&gt;<br>&lt;style&gt;<br>html { color-scheme: light dark; }<br>body { width: 35em; margin: 0 auto;<br>font-family: Tahoma, Verdana, Arial, sans-serif; <br>background-color:green;}<br>&lt;/style&gt;<br>&lt;-- 생략--&gt;</pre><p>AWS CodePipeline에서는 git commit 메시지 edit background color가 표시되어 Deploy까지 실행 중인지 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*hE-XEWpUmFhOw9De" /></figure><p>액세스해 보면 배경이 Green인 index.html이 표시 되어, 이제 git push배포를 자동화 할 수 있습니다</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dhT3i_N7IEh3NTp4" /></figure><h3>마지막으로</h3><p>계속 이 내용을 정리해보고 싶었는데, 마침내 블로그로 정리 할 수있었습니다.사람마다 다른 방법과 다른 접근 방법이 있을 수 있지만,이 블로그가 여러분에게 도움이 되었으면 합니다.<br>이상으로 Terraform을 사용한 AWS CodePipeline을 포함한 AWS Fargate 자동 디플로이에 대한 블로그였습니다. 읽어주셔서 감사드립니다.</p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/2bd00b05de0889#1.-terraform-main.tf%E3%81%AE%E4%BD%9C%E6%88%90%EF%BC%86%E6%A7%8B%E7%AF%89">https://zenn.dev/megazone_japan/articles/311faef395881d</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 정재윤님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center 박지은 매니저</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72eb90bd898f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/terraform-%EA%B8%B0%EB%B0%98-aws-codepipeline%EC%9D%84-%ED%8F%AC%ED%95%A8%ED%95%9C-aws-fargate%EC%9E%90%EB%8F%99-%EB%94%94%ED%94%8C%EB%A1%9C%EC%9D%B4-blue-green-72eb90bd898f">Terraform 기반 AWS CodePipeline을 포함한 AWS Fargate자동 디플로이 (Blue/Green)</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[인터넷 액세스 불가 환경에서 Amazon Bedrock API실행 하기]]></title>
            <link>https://medium.com/cloudvillains/%EC%9D%B8%ED%84%B0%EB%84%B7-%EC%95%A1%EC%84%B8%EC%8A%A4-%EB%B6%88%EA%B0%80-%ED%99%98%EA%B2%BD%EC%97%90%EC%84%9C-amazon-bedrock-api%EC%8B%A4%ED%96%89-%ED%95%98%EA%B8%B0-741eb51f998a?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/741eb51f998a</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[megazone]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 04:12:13 GMT</pubDate>
            <atom:updated>2024-01-10T04:14:02.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>들어가며</h3><p>블로그 컨텐츠 글감을 고려하던 중 Amazon Bedrock에 대해 다뤄본적이 없다는것을 깨달았고, 인터넷 액세스 불가 환경에서 실행 가능할지 생각하다가 실제로 검증 작업을 진행 해 보았는데요, 해당 내용을 게시글을 통해 공유 드리겠습니다.</p><h3>1. 지침</h3><ul><li>Bedrock API를 호출하는 주체는 인터넷 액세스 불가 환경에 두었습니다. 이번에는 인터넷 액세스 불가로 한 SageMaker노트북 인스턴스 (버지니아 북부 리전 프라이빗 서브넷에 붙임)를 사용하였습니다.</li><li>Bedrock용 vpc엔드포인트를 사용하였습니다.</li><li>필요한 데이터가 있다면 S3에 둡니다.</li><li>세세한 제어가 가능할지는 확인이 필요합니다.</li></ul><h3>2. 검증</h3><p><a href="https://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/api-setup.html">https://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/api-setup.html</a></p><p>상기 문서의 셋업 방법을 참고하면서 필요에 따라 수정을 추가 해 나가겠습니다.</p><h4>모델 액세스를 유효화</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5xerOgS9Moa3Ttj" /></figure><p><a href="https://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-access.html">https://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-access.html</a></p><p>먼저 모델을 사용하기 전에 그 모델에 액세스 요청을 합니다.</p><p>이번에는 Claude v2를 사용하겠습니다.</p><h4>SageMaker 노트북 인스턴스 준비</h4><p>버지니아 북부 리전에 하기 설정을 가진 노트북 인스턴스를 생성 해 주세요.</p><ul><li>프라이빗 서브넷에 연결 합니다. NAT Gateway는 이용 하지 않습니다.</li><li>Direct internet access : Disabled</li><li>롤은 문서에 기재 권한 범위로 설정 합니다.</li></ul><p>VPC엔드포인트</p><ul><li>com.amazonaws.us-east-1.s3</li><li>aws.sagemaker.us-east-1.notebook</li><li>com.amazonaws.us-east-1.sagemaker.api</li><li>com.amazonaws.us-east-1.bedrock</li><li>com.amazonaws.us-east-1.bedrock-runtime</li></ul><p>상기를 유효화 합니다.</p><h4>Jupyter로 코드 넣기</h4><p>문서 대로 샘플 코드를 만듭니다.</p><p><a href="https://docs.aws.amazon.com/ko_kr/bedrock/latest/APIReference/API_runtime_InvokeModel.html">https://docs.aws.amazon.com/ko_kr/bedrock/latest/APIReference/API_runtime_InvokeModel.html</a></p><blockquote>지정된 Amazon Bedrock모델을 시작하고 리퀘스트 본문에 제공 된 입력을 사용하여 추론을 실행 합니다. 텍스트 모델, 이미지 모델, 임베디드 모델 추론을 실행 하기 위해서는 InvokeModel을 사용합니다.</blockquote><blockquote>헤더에 지정한 modelId는 사용하는 모델의 종류에 따라 다릅니다.</blockquote><blockquote>베이스 모델을 사용하는 경우는 모델 ID또는 그 ARN을 지정 합니다.</blockquote><blockquote>Provisioned 모델을 사용하는 경우는 ProvisionedModelName, 또는 Provisioned Throughput을 만들 때 반환되는 provisionedModelArn을 지정합니다. 사용자 지정 모델을 사용하는 경우 먼저 해당 모델의 Provisioned Throughput을 구입합니다. (자세한 내용은 Amazon Bedrock 사용 설명서의 Provisioned Throughput 참조) 그 후 ProvisionedModelName 또는 ProvisionedModelArn을 지정합니다. 리퀘스트 본문에서 응답에 영향을 미치는 프롬프트 및 추론 매개 변수를 지정합니다.</blockquote><p>‘Invoke Model’ API 설명은 상기와 같습니다.</p><pre>import boto3<br>import json<br>bedrock = boto3.client(service_name=&#39;bedrock-runtime&#39;)<br>body = json.dumps({<br>&quot;prompt&quot;: &quot;\n\nHuman:Please explain AWS in a way that even kindergarteners can understand\n\nAssistant:&quot;,<br>&quot;max_tokens_to_sample&quot;: 300,<br>&quot;temperature&quot;: 0.1,<br>&quot;top_p&quot;: 0.9,<br>})<br>modelId = &#39;anthropic.claude-v2&#39;<br>accept = &#39;application/json&#39;<br>contentType = &#39;application/json&#39;<br>response = bedrock.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)<br>response_body = json.loads(response.get(&#39;body&#39;).read())<br># text<br>print(response_body.get(&#39;completion&#39;))</pre><p>prompt 부분은 질문 변경을 했습니다.</p><h4>실행 결과</h4><blockquote>Here is an explanation of AWS for kindergarteners:</blockquote><blockquote>AWS is like a really big playground with lots of fun things to play with! There are swings, slides, sandboxes, and jungle gyms. Each thing you want to play with is called a “service.”</blockquote><blockquote>If you want to go down the slide, you use the “EC2” slide service. If you want to swing, you use the “S3” swing service. There are services for all kinds of fun activities!</blockquote><blockquote>The playground monitor is called AWS. AWS makes sure all the equipment is safe and lets you know how long you can play with each thing. AWS gives you a bracelet that tracks how much time you spend playing.</blockquote><blockquote>At the end of recess, AWS tells your teacher how long you played on everything so your parents know how much to pay for the playground. The more things you play with, the more money it costs. But AWS lets you play with lots of fun stuff!</blockquote><blockquote>So AWS is like the biggest, funnest playground ever that lets you play with super cool toys and keeps everything working nicely! The end.</blockquote><blockquote>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</blockquote><blockquote>유치원생을 위한 AWS설명입니다 :</blockquote><blockquote>AWS는 재미있는 놀이기구가 많이 있는 큰 놀이터와 같습니다! 그네, 미끄럼틀, 모래밭, 정글 체육관 등 놀이기구는 각각 ‘서비스’ 라고 불립니다.</blockquote><blockquote>미끄럼틀에서 미끄러지고 싶다면 ‘EC2’ 라는 미끄럼틀 서비스를 사용합니다. 그네의 경우 ‘S3’와 같이 모든 종류의 재미있는 활동을 위한 서비스들이 있습니다!</blockquote><blockquote>놀이터를 감시하는 사람은 AWS라고 불립니다. AWS는 모든 놀이터의 안전성을 확인하고 각각의 놀이터에서 놀 수 있는 시간을 알려줍니다. AWS는 놀았던 시간이 기록된 팔찌를 줍니다.</blockquote><blockquote>휴식 시간이 끝나면 AWS는 놀이터에서 놀았던 시간을 교사에게 보고합니다. 논 것이 많을수록 그만큼 돈이 듭니다. 그렇지만 AWS는 즐거운 것을 통해 많이 놀게 해줍니다 !</blockquote><blockquote>그래서 AWS는 멋진 장난감으로 놀 수 있고, 모든 것이 잘 작동하는, 가장 크고 즐거운 놀이터 같은 것입니다! 끝.</blockquote><p>AWS를 유치원생도 알기 쉽게 설명하면 위와 같습니다.</p><h4>추가로</h4><p><a href="https://docs.aws.amazon.com/ko_kr/service-authorization/latest/reference/list_amazonbedrock.html">https://docs.aws.amazon.com/ko_kr/service-authorization/latest/reference/list_amazonbedrock.html</a></p><p>이 게시글을 작성한 2023년 12월 15일 시점의 최신판에서는 조건 키 등의 제한은 불가 한 것 같습니다. (VPC Config로 엄밀한 제어가 가능하지 않을까 싶어서 찾아 봤습니다)</p><p>리소스 타입으로 foundation-model 제어 등 가능한 것 같습니다.</p><h3>마지막으로</h3><p>이상으로 간단하게 검증 해 본 내용은 작성한 게시글 입니다.</p><p>누군가에게 참고가 된다면 좋을 것 같습니다.</p><p>지금까지 읽어 주셔서 감사드립니다.</p><p>번역 : Cloud Technology Center 박지은 매니저</p><p>원문게시글 :</p><p><a href="https://qiita.com/gahirosan/items/29c5858e112a8af7700a">https://qiita.com/gahirosan/items/29c5858e112a8af7700a</a></p><p><a href="https://qiita.com/advent-calendar/2023/megazonejapan?fbclid=IwAR336c6-ITdmMXeKJ4Rm3aKtjCDDkpz-brjLQoSNED25Gfax4sCtuPcZ6k0">Megazone Japan Advent Calendar 2023</a>에 업로드 중인 게시글로 작성자 Aga님의 동의를 얻어 번역한 게시글 입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=741eb51f998a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/%EC%9D%B8%ED%84%B0%EB%84%B7-%EC%95%A1%EC%84%B8%EC%8A%A4-%EB%B6%88%EA%B0%80-%ED%99%98%EA%B2%BD%EC%97%90%EC%84%9C-amazon-bedrock-api%EC%8B%A4%ED%96%89-%ED%95%98%EA%B8%B0-741eb51f998a">인터넷 액세스 불가 환경에서 Amazon Bedrock API실행 하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PartyRock으로 캐릭터를 만들어 보았습니다!]]></title>
            <link>https://medium.com/cloudvillains/partyrock%EC%9C%BC%EB%A1%9C-%EC%BA%90%EB%A6%AD%ED%84%B0%EB%A5%BC-%EB%A7%8C%EB%93%A4%EC%96%B4-%EB%B3%B4%EC%95%98%EC%8A%B5%EB%8B%88%EB%8B%A4-ded5cda9f654?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ded5cda9f654</guid>
            <category><![CDATA[party-rock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[megazone]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 04:56:47 GMT</pubDate>
            <atom:updated>2023-12-18T05:00:06.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>들어가며</h3><p>이번에 AWS 에서 출시된 <a href="https://aws.amazon.com/ko/about-aws/whats-new/2023/11/partyrock-amazon-bedrock-playground/?nc1=h_ls">PartyRock</a> 서비스를 사용해 보았습니다. PartyRock은 Amazon Bedrock을 기반으로 한 Generative AI Apps 서비스입니다. 간단한 UI로 손쉽게 조작하면서 Generative AI Apps를 생성할 수 있습니다. 예를 들어, 게임 스토리 작성이나 가상 캐릭터 생성 등 아이디어만 있으면 다양한 AI Apps를 만들 수 있다고 합니다. 현재 <strong>기간 한정 무료</strong>이므로 PartyRock를 체험하기에 최적의 타이밍이라는 생각이 듭니다.</p><h3>AI App 만들기</h3><p>이번 게시글에서는 나의 애완 동물 히어로 캐릭터 생성 앱을 만들어 보았습니다.<br>자세한 내용은 아래의 순서로 설명합니다.</p><h3>PartyRock Login</h3><p><a href="https://partyrock.aws/">PartyRock</a>으로 이동하여 오른쪽 상단의 Sign in을 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uv4eSjpkuzYcYwxR" /></figure><p>그러면 Google, Apple, Amazon 계정에서 Sign in을 할 수 있습니다.<br>(레코드판이 돌아가는 UI가 재미 있네요 👍)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D984NzXsoR93APp-" /></figure><p>Sign in한 다음 PartyRock 이름을 입력하고 Submit을 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5q8lmoj5SyIXt07B" /></figure><p>PartyRock을 만든 후 Top Page로 이동합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xYM9PoujLfG2qEG8" /></figure><h3>Build App</h3><p>Top Page에서 Build your own app를 클릭하여 자신의 앱을 만듭니다.<br>자신이 원하는 내용을 입력하게 되는데요, 이번에는 What is my pet’s super hero name?을 입력한 후 Generate app를 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O66EU0bqAEWG8szZ" /></figure><p>여기에서 자신의 앱을 만들 수 있습니다. 구체적으로는 “What is my pet’s super hero name?”이라는 테마를 기반으로 애완 동물 히어로 이름을 생성하는 앱을 구축합니다. 다음과 같이 text prompt를 사용하여 Widget에서 쉽게 앱을 만들 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e8LJcLpaKSjFcAuV" /></figure><p>pet name에 Sparky를 입력하면 superhero name에서 몇 가지 예가 나타납니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f4nsEJV3Ex9T4f3V" /></figure><p>그러나 Sparky라는 애완동물 이름만으로 애완동물 히어로 이름을 생성하는 것은 Generative AI를 충분히 활용한다고 말할 수 없습니다.<br>더 관련성이 높은 결과를 얻기 위해 추가 Widget을 사용해 봅시다.</p><h3>Add Widget</h3><p>화면 오른쪽 상단의 Add Widget을 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*85QDSYR4jxQWFmvk" /></figure><p>위젯 하단에 새로운 위젯이 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8htVXwedTpzkvIJD" /></figure><p>해당 Widget의 ‘User Input’을 클릭하면 오른쪽에 ‘Edit Widget’이라는 입력란이 나타 납니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zT3EM5NGpsu023v_" /></figure><p>다음 값을 입력하고 Save를 클릭합니다.</p><pre>Widget Title : pet description<br>Placeholder : Describe your pet&#39;s personality in a few words</pre><p>다른 Widget을 추가하고 다음 값을 입력하고 Save를 클릭합니다.</p><pre>Widget Title : favorite horoes<br>Placeholder : Describe your favorite heroes</pre><p>이제 이 두 Widget을 추가하여 보다 관련성 있는 결과를 얻을 준비가 되었습니다.</p><pre>Widget추가 전 :애완동물의 이름에서 애완동물 히어로 이름을 생성<br>Widget추가 후 :애완동물의 성격과 좋아하는 히어로 이름에 근거한 애완동물 히어로 이름 생성</pre><p>여기까지 되었다면 다음과 같은 4개의 Widget이 만들어져 있을 것 입니다.<br>참고로 Widget은 드래그 하여 크기와 위치를 조정할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8jR2rOSH4Fu-83wL" /></figure><p>방금 추가한 위젯에 예를 들어 다음 값을 입력합니다.</p><pre>pet description : a poodle dog<br>favorite horoes : the spiderman</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NqVIxbxVWKG6exn1" /></figure><p>그렇지만 superhero name 위젯에는 반영되어 있지 않을 것 입니다. 오른쪽 상단의 편집을 클릭하여 프롬프트를 수정 해 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*VvAJ9eyRtn5mb2ad" /></figure><h3>애완 동물 히어로 이름 생성</h3><p>Prompt에 다음 내용을 입력하고 Save를 클릭합니다.<br>내용은 ‘애완 동물 명, 설명, 좋아하는 히어로 명에 근거해, 창의적인 히어로 명을 생각해낸다.’ 라는 의미입니다.<br>이미 아셨겠지만, 노란색으로 블록 된 부분은 위젯을 나타냅니다. 이 사양은 <em>@Widget Name</em>입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*W65c71yVrTtvjuGz" /></figure><p>superhero name 위젯에 Captain Poodle이 생성 되었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C0bmky6vAVCok2J_" /></figure><h3>애완 동물 히어로 캐릭터 생성</h3><p>추가로 이 애완동물 히어로의 캐릭터를 생성해 봅니다.<br>위에서 언급했듯이 위젯을 추가하고 이미지 생성을 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iFBfbL2vYLdTQThO" /></figure><p>캐릭터 Widget에는 다음 정보를 입력한 다음 Save를 클릭 합니다.<br>superhero name은 특정 조건에 기반한 결과이며 superhero name의 위젯에서 캐릭터 이미지를 생성하려면 해당 프롬프트를 작성해야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*D11ZKrQ2KiLTwfi6" /></figure><p>그 결과, 왕관을 머리에 쓰고 있는 Captain Poodle이라는 애완동물 히어로가 생겼습니다!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UDwPD3P2RGwCnIMb" /></figure><p>참고로 Retry를 클릭하여 다른 결과를 얻을 수도 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*Q4RW--gJjw9B1TVg" /></figure><h3>AI 앱 공유</h3><p>이런 식으로 놀이 목적으로 즐길 수 있지만, 만든 AI App을 활용할 수 있도록 다른 사람과 공유할 수도 있습니다. 오른쪽 상단에서 Make public and Share를 클릭 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*0bO631OE70_rdXjW" /></figure><p>다음 내용이 나타나면 Copy link to clipboard를 클릭하여 공유합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*Q2-x4Hx-dUD02B_W" /></figure><p>실제로 복사한 링크에 액세스하면 마치 템플릿처럼 각 위젯이 깔끔하게 배치됩니다. 각각의 Widget에는 생성하고 싶은 내용을 입력하여 애완동물 히어로 이름이나 캐릭터를 쉽게 생성할 수 있습니다. 그리고 원하는 대로 Widget을 조정하여 자신만의 즐겨찾기를 만들 수도 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6MbGGWd1207jZpXY" /></figure><h3>마지막으로</h3><p>Generative AI가 등장한 이후로 Prompt Engineering 작업이 늘고 있다고 느낍니다. 그리고 PartyRock을 사용해보면서 역시 그러한 작업이 가장 중요한 포지션을 차지할 가능성이 있다고 생각했습니다. PartyRock은 AI 개발자가 아니어도 이용할 수 있으므로 그 점이 매력적이라 생각되었고, UI도 간단하여 매우 이해하기 쉬웠습니다. 서비스는 2023년 11월 초순에 발표된 따끈따끈한 서비스로, 무료 기간 중에 시험해 보는 것을 추천 드립니다.<br>이상, PartyRock에서 캐릭터를 만들어 본 내용에 대한 게시글 이었습니다. 지금까지 읽어 주셔서 감사드립니다.</p><p>번역 : Cloud Technology Center 박지은 매니저</p><p>원문게시글 : <a href="https://qiita.com/jeayoon/items/d89efe88c15045adcfdd">https://qiita.com/jeayoon/items/d89efe88c15045adcfdd</a></p><p><a href="https://qiita.com/advent-calendar/2023/megazonejapan?fbclid=IwAR336c6-ITdmMXeKJ4Rm3aKtjCDDkpz-brjLQoSNED25Gfax4sCtuPcZ6k0">Megazone Japan Advent Calendar 2023</a>에 업로드 중인 게시글로 작성자 정재윤님의 동의를 얻어 번역한 게시글 입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ded5cda9f654" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/partyrock%EC%9C%BC%EB%A1%9C-%EC%BA%90%EB%A6%AD%ED%84%B0%EB%A5%BC-%EB%A7%8C%EB%93%A4%EC%96%B4-%EB%B3%B4%EC%95%98%EC%8A%B5%EB%8B%88%EB%8B%A4-ded5cda9f654">PartyRock으로 캐릭터를 만들어 보았습니다!</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon SageMaker Studio에서 삭제하지 않은 리소스 확인 하기]]></title>
            <link>https://medium.com/cloudvillains/amazon-sgaemaker-studio%EC%97%90%EC%84%9C-%EC%82%AD%EC%A0%9C%ED%95%98%EC%A7%80-%EC%95%8A%EC%9D%80-%EB%A6%AC%EC%86%8C%EC%8A%A4-%ED%99%95%EC%9D%B8-%ED%95%98%EA%B8%B0-43f4037c0792?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f4037c0792</guid>
            <category><![CDATA[amazon-sagemaker]]></category>
            <category><![CDATA[megazone]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 01:08:57 GMT</pubDate>
            <atom:updated>2023-12-19T06:55:11.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>들어가며</h3><p>Amazon SageMaker Studio는 여러 MLOPS기능을 제공 하고 있지만, 여러 리소스를 사용 하는 도중에 리소스 삭제를 잊어버려 과금이 발생하는 경우가 있습니다. (사실 저도 있었습니다.)</p><p>특히 Amazon SageMaker Data Wrangler는 편리한 반면, 시간 마다 요금이 발생하기 때문에, 리소스 삭제를 잊게 되면 엄청난 돈이 들게 됩니다.</p><p>IDLE상태 리소스가 있는 경우 (자동 셧다운이 아닌) 관리자나 유저가 리소스 삭제를 잊지 않았는지 확인 할 수 있도록 되어 있습니다. 본 게시글에서는 해당 내용에 대해 설명 드리도록 하겠습니다.</p><h3>개요</h3><ol><li>요금에 대해</li><li>환경 가정</li><li>Lambda 함수의 생성</li><li>실행 결과</li></ol><h3>1. 요금에 대해</h3><p><a href="https://aws.amazon.com/jp/blogs/news/save-costs-by-automatically-shutting-down-idle-resources-within-amazon-sagemaker-studio/">https://aws.amazon.com/jp/blogs/news/save-costs-by-automatically-shutting-down-idle-resources-within-amazon-sagemaker-studio/</a></p><p>(*번역자 주 : 해당 내용은 한국어 혹은 영어로 게시되어 있지 않은 게시글 이기 때문에 자동 번역 기능을 사용하여 확인 하시는 것을 추천 드립니다)</p><blockquote>발생하는 비용은 인스턴스 타입에 근거 하고 있고, 인스턴스 마다 개별 청구 됩니다. 과금은 인스턴스 생성 시에 개시 되어 인스턴스 상 모든 애플리케이션이 셧다운 되거나 인스턴스 다운 된 때에 정지 합니다.</blockquote><blockquote>인스턴스 상 실행 되어 있는 노트북을 셧다운 해도 인스턴스를 셧다운 하지 않으면 과금은 계속 됩니다.</blockquote><blockquote>여러 노트북을 다른 커널로 기동했다고 해도 같은 인스턴스 타입인 경우 노트북은 같은 인스턴스 상에서 실행 됩니다. 복수의 노트북이 열려있다고 해도 실행 중인 인스턴스가 1대인 경우는 그 1대의 인스턴스 기동 시간에 대해서만 과금 됩니다.</blockquote><blockquote>노트북을 셧다운 하면 노트북 자체에서는 삭제 되지 않지만, 저장 되지 않은 데이터를 잃을 수 있습니다.</blockquote><p>요금에 대해서는 상기 페이지가 알기 쉬울것으로 생각 됩니다.</p><p>이번에는 커널 게이트 웨이 애플리케이션과 SageMaker Data Wrangler리소스를 테스트 해 보겠습니다.</p><h3>2. 환경 가정</h3><ul><li>Domain</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*8RKsOsXq1ScvNyNk.png" /></figure><p>복수 도메인이 같은 리전에 존재 해 있는 환경을 가정 하고 있습니다. 이번에는 테스트로 2가지 도메인을 버지니아 북부 리전으로 생성 해 보겠습니다.</p><ul><li>User Profile</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_5EZ1sLZ6djoyWNh.png" /></figure><p>test-domain-1에는 2가지 유저 프로파일이 존재 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eaXSvdZi9mVJtcfe.png" /></figure><p>test-domain-2에는 1개의 유저 프로파일이 존재 합니다.</p><ul><li>Resource</li></ul><p>각각 유저 프로파일이 커널 게이트 웨이 애플리케이션과 Data Wangler리소스를 각각 시작 시키고 처리를 실행 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*DnOsN35wF8E0n_Hy.png" /></figure><p>test-domain-1에 속하는 user01은 Data Wrangler용 리소스를 셧다운 한 것이지만, 커널 게이트웨이 애플리케이션을 기동한 채로 방치합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*_yV4BSdoeJoXEX9n.png" /></figure><p>test-domain-1에 속하는 user02는 커널 게이트웨이 애플리케이션을 셧다운 한 것이지만, Data Wrangle용 리소스를 기동한 채로 방치합니다.</p><p><strong>* 인스턴스 셧다운에 대해</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*fuDliDeo73NfoWzc.png" /></figure><p>인스턴스를 삭제 하기 위해서는 애플리케이션을 삭제해야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*XfAwPYIubEhLPgrx.png" /></figure><p>커널 게이트웨이 애플리케이션을 삭제하니 ml.t3.medium의 인스턴스가 동시에 셧다운 했습니다.</p><ul><li>Lambda</li></ul><p>이번에는 메인마다 Lambda함수를 준비 합니다.</p><p>test-domain-1용의 Lambda함수를 실행하여 리소스를 장시간 IDLE상태인 채로 유저를 특정 합니다.</p><p>이번 경우에는 test-domain-1 도메인에 속한 유저 (user01/user02)2명이 리소스를 삭제하는것을 잊었기 때문에 2명의 유저명을 Lambda함수로 취득 할 수 있다면 좋습니다.</p><ul><li>CloudWatch Logs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u6LR0zqdKkiilKOA.png" /></figure><ul><li>/aws/sagemaker/studio의 로그 그룹을 확인 합니다.</li><li>커널 게이트 웨이/Data Wrangler리소스 어느 쪽도 같은 애플리케이션 타입으로서 로그 스트림이 만들어 집니다.</li></ul><p><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/logging-cloudwatch.html">Log Amazon SageMaker Events with Amazon CloudWatch</a></p><pre>[domain-id]/[user-profile-name]/[app-type]/[app-name]</pre><p>상기 로그 스트림이름으로 ‘어느 도메인인지’ ‘어느 유저 프로파일인지’ ‘애플리케이션 타입’ ‘애플리케이션 이름’을 식별 가능합니다.</p><h3>3. Lambda함수의 생성</h3><p>※설정</p><p>Runtime: Python 3.11</p><p>Architecture: x86_64</p><p>Lambda함수에 붙이는 IAM롤은 ‘CloudWatch Logs’, ‘SageMaker’의 권한을 적절하게 추가 해 주세요.</p><p>※코드</p><p>※Parameter섹션의 3가지 파라미터는 환경에 맞춰 변경 해 주세요.</p><pre>import boto3<br>from datetime import datetime, timezone, timedelta<br>jst = timezone(timedelta(hours=9), &#39;JST&#39;)<br><br><br># Parameter<br>threshold = 86400 #tolerable time for idle state<br>target_region = &quot;us-east-1&quot; #region<br>domain_id = &quot;xxxxxxxxxxxx&quot; #domain id<br><br><br><br>def list_target_user_profile(specified_domain_id, client):<br>    <br>    profiles = []<br>    <br>    # Check the UserProfile Name corresponding to the specified domain name and store it in the list<br>    for profile in client.list_user_profiles(DomainIdEquals = specified_domain_id)[&#39;UserProfiles&#39;]:<br>        name = profile[&#39;UserProfileName&#39;]<br>        profiles.append(name)<br>            <br>    return profiles<br><br>def list_target_app(userProfiles, client):<br>    <br>    apps = []<br>    <br>    # Check Apps per UserProfile and store in list<br>    # Only when the application type is kernelGateway and the status is Inservice, it is the target of storage.<br>    for i in userProfiles:<br>        user = i<br>        for n in client.list_apps(UserProfileNameEquals = i)[&#39;Apps&#39;]:<br>            if len(n) &gt; 0 and n[&#39;AppType&#39;] == &#39;KernelGateway&#39; and n[&#39;Status&#39;] == &#39;InService&#39;:<br>                user = n[&#39;UserProfileName&#39;]<br>                app = n[&#39;AppName&#39;]<br>                dict= {}<br>                dict[user] = app<br>                apps.append(dict)<br>        <br>    return apps<br>    <br>    <br>def search_idle_instace(apps, client):<br>    <br>    target_user = []<br>    <br>    # Compare current time and log update date<br>    # If the difference is greater than or equal to the threshold, store in the list<br>    for i in apps:<br>        for d in i:<br>            response = client.describe_log_streams(<br>            logGroupName=&#39;/aws/sagemaker/studio&#39;,<br>            logStreamNamePrefix = f&#39;{domain_id}/{d}/KernelGateway/{i[d]}&#39;,<br>            descending=True,<br>            limit = 1<br>            )<br>            <br>            modified_time = response[&#39;logStreams&#39;][0][&#39;lastEventTimestamp&#39;]<br>            time = datetime.fromtimestamp(modified_time/1000, jst)<br>            print(time)<br>            <br>            dt = datetime.now(jst)<br>            print(dt)<br>            <br>            diff = dt - time<br>            print(diff)<br>            <br>            d_diff = diff.days * 86400<br>            sum_diff = d_diff + diff.seconds<br>            message = f&quot;user_name:{d}, diff:{sum_diff}\n&quot;<br>            print(message)<br><br>            <br>            if sum_diff &gt; threshold and d not in target_user:<br>                target_user.append(d)<br>                <br>    return target_user<br>    <br>    <br>def lambda_handler(event, context):<br>    <br>    user_profiles = []<br>    <br>    sm_client = boto3.client(&quot;sagemaker&quot;, target_region)<br>    cw_logs_client = boto3.client(&#39;logs&#39;, target_region)<br><br>    # Stores the names of UserProfiles belonging to the domain<br>    user_profiles = list_target_user_profile(domain_id, sm_client)<br>    print(user_profiles)<br>    <br>    # Define the correspondence between UserProfiles and running applications<br>    apps = list_target_app(user_profiles, sm_client)<br>    print(apps)<br>    <br>    # Check the application log to see which applications are in idle status<br>    target_user = search_idle_instace(apps, cw_logs_client)<br>    print(target_user)</pre><h3>4. 실행 결과</h3><p>Lambda 함수를 실행 합니다.</p><p>24시간(86400초)경과 이후로 실행 하고 있습니다.</p><pre># result(list_target_user_profile)<br>[&#39;user02&#39;, &#39;user01&#39;]<br><br># result(list_target_app)<br>[{&#39;user02&#39;: &#39;sagemaker-data-wrang-ml-m5-4xlarge-xxxxxxxxxxxxxxxxxxxxxxxx&#39;}, {&#39;user01&#39;: &#39;sagemaker-data-scienc-ml-t3-medium-xxxxxxxxxxxxxxxxxxxxxxxxx&#39;}]<br><br># result(search_idle_instace)<br>2023-11-17 11:04:42.316000+09:00<br>2023-11-18 12:25:04.657602+09:00<br>1 day, 1:20:22.341602<br>user_name:user02, diff:91222<br><br>2023-11-17 10:25:06.861000+09:00<br>2023-11-18 12:25:04.689970+09:00<br>1 day, 1:59:57.828970<br>user_name:user01, diff:93597<br><br># target_user list<br>[&#39;user02&#39;, &#39;user01&#39;]</pre><p>test-use-1에 소속 해 있고, 또한 IDLE상태의 리소스를 가진 유저 이름이 취득 되어 있습니다.</p><h3>마지막으로</h3><p>이번에 준비한 Lambda를 EventBridge + SNS와 연계 시켜 일상적으로 정기 실행 시키면 관리자나 유저가 리소스 삭제를 잊지 않았는지 확인 가능합니다. 다양하게 어레인지 해 보시길 바랍니다.</p><p>지금까지 읽어 주셔서 감사합니다 !</p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/e365cea61a7af0">https://zenn.dev/megazone_japan/articles/e365cea61a7af0</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 아가(阿河)님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center 박지은 매니저</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f4037c0792" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/amazon-sgaemaker-studio%EC%97%90%EC%84%9C-%EC%82%AD%EC%A0%9C%ED%95%98%EC%A7%80-%EC%95%8A%EC%9D%80-%EB%A6%AC%EC%86%8C%EC%8A%A4-%ED%99%95%EC%9D%B8-%ED%95%98%EA%B8%B0-43f4037c0792">Amazon SageMaker Studio에서 삭제하지 않은 리소스 확인 하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Systems Manager를 통한 Amazon RDS 자동 정지 및 시작]]></title>
            <link>https://medium.com/cloudvillains/aws-systems-manager%EB%A5%BC-%ED%86%B5%ED%95%9C-amazon-rds-%EC%9E%90%EB%8F%99-%EC%A0%95%EC%A7%80-%EB%B0%8F-%EC%8B%9C%EC%9E%91-fc3924da471c?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3924da471c</guid>
            <category><![CDATA[amazon-rds]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[megazone]]></category>
            <category><![CDATA[aws-system-manager]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 03:15:25 GMT</pubDate>
            <atom:updated>2023-11-02T00:37:18.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>개요</h3><p>이번 게시글에서는 AWS Systems Manager(이하SSM이라고 함)를 사용한 Amazon RDS(이하RDS라 함)의 자동 정지 및 시작에 대해 설명하겠습니다. 제목대로 RDS 비용 절감에 도움이 될 수 있고, 또한 심플하게 대응할 수 있는 것이 메리트라고 생각됩니다. 이번에 구현할 내용은 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7nuaFR1r_cFKtby" /></figure><p>SSM의 기능인 State Manager로 RDS를 중지하고 시작을 구성합니다. State Manager는 AWS 리소스를 정의된 상태로 유지하는 프로세스를 자동화하는 것이지만, 구체적인 관리 내용은 AWS Console의 AWS Systems Manager &gt; Documents 에서 확인하는 것을 추천 드립니다.</p><p>이 설정에 대한 전제 조건은 RDS가 생성되어 있다는 조건이며, 구성 순서는 이하와 같습니다.</p><ol><li>IAM Policy 생성</li><li>IAM Role 생성</li><li>SSM(RDS Stop) 생성</li><li>SSM(RDS Start) 생성</li><li>동작 결과</li></ol><h3>Hands-on</h3><h4>1. IAM Policy 생성</h4><p>SSM에 필요한 IAM Role 및 Policy를 생성합니다. 우선은 Policy부터 생성 해 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S4HykX3sPJ3PBPki" /></figure><p>Step1 : 다음 JSON으로 설정합니다.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;RdsStartStop&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;rds:StopDBInstance&quot;,<br>                &quot;rds:StartDBInstance&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;${RDS_ARN}&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;RdsDescribe&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;rds:DescribeDBInstances&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>Step2 : Policy명을 입력하여 Policy를 만듭니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xXvnlRqN1H4IqThY" /></figure><h4>2. IAM Role 생성</h4><p>다음은 Policy를 연결하여 AWS 서비스가 가능한 것을 정의합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BETe7Iboj6WEkYkF" /></figure><p>Step1 :</p><pre>- Trusted entity type : AWS service<br>- Use case &gt; Service or use case : Systems Manager<br>- Use case &gt; Use case : Systems Manager</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNaGPpHGVIfrVsK_" /></figure><p>Step2 :</p><pre>- Permissions policies : 조금 전 생성한 Policy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eebRsMWJhbUZXLx8" /></figure><p>Step3:</p><pre>- Role name : Role이름</pre><p>설정이 끝나면 IAM 역할을 만듭니다.</p><h4>3. SSM(RDS Stop) 생성</h4><p>이제 SSM을 만듭니다.<em> AWS Systems Manager &gt; State Manager &gt; Create association</em>로 이동하여 RDS정지부터 생성합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H88SorpqkPtZuS-o" /></figure><pre>- Name : RDS Stop용 State Manager이름<br>- Document : AWS-StopRdsInstance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IfOLJsiIYLhqjSY_" /></figure><pre>- Execution : Simple execution<br>- InstanceId : DB instance ID (e.g., arn:aws:rds:us-east-1:123456789012:db:My-SQL-Instance의 My-SQL-Instance가 됨)<br>- AutomationAssumeRole : 조금 전 생성한IAM Role<br>- Specify schedule : On Schedule<br>- Specify with : CRON schedule builder<br>- CRON schedule builder : Daily<br>- When to run the association : CRON시간은 GMT기준이 됨(e.g., 일본 시간은GMT+9시간)<br>- Apply association only at the next specified cron interval : Checked<br><br>체크를 진행 하는 경우, 다음의 Cron설정 시간부터 가동 한다.<br>예 : 현재 시간이 12시, Cron설정을 11시로 하면 다음날 11시부터 Cron이 움직임<br><br>체크를 진행 하지 않는 경우, 그대로 트리거 된다.<br>예 : 현재 시간이 12시, Cron설정을 11시로 하면 12시 이므로 Cron이 움직임</pre><p>위의 설정이 끝나면 생성합니다. 한 가지 주의점은 Instance Id를 입력할 때 Space 없이 해야합니다. SSM이 RDS를 인식하지 못하고 Fail이 되기 때문입니다.</p><h4>4. SSM(RDS Start) 생성</h4><p>SSM의 RDS시작은 정지 설정과 같은 페이지( <em>AWS Systems Manager &gt; State Manager &gt; Create association</em>)에서 아래와 같이 설정합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4AWIRUKo-VCFpsJZ" /></figure><pre>- Name : RDS Stop용 State Manager이름<br>- Document : AWS-StartRdsInstance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ax7-gfmhS-YGVMm0" /></figure><pre>- Execution : Simple execution<br>- InstanceId : DB instance ID (e.g., arn:aws:rds:us-east-1:123456789012:db:My-SQL-Instance의 My-SQL-Instance가 됨)<br>- AutomationAssumeRole : 조금 전 생성한IAM Role<br>- Specify schedule : On Schedule<br>- Specify with : CRON schedule builder<br>- CRON schedule builder : Daily<br>- When to run the association : CRON시간은 GMT기준이 됨(e.g., 일본 시간은GMT+9시간)<br>- Apply association only at the next specified cron interval : No Checked<br><br>체크를 진행 하는 경우, 다음의 Cron설정 시간부터 가동 한다.<br>예 : 현재 시간이 12시, Cron설정을 11시로 하면 다음날 11시부터 Cron이 움직임<br><br>체크를 진행 하지 않는 경우, 그대로 트리거 된다.<br>예 : 현재 시간이 12시, Cron설정을 11시로 하면 12시 이므로 Cron이 움직임</pre><p>위의 설정이 끝나면 생성합니다. 당연한 이야기지만, RDS 정지까지 시간이 걸리기 때문에 시작 시간이 겹치지 않도록 설정하는 것이 좋습니다.</p><h4>5. 동작 결과</h4><p>State Manager의 RDS기동이 시작하면 잠시 후 RDS의 Status가 Stopped temporarily되어 있는지 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tGFOt-B6Vv9a9rGx" /></figure><p>State Manager의 RDS 시작이 움직이면 RDS의 Status가 Available되어 있는지 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kaMJ9orpa9bhmmso" /></figure><h3>마지막으로</h3><p>RDS의 자동 정지 및 시작을 구현하는 방법에는 여러 가지가 있지만, AWS는 다양한 서비스를 제공하며 개인 취향과 요구 사항에 맞게 선택할 수 있는데요, 이를 통해 RDS 비용을 줄이는 것은 어떨까 추천 드립니다.</p><p>이상, AWS Systems Manager를 사용한 Amazon RDS의 자동 정지 및 시작에 대한 블로그 였습니다. 지금까지 읽어 주셔서 감사드립니다!</p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/8a798e52281a89">https://zenn.dev/megazone_japan/articles/8a798e52281a89</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 정재윤님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center 박지은 매니저</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3924da471c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/aws-systems-manager%EB%A5%BC-%ED%86%B5%ED%95%9C-amazon-rds-%EC%9E%90%EB%8F%99-%EC%A0%95%EC%A7%80-%EB%B0%8F-%EC%8B%9C%EC%9E%91-fc3924da471c">AWS Systems Manager를 통한 Amazon RDS 자동 정지 및 시작</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Architecture : AWS EC2 on Brainboard]]></title>
            <link>https://medium.com/cloudvillains/terraform-cloud-architecture-aws-ec2-on-brainboard-fe9a759ce092?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe9a759ce092</guid>
            <category><![CDATA[megazone]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[megazonecloud]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 05:52:51 GMT</pubDate>
            <atom:updated>2023-10-23T04:21:50.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Architecture : AWS EC2 on Brainboard</h3><h3>개요</h3><p>저는 Terraform을 주로 신속하게 환경을 구축 할 수 있도록 Template를 만들고 저장할 때에 이용 합니다. 하지만 템플릿이 많아짐에 따라 관리에 대해 고민하게 되었습니다. 예를 들어 코드를 작성해도 Cloud 구성 검토하는 것을 잊거나 코드를 읽고 이해하는 데에 시간이 낭비되고 있는 것 같았습니다. 그래서 Terraform을 시각화하기 위해 <a href="https://developer.hashicorp.com/terraform/cli/commands/graph">Graph Command</a>를 사용했지만 코드가 증가함에 따라 시각화가 어려운 경우도 있었습니다. (이건 취향에 따른 문제도 있을 것 같긴 합니다) 이러한 경험을 통해 Terraform Visualize등으로 검색하였는데, 그러던 중 <strong>Brainboard</strong> 라는 도구를 우연히 발견했습니다.</p><h3><strong>Brainboard란?</strong></h3><p><a href="https://www.brainboard.co/">Brainboard</a>는 2019년에 출시되었고, 프랑스 기업에서 제공하는 도구입니다. 이 도구는 엔지니어가 Cloud Infra를 시각적으로 설계하고 관리할 수 있는 공동 작업 솔루션으로 그 특징은 다음과 같습니다.</p><ul><li>Brainboard는 한 번의 작업으로 시각적이고 직관적인 솔루션을 제공합니다.</li><li>Multi Cloud를 지원합니다.</li><li>Cloud Architecture를 효율적으로 구축하고 유지할 수 있습니다.</li><li>사내 표준을 수립하고 유지하고 Best Practice 기반 프로세스를 단순화하는 데 도움이 됩니다.</li></ul><p>Diagram만으로 어디까지 관리할 수 있는지 궁금해서 시험삼아 확인 해 보았는데요, 보안 및 요금 플랜을 확인한 결과 문제는 없는 것 같습니다. 보안에 관해서는, SOC2(※)를 취득하고 있고, <a href="https://www.brainboard.co/resources/pricing">요금</a>은 Pro 플랜으로 21일간 무료로 사용할 수 있었습니다.</p><blockquote>※ SOC2를 간단히 설명하면 Cloud Provider 등의 조직이 고객 데이터를 안전하게 관리하고 있는지 여부 등의 보안 체제(내부 통제)를 ‘Trust 서비스 원칙과 표준’이라는 기준에 따라 평가하고 보증 하기 위한 틀이나 평가 내용을 정리한 보증 보고서입니다. SOC2는 일정 기간(반년 이상)에 걸쳐 내부 통제가 적절히 운영되고 있음을 보장합니다.</blockquote><h3><strong>Hands-on</strong></h3><p>다음의 간단한 AWS EC2 구성을 Brainboard를 이용하여 Cloud Architecture 생성, Terraform Code 자동 생성, Terraform Plan/Apply/Destroy까지 진행 해 보도록 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fd7gPGxpksKn6pll" /></figure><p>설명의 흐름은 각 Resource의 절차를 설명드린 후, Brainboard 작업과 관련된 부분을 보충 설명 하도록 하겠습니다. (동일한 내용은 생략합니다.)</p><h4><strong>Top Page</strong></h4><p>먼저 Brainboard에 Login하면 다음과 같은 Top Page로 이동합니다.<br>AWS Template 생성 절차는 다음과 같습니다.</p><blockquote>① Cloud 선택란에서 AWS를 선택합니다.</blockquote><blockquote>② New Architecture를 클릭합니다.</blockquote><blockquote>③ Template, Blank, Import의 Modal이 나타나면, Blank를 선택합니다.</blockquote><blockquote>④ Architecture Name을 입력 하고 이하의 CREATE 버튼을 클릭합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tjI-WAhPAAn-AL9x" /></figure><h3><strong>AWS EC2 구성도 생성</strong></h3><h4>Region</h4><p>Region 생성 순서는 다음과 같습니다.</p><blockquote>① 왼쪽 사이드 메뉴에서 AZ를 선택합니다.<br>② ①의 Resource를 Drag합니다.<br>③ Region: Tokyo로 설정합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*gTV-CYG-1OiFqp8L" /></figure><p>Resource를 Drag하고 오른쪽 사이드 메뉴에 나타나는 항목은 Terraform 각 Resource의 Options가 됩니다. 또한 해당 항목에 입력하면 자동 저장됩니다.</p><h4>VPC</h4><p>VPC 생성 절차는 다음과 같습니다.</p><blockquote>① 왼쪽 사이드 메뉴에서 VPC를 선택하고 Template에 Drag합니다.<br>② Resource name : main (eg Terraform code resource name)<br>③ Advanced configuration &gt; Cidr Block : var.vpc_cidr (이 변수명은 Variables &amp; localls에 자동 생성됩니다.)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*KK-6ClvBCkXp1Z_W" /></figure><p>VPC의 변수 생성 절차는 다음과 같습니다.</p><blockquote>① 왼쪽 사이드 메뉴에서 Variables를 선택하면 Variables &amp; localals Modal이 나타납니다.<br>② vpc_cidr을 선택합니다.<br>③ type : String<br>④ default : “10.0.0.0/16”<br>⑤ UPDATE 버튼을 클릭합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*xOb4qAsC45BOL5o1" /></figure><p>VPC와 변수까지 설정할 수 있으며, Template로 돌아가서 오른쪽의 작은 화살표를 클릭하면 Terraform Code를 확인 할 수 있습니다.<br>참고로 Tags는 이전의 Variables &amp; locals Modal에서 자동으로 생성되며 수정이 가능하지만 Terraform Code는 Read Only입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*LXtNVmAnLc9raLz1" /></figure><p>이와 같이 대상의 Resource를 Template에 Drag하고 Options와 변수를 설정하면 Terraform Code가 자동 생성되는 구조를 이해할 수 있을 것입니다.</p><h4>Internet Gateway</h4><p>IGW 작성 절차는 다음과 같습니다.</p><p>① IGW를 Template로 Drag합니다.<br>② Resource name : main<br>③ Advanced configuration &gt; Vpc id : aws_vpc.main.id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*JKlhHpePLgjfeZ4U" /></figure><p>그러면 VPC와 마찬가지로 Terraform Code도 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*9l7CabjIA-GdibBG" /></figure><h4><strong>Availability Zone</strong></h4><p>AZ를 만드는 절차는 다음과 같습니다.</p><blockquote>① AZ를 Template로 Drag합니다.<br>② Advanced configuration &gt; Availability Zone : ap-northeast-1a (Region내에 Drag하면 Region은 마음대로 설정됩니다.)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*Y5j8wBazyACDV3_b" /></figure><p><strong>Subnet</strong></p><p>Subnet을 만드는 절차는 다음과 같습니다.</p><blockquote>① Subnet을 Template로 Drag합니다.<br>② Resource name : main<br>③ Vpc id : aws_vpc.main.id<br>④ Advanced configuration &gt; Availability Zone : ap-northeast-1a<br>⑤ Advanced configuration &gt; Cidr Block : var.sb_cidr</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*Gjrzle0k7HThahXw" /></figure><p>Subnet의 변수 작성 순서는 다음과 같습니다.</p><blockquote>① sb_cidr 선택합니다.<br>② type : String<br>③ default : “10.0.10.0/24”<br>④ UPDATE 버튼을 클릭합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*-rJBPA7sK13Eb-eH" /></figure><p>Subnet Terraform Code가 생성되었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*kK5KkdKButw1N5rO" /></figure><p><strong>Route Table</strong></p><p>Route Table을 만드는 절차는 다음과 같습니다.</p><blockquote>① Route Table을 Template로 Drag합니다.<br>② Resource name : main<br>③ Vpc id : aws_vpc.main.id<br>④ Advanced configuration &gt; Cidr Block : var.rt_cidr<br>⑤ Advanced configuration &gt; Gateway id : aws_internet_gateway.main.id</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*uW1im8pLEkrtdSK_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*nNUvq_dwnld0HrdX" /></figure><p>Route Table의 변수 작성 순서는 다음과 같습니다.</p><blockquote>① rt_cidr 선택합니다.<br>② type : String<br>③ default : “10.0.10.0/24”<br>④ UPDATE 버튼을 클릭합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*8nCVb0uDKRaUEnZX" /></figure><p>Route Table Association을 만드는 절차는 다음과 같습니다.</p><blockquote>① Route Table Association을 Template로 Drag합니다.</blockquote><blockquote>② Resource name : main<br>③ Route Table id : aws_route_table.main.id<br>④ Advanced configuration &gt; Subnet id : aws_subnet.main.id</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*7L-vhB0GKMMM15ax" /></figure><p>Route Table Association까지 설정했으므로 Terraform Code를 확인합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*vY0xC373fgTMOOSZ" /></figure><h4>Security Group</h4><p>Security Group을 생성하는 절차는 다음과 같습니다.</p><blockquote>① Security Group을 Template로 Drag합니다.<br>② Resource name : main<br>③ Advanced configuration &gt; Vpc id : aws_vpc.main.id</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*A_fuDvGbW0BRG0AD" /></figure><p>계속하여 Options에서 다음과 같이 Egress와 Ingress를 설정합니다.</p><blockquote>④ Advanced configuration &gt; Egress &gt; Cidr Blocks : “0.0.0.0/0”<br>⑤ Advanced configuration &gt; Egress &gt; From Port : 0<br>⑥ Advanced configuration &gt; Egress &gt; Protocol : “-1”<br>⑦ Advanced configuration &gt; Egress &gt; To Port : 0<br>⑧ configuration &gt; Ingress &gt; Cidr Blocks : “0.0.0.0/0”<br>⑨ Advanced configuration &gt; Ingress &gt; From Port : 80<br>⑩ Advanced configuration &gt; Ingress &gt; Protocol : “tcp”<br>⑪ Advanced configuration &gt; Ingress &gt; To Port : 80<br>⑫ Advanced &gt; Cidr Blocks : “0.0.0.0/0”<br>⑬ Advanced configuration &gt; Ingress &gt; From Port : 22<br>⑭ Advanced configuration &gt; Ingress &gt; Protocol : “tcp”<br>⑮ Advanced configuration &gt; Ingress &gt; To Port : 22</blockquote><p>Security Group의 Terraform Code를 검토합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*K5hTpaskzncIREkQ" /></figure><p>추가로, Drag하여 Template를 조정하는 것도 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nf8Ag4mtGjumoNki" /></figure><h4><strong>Key Pair</strong></h4><p>Key Pair의 생성 순서는 다음과 같습니다.</p><blockquote>① Key Pair를 Template로 Drag합니다.<br>② Resource name : main<br>③ Public Key : var.pub_key (Local에서 SSH Key 생성 해 둡니다.)<br>④ Advanced configuration &gt; Key Name : var.key_name</blockquote><p>③, ④는 위에서 했듯이 Variables&amp;locals에서 각 Type과 Default를 입력해 주세요.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*r0uoIxb9IiwJLSEX" /></figure><h4><strong>EC2</strong></h4><p>EC2 생성 절차는 다음과 같습니다.</p><blockquote>① EC2(t2)를 Template로 Drag합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*Vojkncmqyz_Guj14" /></figure><p>계속해서 Options에서 다음과 같이 설정합니다.</p><blockquote>② Resource name : main<br>③ Advanced configuration &gt; Ami : var.ami (eg “ami-04a735b489d2a0320”)<br>④ Advanced configuration &gt; Associate Public Ip Address : TRUE<br>⑤ Advanced configuration &gt; Key Name : var.key_ce<br>⑥ Advanced configuration &gt; Instance Type : t2.micro<br>⑦ Advanced configuration &gt; Security Groups : aws_security_group.main.id<br>⑧ Advanced configuration &gt; Subnet id : aws_subnet.main.id<br>⑨ Extra Attributes &gt; Depends On : aws_key_pair.main.id</blockquote><p>EC2 Terraform Code도 확인해 봅시다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*-ovhwqKRXPyj2vE2" /></figure><p><strong>EIP</strong></p><p>EIP 생성 절차는 다음과 같습니다.</p><blockquote>① DIP를 Template로 드래그합니다.<br>② Resource name : main<br>③ Advanced configuration &gt; instance : aws_instance.main.id</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*SrT5GbCRZ71OmgLR" /></figure><p><strong>Terraform Code</strong></p><p>여기까지 Brainboard를 사용하여 생성한 AWS EC2의 구성도입니다. 이 구성도를 생성함으로 인하여 Terraform Code 생성이 매우 간단해졌습니다. 또한 Terraform 초보자도 사용하기 쉬운 도구라고 생각됩니다.</p><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  tags       = merge(var.tags, {})<br>  cidr_block = var.vpc_cidr<br>}<br><br>resource &quot;aws_internet_gateway&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, {})<br>}<br><br>resource &quot;aws_subnet&quot; &quot;main&quot; {<br>  vpc_id            = aws_vpc.main.id<br>  tags              = merge(var.tags, {})<br>  cidr_block        = var.sb_cidr<br>  availability_zone = &quot;ap-northeast-1a&quot;<br>}<br><br>resource &quot;aws_route_table&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, {})<br><br>  route {<br>    gateway_id = aws_internet_gateway.main.id<br>    cidr_block = var.rt_cidr<br>  }<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;main&quot; {<br>  subnet_id      = aws_subnet.main.id<br>  route_table_id = aws_route_table.main.id<br>}<br><br>resource &quot;aws_security_group&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags   = merge(var.tags, {})<br><br>  egress {<br>    to_port   = 0<br>    protocol  = &quot;-1&quot;<br>    from_port = 0<br>    cidr_blocks = [<br>      &quot;0.0.0.0/0&quot;,<br>    ]<br>  }<br><br>  ingress {<br>    to_port   = 80<br>    protocol  = &quot;tcp&quot;<br>    from_port = 80<br>    cidr_blocks = [<br>      &quot;0.0.0.0/0&quot;,<br>    ]<br>  }<br>  ingress {<br>    to_port   = 22<br>    protocol  = &quot;tcp&quot;<br>    from_port = 22<br>    cidr_blocks = [<br>      &quot;0.0.0.0/0&quot;,<br>    ]<br>  }<br>}<br><br>resource &quot;aws_key_pair&quot; &quot;main&quot; {<br>  tags       = merge(var.tags, {})<br>  public_key = var.pub_key<br>  key_name   = var.key_name<br>}<br><br>resource &quot;aws_instance&quot; &quot;main&quot; {<br>  tags                        = merge(var.tags, {})<br>  subnet_id                   = aws_subnet.main.id<br>  key_name                    = var.key_name<br>  instance_type               = &quot;t2.micro&quot;<br>  availability_zone           = &quot;ap-northeast-1a&quot;<br>  associate_public_ip_address = true<br>  ami                         = var.ami<br><br>  depends_on = [<br>    aws_key_pair.main,<br>  ]<br><br>  security_groups = [<br>    aws_security_group.main.id,<br>  ]<br>}<br><br>resource &quot;aws_eip&quot; &quot;main&quot; {<br>  vpc      = true<br>  tags     = merge(var.tags, {})<br>  instance = aws_instance.main.id<br>}</pre><p><strong>AWS EC2 Deploy</strong></p><p>Terraform Code가 완성되었기때문에 Terraform deploy까지 해보겠습니다.<br>그 전에 Cloud Provider를 설정해야 합니다.</p><p><strong>Cloud Provider 설정</strong></p><p>Cloud Provider 설정 페이지로 이동하는 방법은 다음과 같습니다.</p><blockquote>① 오른쪽 상단의 계정을 클릭합니다.<br>② Cloud Providers를 클릭합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*2-L2129tQorGYP1m" /></figure><p>AWS Credentials 설정 절차는 다음과 같습니다.</p><blockquote>① AWS를 선택하고 + 버튼을 클릭합니다.<br>② Modal에 있는 NAME, AWS ACCESS KEY ID, AWS SECRET ACCESS KEY를 입력하고 SUBMIT을 클릭합니다.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*zbwe4bG6uhfghn3B" /></figure><p>이제 Cloud Provider 설정을 완료했으므로 Terraform Command를 실행 해 보겠습니다.</p><h4><strong>Terraform Plan</strong></h4><p>Template의 Terraform이 표시되는 부분에 있는 Plan 버튼을 클릭합니다. 그러면 Local에서 Command를 실행하는 것처럼 Plan 결과가 표시됩니다.<br>참고로 무료 플랜의 경우, tfstate의 관리는 Brainboard의 백엔드에서 이루어집니다. S3 등으로 관리하려는 경우 플랜을 변경해야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*JltkhBn9Do6NkzKJ" /></figure><h4>Terraform Apply</h4><p>Terraform Plan이 문제없이 움직이기 때문에 Terraform Apply하여 AWS에 Deploy해 보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2MRhY7EGdgbqRlzV" /></figure><p>Deploy가 완료되었습니다. AWS 콘솔에 들어가서 EC2를 확인하면 제대로 배포할 수 있는지 확인 할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NQBO6ugYUg9cCQJS" /></figure><p>SSH 연결도 확인 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40-FzjJmSEHTzHn1" /></figure><p>Brainboard에서 생성된 Terraform Code로 Deploy 할 수 있는 곳까지 확인하였으므로, 다음으로는 Destroy를 해 보겠습니다.</p><h4><strong>Terraform Destroy</strong></h4><p>Destroy 버튼을 클릭하여 AWS Resource를 삭제합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*_R3VIz8XN-sWZZjl" /></figure><p>EC2가 Terminated로 되어있는지도 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hPgpXXLFhEHnUFQ3" /></figure><h3><strong>그 외기능</strong></h3><p>이번에는 간단한 Cloud Architecture를 만들어 Deploy를 수행했지만, 그 외에도 다양한 기능이 있었습니다. 무료 플랜이어서 세세한 부분까지는 확인할 수 없었지만, 간단하게 설명하면 이하의 기능이 가능 한 것 같습니다.</p><ul><li>프로젝트 관리</li></ul><p>Multi Cloud Architecture의 버전 관리</p><p>멤버 관리(RBAC)</p><ul><li>Pull Request</li></ul><p>Azure Devops, Bitbucket, Gitlab에 Pull Request 가능</p><ul><li>CI/CD Design</li></ul><p>YAML 지식이 없어도 파이프 라인을 시각화 할 수 있습니다.</p><ul><li>Terraform</li></ul><p>*.tf files 자동 생성</p><p>Module, Cloud Architecture의 버전 관리</p><p>Import 가능</p><p>Import는 한번 해 보고 싶어져서, 방금 생성된 Terraform Code를 이용 하여 Import해 보았습니다.</p><p>아래 그림의 위는 Hands-on에서 만든 Architecture이고, 아래쪽은 Import한 것입니다. Terraform에 있는 Resource는 어느 정도 생성 된 것 같지만, 역시 세세한 연결 부분까지는 이해하기 어렵다고 느꼈습니다. Import 할 때는 조정이 필요하다 생각되네요.</p><p>Template생성한 것</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*LDPOZLH_LTQbbNkv" /></figure><p>Import한 것</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*zG5R2yZu4Ig4ghGf" /></figure><h3>마지막으로</h3><p>IT 업계에서는 Front-End, Back-End, Cloud Infra 등 다양한 팀과 협력하면서 커뮤니케이션 오해와 같은 문제로 진행이 멈추는 경우도 있습니다. 예를 들어, API에 관한 최신 문서가 필요한 경우, 다수의 Microservice 문서를 어떻게 관리하고 제공하는지 등이 있을 수 있습니다. 텍스트 파일을 만들 때 YAML보다 Markdown이 더 오래 걸린다거나, IaC를 만드는 것보다 Architecture를 만드는 것이 더 오래 걸릴 수 있습니다. 문서가 최신버전이 아니라면, 전체의 효율이 저하되는 일도 있고, 복잡한 Architecture 문서화는 영원한 도전 과제 중 하나일 수 있습니다.</p><p>Brainboard 도구는 Diagram as Code를 구현합니다. 종이에 Architecture를 그린 것과 같은 시각화, 관리 및 Terraform Code를 자동 생성할 수 있습니다. 이를 통해 정보를 최신 상태로 팀 구성원에게 제공하고 Architecture에 집중할 수 있습니다. 하지만 IaC의 출력은 Terraform만 지원하므로 예를 들어 Azure 사용자가 Bicep를 원하는 경우 도구를 사용할 수 없다는 단점도 있습니다.</p><p>개인적으로는 매우 흥미로운 툴이라고 생각하고, 업무에 활용할 수 있는 경우가 생긴다면 이 툴을 사용해 보고자 합니다.</p><p>지금까지 Brainboard에 관한 게시글 이었습니다. 읽어주셔서 감사드립니다.</p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/311faef395881d">https://zenn.dev/megazone_japan/articles/311faef395881d</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 정재윤님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center 박지은 매니저</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe9a759ce092" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/terraform-cloud-architecture-aws-ec2-on-brainboard-fe9a759ce092">Terraform Cloud Architecture : AWS EC2 on Brainboard</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS S3트리거를 사용하여 동영상 번역 및 자막 삽입 하기]]></title>
            <link>https://medium.com/cloudvillains/aws-s3%ED%8A%B8%EB%A6%AC%EA%B1%B0%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%EB%8F%99%EC%98%81%EC%83%81-%EB%B2%88%EC%97%AD-%EB%B0%8F-%EC%9E%90%EB%A7%89-%EC%82%BD%EC%9E%85-%ED%95%98%EA%B8%B0-cad7121e0545?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cad7121e0545</guid>
            <category><![CDATA[megazone]]></category>
            <category><![CDATA[megazonecloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 11:40:21 GMT</pubDate>
            <atom:updated>2023-10-17T11:47:15.443Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>개요</strong></h3><p>이번에 AWS S3 트리거를 사용하여 동영상 번역을 진행 해 보았습니다.</p><p>지난 번 사내에서 본사(한국)로부터 회사 관련 동영상이 공유 되었지만, 그 내용이 한국어로 되어 있어 자막이 필요하다는 팀원이 있었습니다.<br>저는 이미 AWS에서 영상이나 언어 관련 서비스를 제공하고 있는 것을 알고 있어서 부담없이 자막 관련 작업을 진행 해 보았고, 그 내용을 본 게시글로 작성 하게 되었습니다.</p><h3><strong>Infrastructure</strong></h3><p>이번에 생성할 Infrastructure는 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pl9a0LbRTkrEv6z1" /></figure><p>User가 동영상을 S3에 업로드하면 Lambda가 움직이게 됩니다.<br>Lambda는 동영상을 Amazon Transcribe로 SRT를 추출하고 File을 Amazon Translate로 번역합니다. 마지막으로 번역된 SRT를 동영상에 넣어 S3에 업로드하는 메커니즘입니다.</p><p>목표로 하는 Output은 아래의 왼쪽 Before를 오른쪽 After처럼 만드는 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*1yCJ9wtY2tjV0S-VYuN05w.png" /></figure><p>본 블로그는</p><ol><li>구축 절차</li><li>좋았던 포인트</li><li>감상</li></ol><p>순서로 써 보겠습니다.</p><h3><strong>1. 구축 절차</strong></h3><p>이번 구축은 기본 Console상에서 실시했습니다. 다음 순서로 설명드리겠습니다.</p><pre>1) Lambda생성<br>2) S3생성<br>3) Lambda functions생성<br>4) 동작 확인</pre><h4>1) Lambda 생성</h4><p>Lambda에서 생성 합니다.<br>값은 아래와 같이 Name과 Python의 선택 정도만 진행 하면 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p2qLh4iiYhQIAzVD" /></figure><p>만든 Lambda 페이지는 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zvdasjN7tMxBRMMH" /></figure><p>function은 S3 트리거 설정 후에 설명 드리겠습니다.</p><h4>2) S3 생성</h4><p>S3 Bucket을 만듭니다. 이름을 입력하고 다른 Options는 Default로 두겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tOncXj1N_o-rV-Ou" /></figure><p>S3 Bucket이 완료되면 Create folder에서 video, srt, substitle을 만듭니다.<br>각 역할은 다음과 같습니다.</p><pre>YourBucket/video/ : 동영상을 업로드 할 트리거 용<br>YourBucket/srt/ : srt file보관용<br>YourBucket/substitle/ : 동영상 자막 버전 보관용</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*um-ERq7NyMQ-lW2R" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WVkTnETYyZYFZyBH" /></figure><p>그럼 트리거 folder를 설정 해 보겠습니다.<br>Bucket의 Properties에 태그를 바꿉니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTtsECME8y4E7bEH" /></figure><p>아래로 스크롤하면 Event notifications(트리거)가 있으므로 Event를 생성합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBqU9IH1vT-lfwcz" /></figure><p>Event는 다음과 같이 설정합니다.<br>Video folder에 Upload(PUT)하면, ‘1) Lambda생성’에서 생성한 Lambda function을 호출 할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*um14rcmaPIbZR10c" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LeUmJ6-HTqNEE0XG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Pbk8qp-bqasubvG" /></figure><p>위의 설정으로 만들면 다음과 같이 보입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8yyAI8y5caqXNPp" /></figure><p>그리고 Lambda의 내용을 보면 트리거로 나타납니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eMOHdeSEEtjAsZ7f" /></figure><h4><strong>3) Lambda functions 생성</strong></h4><p>여기까지 진행하여 S3트리거를 사용하여 Lambda를 호출하게 되었으므로, Lambda에 S3 권한을 부여하는 부분부터 설명 드리겠습니다.</p><p>IAM의 Roles로 이동하면, ‘1) Lambda생성’으로 생성했을 때에 만들어진 Role이 있을겁니다. 해당 역할 이름을 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZdrfgROw8UYaWGx" /></figure><p>Add permissions 드롭다운에서 Attach policies를 클릭합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dGrlIsocQ6vDCYTp" /></figure><p>S3에서 검색하면 여러 가지가 표시되지만 S3FullAccess를 선택하고, Add permissions를 클릭하여 Attach를 수행합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OF0Tkn4cf9e_pFZb" /></figure><p>이제 S3의 권한을 부여할 수 있게 되었습니다.</p><p>Lambda functions는 다음과 같이 만들었습니다.</p><p>간단하게 설명 드리자면, Amazon Transcribe에서 S3(video/)에 업로드 한 .mp4 언어를 식별하고 srt 파일을 S3(srt/)에 생성합니다.<br>해당 srt 파일을 Amazon Translate에서 번역 버전으로 만듭니다.<br>번역판의 srt file을 S3(video/)에 있는 .mp4에 넣고 S3(substitle/)에 Upload합니다.</p><pre>import json<br>import re<br>import boto3<br>import random<br>import string<br>import subprocess<br><br>s3_client = boto3.client(&#39;s3&#39;)<br>transcribe_client = boto3.client(&#39;transcribe&#39;)<br>translate_client = boto3.client(&#39;translate&#39;)<br><br>TRANSCRIBE_LANG_CODE = {<br>    &#39;en&#39; : &#39;en-US&#39; ,<br>    &#39;ja&#39; : &#39;ja-JP&#39; ,<br>    &#39;ko&#39; : &#39;ko-KR&#39; ,<br>    &#39;zh&#39; : &#39;zh-CN&#39;<br>}<br>FFMPEG_LANG_CODE = {<br>    &#39;en&#39; : &#39;eng&#39; ,<br>    &#39;ja&#39; : &#39;jpn&#39; ,<br>    &#39;ko&#39; : &#39;kor&#39; ,<br>    &#39;zh&#39; : &#39;zho&#39;<br>}<br>SOURCE_LANG = &#39;en&#39;<br>TARGET_LANG = &#39;ja&#39;<br><br>LOCAL_SRT_PATH = &#39;/tmp/jp_sub.srt&#39;<br>LOCAL_VIDEO_PATH = &#39;/tmp/video.mp4&#39;<br>LOCAL_SUBTITLE_VIDEO_PATH = &#39;/tmp/subtitle_video.mp4&#39;<br><br>SRT_KEY_FOLDER = &#39;srt/&#39;<br>SUBSTITLE_KEY_FOLDER = &#39;substitle/&#39;<br><br># TranscriptionJobName to avoid duplication<br>def generate_random_string(length):<br>    letters = string.ascii_letters<br>    return &#39;&#39;.join(random.choice(letters) for _ in range(length))<br><br># Create Transcribe and Save to S3<br>def create_transcription_job_save_s3(bucket, key):<br>    random_string = generate_random_string(3) # make a TranscriptionJobName<br>    transcribe_job_name = key.split(&#39;/&#39;)[1].split(&#39;.&#39;)[0] + random_string<br>    transcribe_response = transcribe_client.start_transcription_job(<br>        TranscriptionJobName=transcribe_job_name,<br>        Subtitles={&#39;Formats&#39;: [&#39;srt&#39;]},<br>        Media={&#39;MediaFileUri&#39;: f&#39;s3://{bucket}/{key}&#39;},<br>        LanguageCode=TRANSCRIBE_LANG_CODE[SOURCE_LANG],<br>        OutputBucketName = bucket,<br>        OutputKey = SRT_KEY_FOLDER #save to srt folder<br>    )<br>    return transcribe_job_name<br><br># Get S3 and Translate Target Languege<br>def get_s3_translate_text(bucket, key_srt):<br>    srt_body = s3_client.get_object(Bucket=bucket,Key=key_srt)[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>    translate_response = translate_client.translate_text(<br>        Text= srt_body,<br>        SourceLanguageCode=SOURCE_LANG,<br>        TargetLanguageCode=TARGET_LANG<br>    )<br>    return translate_response[&#39;TranslatedText&#39;]<br><br># When translated by AWS translate, the timeline format changes, so it is transformed to fit the srt format.<br>def format_subtitles(translated_text):<br>    pattern = r&quot;(\d{2}:\d{2}:\d{2},\d{3})--&gt; (\d{2}:\d{2}:\d{2},\d{3})&quot;<br>    replacement = r&quot;\1 --&gt; \2&quot;<br>    return re.sub(pattern, replacement, translated_text)<br><br>def lambda_handler(event, context):<br>    <br>    #Get our bucket and file name<br>    bucket = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>    key = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br><br>    transcribe_job_name = create_transcription_job_save_s3(bucket, key)<br>    <br>    # looping until the work is finished<br>    while True:<br>        status = transcribe_client.get_transcription_job(TranscriptionJobName=transcribe_job_name)[&#39;TranscriptionJob&#39;][&#39;TranscriptionJobStatus&#39;]<br>        if status in [&#39;COMPLETED&#39;, &#39;FAILED&#39;]:<br>            break<br>    <br>    key_srt = SRT_KEY_FOLDER + transcribe_job_name + &#39;.srt&#39;<br>    translated_text = get_s3_translate_text(bucket, key_srt)<br>    formatted_subtitle = format_subtitles(translated_text)<br>    <br>    <br>    # srt save to local<br>    with open(LOCAL_SRT_PATH, &quot;a&quot;) as f:<br>        f.write(formatted_subtitle)<br><br>    s3_client.download_file(bucket, key, LOCAL_VIDEO_PATH)<br>    <br>    # Add subtitles to videos using FFmpeg<br>    command = [<br>        &quot;/opt/bin/ffmpeg&quot;,<br>        &quot;-y&quot;,<br>        &quot;-i&quot;, LOCAL_VIDEO_PATH,<br>        &quot;-i&quot;, LOCAL_SRT_PATH,<br>        &quot;-c&quot;, &quot;copy&quot;,<br>        &quot;-c:s&quot;, &quot;mov_text&quot;,<br>        &quot;-metadata:s:s:0&quot;, &quot;language=&quot;+ FFMPEG_LANG_CODE[TARGET_LANG], <br>        LOCAL_SUBTITLE_VIDEO_PATH<br>    ]<br>    subprocess.run(command, check=True)<br>    <br>    # Upload Subtitle Video<br>    output_key_name = SUBSTITLE_KEY_FOLDER + key.split(&#39;/&#39;)[1].split(&#39;.&#39;)[0] + f&#39;-subtitle.mp4&#39; # S3 uplpad key name e.g. substitle/sample-subtitle.mp4<br>    s3_client.upload_file(LOCAL_SUBTITLE_VIDEO_PATH, bucket, output_key_name)<br>    <br>    # Delete Transcription job<br>    response = transcribe_client.delete_transcription_job(TranscriptionJobName=transcribe_job_name)<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;Saved video subtitles!&#39;)<br>    }</pre><p>Code를 생성 및 수정할 때마다 Deploy 해 둡니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQgAA5JwFhjetsfN" /></figure><p>다음은 ffmpeg를 Layers에 등록합니다.<br>먼저 자신의 환경에서 다음 Command를 실행합니다. ffmpeg가 포함된 Zip을 만듭니다.</p><pre>$ wget https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz<br>$ tar xvf ffmpeg-release-amd64-static.tar.xz<br>$ mkdir -p ffmpeg/bin<br>$ cp ffmpeg-6.0-amd64-static/ffmpeg ffmpeg/bin/<br>$ cd ffmpeg<br>$ zip -r ../ffmpeg.zip .</pre><p>이 Zip을 ‘2) S3생성’으로 생성한 Bucket에 Upload 해 둡니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GRfbIURbGwgNmhhc" /></figure><p>Lambda의 Layers로 이동하여 Layer를 만듭니다.<br>방금 전에 ffmpeg Zip을 업로드 한 Object URL을 붙여 넣습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T0QJ7aj616Eq_9Df" /></figure><p>Layer 생성이 끝나면 세부 정보 페이지에 ARN이 표시됩니다. (아래 빨간색 상자) 이를 복사 해 주세요. (image에 있는 Version은 신경 쓰지 말아 주세요. 처음으로 작성되면 1로 되어 있을 것 입니다.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vCxrFbBvT28cJYp_" /></figure><p>Lambda function으로 돌아가서 생성한 Layer를 등록해 둡니다.<br>Add Layer에서 Specify an ARN을 선택하고 Copy한 ARN을 붙여넣고 Verify까지 진행합니다.<br>그 후 Add를 클릭하여 Lambda function에 Layer를 등록합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xwuoSdrgIxmBjElT" /></figure><p>Lambda function의 OverView에는 S3 트리거와 Layer(1)가 표시됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EFAja-5AvFWPWBfm" /></figure><p>마지막으로 functions의 timeout을 설정합니다.<br>1분으로 설정 해 두었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7rxb2osAZ7hbeDAV" /></figure><h4><strong>4) 동작 확인</strong></h4><p>S3 Video에 샘플 동영상을 업로드합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NM8SYQ6ZKvcxERfw" /></figure><p>이 트리거를 사용하면 동일한 타이밍에 CloudWatch Logs가 생성되는지 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YsKALDNY6oft7Dng" /></figure><p>Logs의 내용을 확인하여 끝까지 실행 된 것이 확인되면 S3의 srt/와 substitle/를 확인합니다.<br>시간을 보게되면 실행 완료까지 1분 정도 걸리는 것을 알 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uGnrsUHB2Nsyyt4B" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qLDN2bXysEq5SZUQ" /></figure><p>동영상에 자막이 있는 파일을 확인한 후 sample-substitle.mp4를 다운로드하여 확인 해 보았습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*mQ7K50Qg2pOL1ZHx" /></figure><p>시험 삼아 한국어로도 해 보았습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*L9mswfCNj1a_W-g-" /></figure><p>추가로 Code의 Debug나 동작 확인을 위해, Configure test event를 설정해 두었습니다.<br>템플릿은 S3Put을 선택하고 bucket &gt; name에는 Bucket 이름을 object &gt; key 에는 Video / {~.mp4}로 설정했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iUp_k1uxf-ZpmQdf" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*wWPQG8cfEvJ1pGid" /></figure><h3><strong>좋았던 포인트</strong></h3><p><strong>ffmpeg layer에 대해</strong></p><blockquote>Lambda에서 라이브러리를 사용할 때 import 이외의 방법은 별로 경험이 없었습니다. 보통 ffmpeg를 import하여 진행했는데, not found 에러에 빠져 버렸습니다. 그렇지만 나중에 패키징과 레이어를 사용하여 문제를 해결했습니다.<br>구체적으로 설명 드리면 ffmpeg를 포함한 사용자 정의 Layer를 만들고 Lambda 함수에서 해당 Layer를 사용하여 필요한 라이브러리와 실행 파일을 제공했습니다. 이렇게 하면 라이브러리를 찾을 수 없다는 오류를 피하면서 순조롭게 ffmpeg를 사용하여 작동 시킬 수 있었습니다.<br>이 경험을 통해 Lambda에서 외부 라이브러리를 사용할 때 패키징과 Layer의 활용이 중요하다는 것을 배웠습니다.</blockquote><p><strong>AWS translate 및 srt에 대해</strong></p><blockquote>AWS translate로 srt 파일을 번역하면 srt format이 무너지는 것을 알았습니다.</blockquote><blockquote>예를 들어, 맞는 것 : 00:01:23,150 → 00:01:27,880<br>틀린 것 : 00:01:23,150 → 00:01:27,880<br>상기의 틀린 것에서 나타낸 것처럼 화살표 모양이 변경되어 ffmpeg로 동영상에 자막을 넣을 때 invalid data 오류가 발생했습니다.<br>따라서 화살표 형식을 올바르게 수정하는 format_subtitles() 함수를 만들어 해결했습니다.<br>또한 AWS translate를 이용한 번역이어서, 필요에 따라 의역이 필요하다고 생각했습니다.</blockquote><h3><strong>감상</strong></h3><p>오랜만에 AWS를 사용하여 즐거운 시간을 보냈습니다. 실제로 해 보면서 향후 어떻게 활용할 수 있을 지에 대해 공부 가능한 점이나 얻을 수 있는 것이 많았습니다.</p><p>이번에는 Lambda를 사용하여 동영상 파일을 기록하고 번역을 하여 자막을 붙여 보았지만, 한편으로는 Lambda 함수의 스케일링에 관한 부분이 부족했다고 느꼈습니다.</p><p>특히, TransscribeService의 start_transcription_job이라는 동영상 기록과 관련된 처리는 기록(이 경우에서는 SRT 형식의 생성)에 시간이 걸리는 사양이었습니다. Lambda내에서 실행하기 위해 작업의 완료 상태를 get_transcription_job을 사용하여 검색하고 완료 할 때까지 while 루프에서 대기했습니다. 이 방법으로 문제는 없었지만, 이러한 실시간 실행이 적절한지 여부를 계속 고민했습니다.<br>덧붙여서, 실시간으로 실행 가능한 start_stream_transcription 이라는 이벤트도 존재했지만, 이번과 같은 자막 대응에는 적용할 수 없었습니다.</p><p>Lambda 함수의 스케일링에 관한 것도 아직 많이 있어, 앞으로 실제로 경험하면서 깊이 이해 해 나가고 싶다고 생각 했습니다.</p><h4>Reference</h4><p><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/transcribe.html">AWS boto3 docs TranscribeService</a></p><p><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/translate.html">AWS boto3 docs Translate</a></p><p><a href="https://www.pexels.com/search/videos/public%20speaking/">샘플 비디오 파일</a></p><p><a href="https://ffmpeg.org/ffmpeg.html">ffmpeg docs</a></p><p><a href="https://aws.amazon.com/ko/blogs/media/processing-user-generated-content-using-aws-lambda-and-ffmpeg/">Lambda Layer</a></p><p><a href="https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/with-s3-example.html">Amazon S3 trigger to invoke a Lambda function</a></p><p><a href="https://dev.classmethod.jp/articles/lambda-layer-basics-how-it-works/">Lambda Layer의 기본 메커니즘 확인 #reinvent</a></p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/f5aed2c5fb8767">https://zenn.dev/megazone_japan/articles/f5aed2c5fb8767</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 정재윤님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center 박지은 매니저</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad7121e0545" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/aws-s3%ED%8A%B8%EB%A6%AC%EA%B1%B0%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%EB%8F%99%EC%98%81%EC%83%81-%EB%B2%88%EC%97%AD-%EB%B0%8F-%EC%9E%90%EB%A7%89-%EC%82%BD%EC%9E%85-%ED%95%98%EA%B8%B0-cad7121e0545">AWS S3트리거를 사용하여 동영상 번역 및 자막 삽입 하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bastion서버가 필요 없다? EC2 Instance Connect Endpoint 추천 포인트(1)]]></title>
            <link>https://medium.com/cloudvillains/bastion%EC%84%9C%EB%B2%84%EA%B0%80-%ED%95%84%EC%9A%94-%EC%97%86%EB%8B%A4-ec2-instance-connext-endpoint-%EC%B6%94%EC%B2%9C-%ED%8F%AC%EC%9D%B8%ED%8A%B8-1-910fb5ec9833?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/910fb5ec9833</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[megazonecloud]]></category>
            <category><![CDATA[bastion]]></category>
            <category><![CDATA[megazone]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 02:27:21 GMT</pubDate>
            <atom:updated>2023-09-20T06:07:07.362Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS를 사용할 때 인터넷에서 격리된 환경의 EC2 인스턴스(서버)에 로그인하는 방법은 여러 가지가 있지만, 그 중에서도 EC2 Instance Connect Endpoint는 쉽고 비용을 절감할 수 있는 수단입니다.</p><p>본 게시글에서는 EC2 Instance Connect Endpoint를 사용하여 폐쇄 환경의 EC2 인스턴스에 연결하는 순서에 대해 소개하겠습니다.</p><h3>목차</h3><ol><li>폐쇄 환경에 접속하는 방법</li><li>EC2 Instance Connect Endpoint의 이점</li><li>본 게시글의 구성</li><li>주의점</li><li>EC2 Instance Connect Endpoint 보안 그룹 만들기</li><li>대상 EC2 인스턴스의 보안 그룹 수정</li><li>EC2 Instance Connect Endpoint 만들기</li><li>EC2 인스턴스에 로그인 확인</li><li>마지막으로</li><li>참고 URL</li></ol><h3>폐쇄 환경에 접속하는 방법</h3><p>먼저 AWS로 인터넷에서 프라이빗 서브넷(폐쇄 환경) EC2 인스턴스에 연결하는 방법 세 가지를 알아보겠습니다.</p><h4>[1] Bastion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*PE_Q7C2H68R4KGcm" /></figure><p>먼저 첫 번째 방법은 공개 네트워크인 퍼블릭 서브넷에 SSH 접속이 가능한 EC2 인스턴스를 준비하고, 그 EC2 인스턴스를 발판으로 프라이빗 서브넷에 포트 포워딩하는 방법입니다. 굉장히 오래된 방식으로 AWS 환경에 관계없이 사무실 네트워크 또는 온프레미스 환경 접속에 자주 사용됩니다.</p><p>외부 접속 제어는 입구가 되는 Bastion 서버가 중심이 되기 때문에 통신 제어에 대해 알기 쉽고, 필요할 때만 작동하게 하면 평상시에는 외부로부터의 접속을 할 수 없는 상태로도 만들 수 있어 비용 삭감도 가능합니다.</p><h4>[2] AWS Systems Manager Session Manager</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*UHqIVD4KUSYj8RMY" /></figure><p>AWS 리소스 관리 서비스인 Systems Manager(SSM) 기능입니다. Bastion서버와 달리 IAM 정책 기반 액세스를 제어합니다. AWS Management Console 또는 AWS CLI에서 EC2 인스턴스에 로그인할 수 있으므로 EC2 인스턴스에 로그인하기 위해 통신 제어 설정을 하지 않아도 됩니다.<br>또한 EC2 인스턴스에 로그인하는 단말기에 SSH Key를 저장할 필요가 없다는 이점이 있습니다. (대신 IAM 자격 증명이 필요합니다)</p><p>사용에는 몇 가지 조건이 있으며, 로그인 할 EC2 인스턴스에 SSM Agent를 설치해야 합니다. 또한 폐쇄 환경에서 이용하는 경우에는 PrivateLink가 3개 필요한데, 비싸지는 않지만, Bastion 서버와 비교하면 비용이 증가 됩니다.</p><h4>[3] EC2 Instance Connect Endpoint</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*NAogEZ9qEiFXJnMq" /><figcaption><a href="https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/connect-with-ec2-instance-connect-endpoint.html"><em>AWS 문서</em></a><em> 에서 인용</em></figcaption></figure><p>이번에 소개하고자 하는 AWS 기능입니다. 원래 EC2 Instance Connect라는 기능이 있었는데요, 로그인 대상의 EC2 인스턴스에 퍼블릭 IPv4 주소를 할당해야 하기 때문에, 이용 경우가 적지 않았을까 생각 됩니다.</p><p>현재는 엔드포인트를 이용하여 퍼블릭 IPv4 주소를 가지지 않는 폐쇄 환경의 EC2 인스턴스 로그인이 가능하게 되었습니다.</p><p>접속 방법은 2가지가 있습니다. 하나는 기존의 Instance Connect와 마찬가지로 AWS Management Console에서 연결하는 방법입니다. 다른 하나는 AWS CLI를 사용하여 대상 EC2 인스턴스에 개인 터널을 설정하는 것입니다.<br>그리고 엔드포인트에 연결하려면 IAM 권한이 필요하며 EC2 인스턴스에 연결하려면 보안 그룹을 설정해야 합니다.</p><h3>EC2 Instance Connect Endpoint의 이점</h3><p>고정비가 들지 않는 것이 가장 큰 장점입니다. 다음 내용에 따르면 EC2 Instance Connect Endpoint는 비용이 발생하지 않는다고 합니다.</p><p><a href="https://aws.amazon.com/ko/about-aws/whats-new/2023/06/amazon-ec2-instance-connect-ssh-rdp-public-ip-address/?nc1=h_ls">https://aws.amazon.com/ko/about-aws/whats-new/2023/06/amazon-ec2-instance-connect-ssh-rdp-public-ip-address/?nc1=h_ls</a></p><blockquote>EIC Endpoint는 모든 AWS 상용 리전 및 AWS GovCloud(미국) 리전에서 사용할 수 있습니다. EIC Endpoint 사용에는 추가 비용이 발생하지 않습니다. 일반 데이터 전송에 대해서는 소정의 요금이 적용됩니다.</blockquote><p>일부 Linux로 제한되지만 Session Manager와 마찬가지로 AWS Management Console로 연결할 수 있기 때문에 SSH의 비공개 키를 연결된 단말에서 관리할 필요가 없다는 것도 큰 이점입니다. 또, AWS CLI로 프라이빗 터널을 만드는 경우는 접속원의 단말로 SSH 비밀키를 관리해야 하지만, Bastion서버의 SSH 포트 포워딩과 같은 이용 방법으로 대상 OS에 독립적으로 사용할 수 있습니다.</p><h3>이 게시글의 구성</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uS-KiRop935NOhL0" /></figure><p>본 게시글은 상기의 구성으로 진행 합니다.<br>또한 다음과 같이 EC2 Instance Connect Endpoint 이외의 설정은 완료된 것으로 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*qBGx5QsrugGT1bYaKG7PFw.png" /></figure><h4>주의</h4><blockquote>이미지와 항목 이름은 영어로 표시됩니다. 한국어 표시로 이용하시고자 하시는 분은 항목명을 한국어로 바꾸시길 바라겠습니다.</blockquote><h3>EC2 Instance Connect Endpoint 보안 그룹 만들기</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZtoSDdEyeGAzd32W" /></figure><ul><li>AWS Management Console에서 EC2 페이지로 이동</li><li>왼쪽 메뉴에서 Security Groups를 클릭</li><li>오른쪽 상단의 Create security group을 클릭</li><li>다음 항목을 입력하거나 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*vSSIbyCqCZIbGQFPkiTk3Q.png" /></figure><ul><li>Create security group 클릭</li><li>보안 그룹이 생성되었는지 확인</li></ul><h3>대상 EC2 인스턴스의 보안 그룹 수정</h3><ul><li>AWS Management Console에서 EC2 페이지로 이동</li><li>왼쪽 메뉴에서 Security Groups 클릭</li><li>목록에 있는 “example-prod-ssh-sg(연결 대상 EC2 인스턴스의 보안 그룹)” 선택</li><li>상단 메뉴에서 Actions-&gt;Edit Inbound rules 클릭</li><li>example-prod-eice-sg (EC2 Instance Connect Endpoint 보안 그룹)에서 SSH 연결 권한 부여 규칙 추가</li><li>Save rules 클릭</li></ul><h3>EC2 Instance Connect Endpoint 만들기</h3><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 Endpoints 클릭</li><li>오른쪽 상단의 Create endpoint 클릭</li><li>다음 항목을 입력하거나 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*BsyZmqoRgyOjdyC8I34w0g.png" /></figure><ul><li>Create endpoint 클릭</li><li>EC2 Instance Connect Endpoint 생성이 시작되고 ‘Status’가 ‘Pending’인지 확인</li><li>몇 분 후 ‘Status’가 ‘Available’이 되는지 확인</li></ul><h3>EC2 인스턴스에 로그인 확인</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*_wzIsmzgEq1O227s" /></figure><ul><li>AWS Management Console에서 EC2 페이지로 이동</li><li>왼쪽 메뉴에서 Instances 클릭</li><li>목록에 있는 “example-prod-eic-amzlinux-1a-01(로그인 대상 EC2 인스턴스)” 선택</li><li>상단 메뉴에서 Connect를 클릭</li><li>다음 항목을 입력하거나 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*3NsxT_R8ZN9Iz8B_eDGLkQ.png" /></figure><ul><li>Connect 클릭</li><li>웹 브라우저에 콘솔 화면이 표시되고 로그인이 시작됨</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*gdGZV7PZ0BOaXNkS" /><figcaption><em>로그인 후 콘솔 화면</em></figcaption></figure><h3>마지막으로</h3><p>EC2 Instance Connect Endpoint는 보안 그룹 설정 및 엔드포인트 생성만으로 완료되기 때문에 쉽게 배포할 수 있습니다. 다음 번에는 AWS CLI를 사용하여 프라이빗 터널을 통해 연결할 예정입니다. 폐쇄 환경의 EC2 인스턴스에 접속하는 방법의 하나로서 참고해 주시면 좋을 것 같습니다.</p><p>읽어 주셔서 감사합니다.</p><h3>참고 URL</h3><p><a href="https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/connect-with-ec2-instance-connect-endpoint.html">https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/connect-with-ec2-instance-connect-endpoint.html</a></p><p><a href="https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/WindowsGuide/connect-using-eice.html">https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/WindowsGuide/connect-using-eice.html</a></p><p><a href="https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/ec2-instance-connect-prerequisites.html">필수 조건</a></p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/d82b505744d0b6">https://zenn.dev/megazone_japan/articles/d82b505744d0b6</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 카와나 료(川名(亮))님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center <a href="http://medium.com/@pakuji">박지은 매니저</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=910fb5ec9833" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/bastion%EC%84%9C%EB%B2%84%EA%B0%80-%ED%95%84%EC%9A%94-%EC%97%86%EB%8B%A4-ec2-instance-connext-endpoint-%EC%B6%94%EC%B2%9C-%ED%8F%AC%EC%9D%B8%ED%8A%B8-1-910fb5ec9833">Bastion서버가 필요 없다? EC2 Instance Connect Endpoint 추천 포인트(1)</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[테스트하며 이해해보는 사이트 간 VPN (YAMAHA RTX830이용)]]></title>
            <link>https://medium.com/cloudvillains/%ED%85%8C%EC%8A%A4%ED%8A%B8%ED%95%98%EB%A9%B0-%EC%9D%B4%ED%95%B4%ED%95%B4%EB%B3%B4%EB%8A%94-%EC%82%AC%EC%9D%B4%ED%8A%B8-%EA%B0%84-vpn-yamaha-rtx830%EC%9D%B4%EC%9A%A9-f50aae055a80?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f50aae055a80</guid>
            <category><![CDATA[megazonecloud]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 06:53:46 GMT</pubDate>
            <atom:updated>2023-09-13T00:43:57.642Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS에는 VPN 서비스가 있어 외부에서 AWS로 접속 시, VPN을 이용하여 안전하게 접속이 가능합니다. 본 게시글에서는 YAMAHA RTX830 VPN 루터를 이용한 사이트간 VPN 접속 방법을 기재 해 보도록 하겠습니다.</p><p>Client VPN의 접속방법에 대해서는 저희 회사 다른 분이 쓰신 게시글을 참고 해 주시길 바랍니다.</p><p><a href="https://medium.com/cloudvillains/vpn-%EB%B6%84%ED%95%A0-%ED%84%B0%EB%84%90%EC%97%90-%EB%8C%80%ED%95%B4-%EB%B0%B0%EC%9A%B0%EB%A9%B4%EC%84%9C-vpn%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95-%ED%95%B4-%EB%B3%B4%EA%B8%B0-bdeee71351">https://medium.com/cloudvillains/vpn-%EB%B6%84%ED%95%A0-%ED%84%B0%EB%84%90%EC%97%90-%EB%8C%80%ED%95%B4-%EB%B0%B0%EC%9A%B0%EB%A9%B4%EC%84%9C-vpn%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95-%ED%95%B4-%EB%B3%B4%EA%B8%B0-bdeee71351</a></p><h3>2개의 VPN 사용 구분</h3><p>VPN은 공개 된 인터넷을 이용하면서 마치 전용 프라이빗 네트워크를 이용하는 것 처럼 안전하게 통신하는 기술 입니다. VPN은 주로 Client VPN과 사이트 간 VPN, 2가지로 나뉘는데요, 이들의 사용 방법에 대해 설명 해 보겠습니다.</p><h4>■ Client VPN</h4><p>Client VPN은 원격 액세스 VPN이라고도 불리며, VPN엔드포인트에 단말마다 VPN을 접속 합니다. VPN접속에 VPN Client 소프트웨어를 이용합니다. 또한 암호화에는 SSL/TLS를 이용 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*99Wo2h7-OYrGoKEI" /><figcaption><em>Client VPN 접속 예시</em></figcaption></figure><p>현재는 HTTPS나 SFTP와 같은 VPN을 이용하지 않아도 통신이 암호화 된 경우가 거의 대부분 입니다. 그렇기 때문에 Client VPN은 암호화때문이라기 보다는 ‘인터넷에서 내부 네트워크에 들어갈 것’ 이나 ‘Client VPN접속 후에 할당 된 Client CIDR에 의한 접속처 액세스 제한’을 목적으로 이용 된 경우가 많을 것 입니다.</p><p>사이트간 VPN과 다른 VPN 접속처가 고정 되어 있지 않은 것은 외출한 곳에서나 자택에서 VPN을 이용하여 내부 네트워크에 접속하는 경우를 의미합니다. 반대로 VPN Client소프트웨어가 설치 되지 않는 (또는 서버 등 운용상 인정 되지 않음) 기기는 VPN접속 불가하다는 단점도 있습니다.</p><h4>■ 사이트 간 VPN</h4><p>사이트간 VPN은 거점간 VPN이라고도 불리며, VPN엔드포인트에 대해 네트워크 단위로 VPN에 접속 합니다. VPN접속에는 VPN루터 (또는 그에 상당하는 기기)가 필요합니다. 또 암호화에는 IPsec이 이용 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-T2YNlY45lceibYo" /><figcaption>사이트간 VPN접속 예시</figcaption></figure><p>Client VPN과 다른 각각의 단말에 VPN Client소프트웨어를 인스톨하여 단말 시작 마다 VPN접속 인증 작업이 필요 없게 됩니다. VPN에 접속하는 네트워크에 설치되어 있는 것 만으로 이용 가능합니다. 그 때문에 외출한 곳에서나 자택에서의 VPN접속 용도로는 적합하지 않습니다. 일반적으로 오피스 네트워크, 데이터 센터, 클라우드 서비스 내의 프라이빗 네트워크를 접속하기 위해 이용 됩니다.</p><h3>본 게시글의 구성</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OmvG-LQgcTeybUet" /><figcaption>구성도</figcaption></figure><p>본 게시글은 상기와 같은 구성으로 생각 하고 있습니다.</p><p>또한 이하와 같이 VPN이외의 설정은 완료한 것으로 하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*8C4kFxp2zK56vPyIAaTzpA.png" /></figure><h3>주의</h3><blockquote>본 게시글의 이미지나 항목명은 영어로 되어 있습니다. 한국어 표시를 희망하시는 분들은 항목명을 한국어로 변환 해 주시길 바랍니다.</blockquote><h3>개요</h3><ol><li>고객 게이트웨이 만들기</li><li>가상 프라이빗 게이트웨이 만들기</li><li>가상 프라이빗 게이트웨이를 VPC에 연결</li><li>사이트 간 VPN 설정</li><li>RTX830용 VPN 설정 파일 다운로드</li><li>RTX830용 VPN 설정 파일 수정</li><li>라우팅 테이블 설정</li><li>RTX830 설정</li><li>VPN 접속 확인</li><li>VPN 연결 확인</li><li>마지막으로</li></ol><h3>고객 게이트웨이 만들기</h3><p>구성도에서 볼 수 있듯이 고객 게이트웨이 장치(RTX830)는 온프레미스 환경에 있습니다. 이제부터 생성하려는 ‘고객 게이트웨이’는 ‘고객 게이트웨이 리소스’라고 불리우는 AWS 측 설정입니다.</p><p>고객 게이트웨이 리소스에는 고객 게이트웨이 장치(RTX830)의 글로벌 IP 주소와 같은 장치에 대한 정보가 저장됩니다. AWS 사이트 간 VPN 연결을 설정할 때 고객 게이트웨이(고객 게이트웨이 리소스)를 지정하면 연결할 고객 게이트웨이 디바이스(RTX830) 정보를 매번 하나씩 입력할 필요가 없습니다.</p><p><a href="https://docs.aws.amazon.com/ko_kr/vpn/latest/s2svpn/your-cgw.html">https://docs.aws.amazon.com/ko_kr/vpn/latest/s2svpn/your-cgw.html</a></p><h4>■ 고객 게이트웨이 생성 작업</h4><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 Customer gateways를 클릭</li><li>Create customer gateway를 클릭하여 다음 항목을 입력하거나 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*_rf5Lk0QvHAiMTz9" /><figcaption><em>고객 게이트웨이 설정</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*uDC3SbvIfVbR0n_Lpim_gA.png" /></figure><ul><li>입력이나 선택이 완료되면 ‘Create customer gateway’를 클릭</li><li>고객 게이트웨이가 생성되었는지 확인</li></ul><h3>가상 프라이빗 게이트웨이 만들기</h3><p>가상 프라이빗 게이트웨이(Virtual Private Gateway)의 역할에 대해 설명하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*tM0HBghnoFEZnd5I" /><figcaption><em>VPC — 가상 프라이빗 게이트웨이</em></figcaption></figure><p>가상 프라이빗 게이트웨이는 VPN 연결에서 온프레미스와 통신할 때 이용되는 VPC의 출입구가 되는 게이트웨이입니다. 특정 VPC에 연결하면 ‘VPC — Virtual Private Gateway’가 접속됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*ZAnc8C8OLPtC6zii" /><figcaption><em>사이트 간 VPN 설정으로 가상 프라이빗 게이트웨이를 타겟 지정</em></figcaption></figure><p>사이트 간 VPN 연결을 만들 때 ‘가상 프라이빗 게이트웨이 — 사이트 간 VPN’의 타겟 설정을 진행합니다. 이렇게 하면 ‘VPC — 가상 프라이빗 게이트웨이 — 사이트 간 VPN’ 통신이 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*49gSmu50t0-IyamF" /><figcaption><em>AWS 사이트 간 VPN 온프레미스 및 VPN 연결 설정</em></figcaption></figure><p>온프레미스와 사이트 간 VPN 연결이 설정되면 ‘VPC — 가상 프라이빗 게이트웨이 — 사이트 간 VPN — 온프레미스’ 형태로 AWS와 온프레미스간 통신이 가능합니다.</p><h4>■ 가상 프라이빗 게이트웨이 생성 작업</h4><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 Virtual private gateways를 클릭</li><li>Create virtual private gateway를 클릭하여 다음 항목을 입력하거나 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*z8d0Mhny_yygkk5i" /><figcaption><em>가상 프라이빗 게이트웨이 설정</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*nQwsMeuo-CiUuwgzEWkrVg.png" /></figure><ul><li>입력 및 선택이 완료되면 ‘Create virtual private gateway’를 클릭</li><li>가상 프라이빗 게이트웨이가 생성되는지 확인</li></ul><h3>가상 프라이빗 게이트웨이를 VPC에 연결</h3><p>조금 전 만든 가상 프라이빗 게이트웨이를 VPC에 연결하여 VPC가 사이트 간 VPN을 통해 통신할 수 있도록 합니다.</p><h4>■ 가상 프라이빗 게이트웨이 연결 작업</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*WZ10z5wUU89yegbe" /><figcaption><em>VPC에 연결</em></figcaption></figure><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 ‘Virtual private gateways’를 클릭</li><li>방금 만든 ‘example-prod-vgw’에 체크 표시</li><li>오른쪽 상단의 ‘Actions’를 클릭</li><li>‘Attach to VPC’를 클릭</li><li>사용 가능한 VPC에서 VPN을 사용하는 VPC 선택</li><li>‘Attach to VPC’를 클릭</li><li>몇 분 후 ‘example-prod-vgw’의 상태가 ‘Attached’로 설정되어 있는지 확인</li></ul><h3>사이트 간 VPN 설정</h3><p>사이트 간 VPN 설정은 VPC에 대한 연결 대상으로 가상 프라이빗 게이트웨이를 지정합니다. 또한 온프레미스에 대한 연결 대상으로서 고객 게이트웨이를 지정합니다. 이 VPN 연결을 설정하면 가상 프라이빗 게이트웨이를 통해 VPC와 온프레미스 통신이 가능하게 됩니다.</p><p><a href="https://docs.aws.amazon.com/ko_kr/vpn/latest/s2svpn/create-cwan-vpn-attachment.html">https://docs.aws.amazon.com/ko_kr/vpn/latest/s2svpn/create-cwan-vpn-attachment.html</a></p><h4>■ 사이트 간 VPN 설정 작업</h4><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 ‘Site-to-Site VPN connections’를 클릭</li><li>‘Create VPN connection’을 클릭하여 다음 항목을 입력하거나 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*KIJ8oyq7UctYVf7J" /><figcaption><em>사이트 간 VPN 설정</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*HHFXhEPri8W0A7mx3eiT8A.png" /></figure><ul><li>Create VPN connection을 클릭</li><li>사이트 간 VPN 연결 설정이 추가되었는지 확인</li></ul><h3>RTX830용 VPN 구성 파일 다운로드</h3><p>RTX830용 VPN 설정 파일을 AWS Management Console에서 다운로드할 수 있습니다. 이 설정 파일에는 VPN 연결에 사용하는 자격 증명도 포함되어 있습니다. 본 게시글의 환경에서는 거의 그대로 사용 가능하지만, 샘플 파일이므로 자신의 환경에 맞추어 수정해야 합니다.</p><h4>■ 설정 파일 다운로드</h4><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 Site-to-Site VPN connections를 클릭</li><li>다운로드 구성을 클릭</li><li>이하의 항목을 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*ADamyX9BY2wInI5QVYKFhA.png" /></figure><ul><li>다운로드를 클릭하여 RTX830용 설정 파일을 로컬로 저장</li></ul><h3>RTX830용 VPN 설정 파일 수정</h3><p>다운로드한 RTX830용 VPN 설정 파일을 수정합니다. RTX830의 글로벌 IP 주소가 포함된 부분을 프라이빗IP 주소로 다시 씁니다.</p><h4>■ 변경 부분(1)</h4><p>첫 번째 VPN 터널의 local address를 라우터의 글로벌 IP 주소에서 프라이빗 IP 주소로 변경합니다.</p><pre>변경전<br>ipsec ike local address 1 xxx.xxx.xxx.xxx</pre><pre>변경후<br>ipsec ike local address 1 192.168.100.1</pre><p>※ xxx.xxx.xxx.xxx에는 Create customer gateway경우 지정한 라우터의 외부 IP 주소(Global IP Address)가 기재되어 있습니다.</p><p>※ 192.168.100.1은 RTX830의 기본 내부 IP주소 (Private IP Address)입니다.</p><h4>■ 변경 부분(2)</h4><p>두 번째 VPN 터널의 ‘local address’를 라우터의 글로벌 IP 주소에서 사설 IP 주소로 변경합니다.</p><pre>변경전<br>ipsec ike local address 1 xxx.xxx.xxx.xxx</pre><pre>변경후<br>ipsec ike local address 1 192.168.100.1</pre><p>※xxx.xxx.xxx.xxx에는 Create customer gateway시에 지정한 라우터의 외부 IP 주소(Global IP Address)가 기재되어 있습니다.</p><p>※ 192.168.100.1은 RTX830의 기본 내부 IP주소 (Private IP Address)입니다.</p><h3>라우팅 테이블 설정</h3><p>이번에는 프라이빗 서브넷만 VPN 연결을 이용하여 온프레미스 환경과 통신할 수 있도록 합니다. 온프레미스 환경으로 라우팅 설정이 필요하지만 라우팅 정보는 BGP를 사용하여 온프레미스 환경의 라우터인 RTX830과 상호 작용합니다. (그 때문에 VPN 설정 생성시 Routing options에서 Dynamic (requires BGP)를 지정하고 있습니다)</p><p>Route propagation(라우팅 전파)을 활성화하면, VPN 연결 대상인 온프레미스 환경의 라우터(RTX830)에서 라우팅 정보를 받아 라우팅 테이블에 추가합니다.</p><p><a href="https://docs.aws.amazon.com/ko_kr/vpn/latest/s2svpn/VPNRoutingTypes.html">https://docs.aws.amazon.com/ko_kr/vpn/latest/s2svpn/VPNRoutingTypes.html</a></p><h4>■ 루트 테이블 설정 작업</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*w9jm4Na7eQFq7FWO" /><figcaption><em>라우팅 테이블 설정</em></figcaption></figure><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 Route tables를 클릭</li><li>사이트 간 VPN을 사용하는 프라이빗 서브넷의 라우팅 테이블 선택</li><li>아래에 표시되는 라우팅 테이블 설정에서 Route propagation(라우팅 전파)을 클릭</li><li>Edit route propagation(라우팅 전파 편집)을 클릭</li><li>Propagation(전파)의 Enable(활성화)을 선택합니다.</li><li>Save를 클릭</li></ul><h3>RTX830 설정</h3><blockquote>이 설정을 진행 하기 전에 RTX830에서 사용하고 있는 기존 config 파일을 내보내 복원할 수 있도록 해 주십시오.<br>RTX830측에 VPN 설정이 있거나 VPN 설정이 터널 1과 터널 2로 설정된 경우 둘 다 AWS VPN 설정을 덮어쓰게 됩니다.</blockquote><h4>■ RTX830에 VPN 설정 추가</h4><ul><li>RTX830 관리 화면 (GUI)에 액세스</li><li>상단 메뉴에서 관리를 클릭</li><li>유지보수 -&gt; 명령 실행</li><li>RTX830 용 VPN 설정 파일 내용 (텍스트)을 ‘커맨드 입력’양식에 붙여 넣기</li><li>실행 클릭</li><li>VPN 설정 추가</li></ul><h4>■ RTX830의 VPN 설정 확인</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xWMtW2sXaxgR6Uam" /><figcaption><em>RTX830의 VPN 설정</em></figcaption></figure><ul><li>상단 메뉴에서 간단 설정 클릭</li><li>VPN -&gt; 거점 간 연결 클릭</li><li>연결 설정 목록에 두 개의 VPN 설정이 추가되어 있는지, VPN 연결이 설정되어 있는지 확인(접속 상황이 초록색 화살표로 되어있다면 OK)</li></ul><h4>■ RTX830의 Config 확인</h4><ul><li>라우터 관리 화면 (GUI)의 오른쪽 상단에서 config를 클릭</li><li>브라우저에서 보기를 클릭</li><li>tunnel select 1, tunnel select 2 설정이 추가되어 AWS Management Console에서 다운로드한 RTX용 VPN 구성 파일의 설정 값과 동일한지 확인</li></ul><h3>VPN 접속 확인</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cSastPFs2PeVh33V" /><figcaption><em>VPN 연결 확인</em></figcaption></figure><ul><li>AWS Management Console에서 VPC 페이지로 이동</li><li>왼쪽 메뉴에서 Site-to-Site VPN connections를 클릭</li><li>example-prod-vpn의 VPN 연결에 체크 표시</li><li>하단 메뉴의 Tunnel details-&gt;Tunnel state-&gt;Status가 UP인지 확인</li></ul><h3>VPN 연결 확인</h3><p>AWS -&gt; 온프레미스, 온프레미스 -&gt; AWS의 양방향 연결을 확인합니다.</p><h4>■ AWS에서 온프레미스로의 연결 확인</h4><ul><li>프라이빗 서브넷에 설치된 EC2 인스턴스 ‘10.0.11.154’에 Bastion을 통해 SSH 로그인</li><li>‘10.0.11.154’에서 온 프레미스 클라이언트 ‘192.168.100.2’에 ping으로 연결 확인 (192.168.100.2측에서 ICMP의 Echo Request를 허가해 둠)</li></ul><pre>AWS에서 온프레미스로의 ping<br>$ ping 192.168.100.2<br>PING 192.168.100.2 (192.168.100.2) 56(84) bytes of data.<br>64 bytes from 192.168.100.2: icmp_seq=1 ttl=127 time=8.14 ms<br>64 bytes from 192.168.100.2: icmp_seq=2 ttl=127 time=7.40 ms<br>64 bytes from 192.168.100.2: icmp_seq=3 ttl=127 time=7.74 ms<br>64 bytes from 192.168.100.2: icmp_seq=4 ttl=127 time=7.87 ms<br>64 bytes from 192.168.100.2: icmp_seq=5 ttl=127 time=7.69 ms</pre><p>※연결 OK</p><h4>■ 온프레미스에서 AWS로의 연결 확인</h4><ul><li>온프레미스 클라이언트 192.168.100.2에 로그인</li><li>192.168.100.2에서 온프레미스 Client 10.0.11.154로 ping을 통해 연결 확인</li></ul><pre>온프레미스에서 AWS로의 ping<br>&gt; ping 10.0.11.154<br>10.0.11.154 에 ping을 송신 하고 있습니다 32바이트 데이터:<br>10.0.11.154 에서의 응답: 바이트 수 =32시간 =7ms TTL=126<br>10.0.11.154 에서의 응답: 바이트 수=32시간 =7ms TTL=126<br>10.0.11.154 에서의 응답: 바이트 수=32시간 =8ms TTL=126<br>10.0.11.154 에서의 응답: 바이트 수=32시간 =7ms TTL=126<br>10.0.11.154 의 ping통계:<br>패킷 수: 송신 = 4, 수신 = 4, 손실 = 0 (0%의 손실),<br>라운드 트립 예상 시간 (밀리 초):<br>최소 = 7ms, 최대 = 8ms, 평균 = 7ms</pre><p>※연결 OK</p><h3>마지막으로</h3><p>사이트간 VPN은 저렴하게 도입할 수 있는 거점간 통신으로서 널리 사용되고 있습니다. YAMAHA RTX830은 사이트간 VPN을 이용할 수 있는 VPN 라우터로서는 저렴하기때문에, 관심이 있으신 분은 본 게시글을 참고로 사이트간 VPN을 꼭 시험해 보시길 바랍니다.</p><p>읽어 주셔서 감사합니다.</p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/89e300e27b28e2">https://zenn.dev/megazone_japan/articles/aee08a90c42edf</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 카와나 료(川名(亮))님의 동의를 얻어 번역한 게시글 입니다.</p><p>번역 : 메가존클라우드 Cloud Techonolgy Center <a href="https://medium.com/@pakuji">박지은 매니저</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f50aae055a80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/%ED%85%8C%EC%8A%A4%ED%8A%B8%ED%95%98%EB%A9%B0-%EC%9D%B4%ED%95%B4%ED%95%B4%EB%B3%B4%EB%8A%94-%EC%82%AC%EC%9D%B4%ED%8A%B8-%EA%B0%84-vpn-yamaha-rtx830%EC%9D%B4%EC%9A%A9-f50aae055a80">테스트하며 이해해보는 사이트 간 VPN (YAMAHA RTX830이용)</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform + AWS Batch + Golang으로 스케줄 실행 / 수동 배치 생성하기]]></title>
            <link>https://medium.com/cloudvillains/terraform-aws-batch-golang%EC%9C%BC%EB%A1%9C-%EC%8A%A4%EC%BC%80%EC%A4%84-%EC%8B%A4%ED%96%89-%EC%88%98%EB%8F%99-%EB%B0%B0%EC%B9%98-%EC%83%9D%EC%84%B1%ED%95%98%EA%B8%B0-d6e50ea6b8c0?source=rss-d9957cf2c6c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e50ea6b8c0</guid>
            <dc:creator><![CDATA[MZC_Global]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 01:08:01 GMT</pubDate>
            <atom:updated>2023-08-18T01:08:43.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/125/0*4Abi7MCq8DT2fZqg" /></figure><h3>시작하며</h3><p>배치나 작업을 단발적 혹은 정기적으로 실행 하고자 할 때, Lambda로 구현하여 대응하는 경우가 많습니다. 하지만 Lambda는 실행 시간 문제가 있어, 여러 상황에 모두 대응 가능하다고는 할 수 없습니다.</p><p>대안으로 AWS Batch나 Amazon ECS를 고려할 수 있지만, 이번에는 AWS Batch(스케줄 실행 / AWS CLI기준의 수동 실행)를 Terraform+Golang 컨테이너 이미지로 구성 해 보았습니다.</p><p>본 게시글에서 다루고 있는 처리 내용의 구성을 참고하여 여러분의 환경에 맞게 커스터마이즈하여 사용 해 보시면 좋을 듯 합니다.</p><h3>대상자</h3><ul><li>AWS를 이용 중 혹은 검증 중인 분</li><li>비교적 처리 시간이 걸리는 배치나 작업을 스케줄링 하거나 수동 실행 하고 싶은 분</li><li>Terraform으로 디플로이를 자동화 하고 싶은 분</li></ul><h3>개요</h3><ol><li>환경 셋업</li><li>스케줄링 작동 확인</li><li>수동 작업 작동 확인</li></ol><h3>1. 환경 셋업</h3><h4><strong>전제 조건</strong></h4><p>하기의 셋업이 필요 합니다.</p><pre>- AdministratorAccess상당 IAM유저 권한<br>- git<br>- docker<br>- terraform</pre><p><a href="https://github.com/agamemnon-ai/golang-test">https://github.com/agamemnon-ai/golang-test</a></p><p>로컬 환경에 셋업하기 어려운 경우에는 AWS Cloud9을 사용해 ECR에 이미지 업로드까지 완료 시켜 주세요.</p><h4><strong>로컬에서 테스트</strong></h4><pre>$ cd golang-test<br>$ docker build .</pre><p>git clone실행 후 로컬에서 작동 확인을 합니다.</p><p><strong>main.go</strong></p><pre>package main<br><br>import (<br> “fmt”<br> “os”<br>)<br><br>func main() {<br> env1 := os.Getenv(“ENV1”)<br> env2 := os.Getenv(“ENV2”)<br> fmt.Println(env1)<br> fmt.Println(env2)<br>}</pre><p>처리 내용은 심플하게 환경 변수의 값을 표시하는 것 입니다.</p><p>기본으로 “Hello golang”이라고 표시 되어 있지만, ENV1 및 ENV2 값을 보내면 표시할 텍스트 내용을 바꾸는 것이 가능합니다.</p><pre>$ docker container run [※image id]<br>Hello golang<br><br>$ docker container run -e ENV1=GoodBye -e ENV2=all [※image id]<br>GoodBye all</pre><p>동작이 확인 되었다면, 다음으로 AWS Batch 실행 환경을 생성 합니다.</p><p>버지니아 북부 리전 이용 기준 입니다.</p><h4>Terraform 실행 준비</h4><pre>$ cd terraform</pre><p>“terraform.tfvars”파일의 파라미터를 각각 설정 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*UGL7aGzeO4LsSFfp" /></figure><ul><li>project/environment : 디플로이된 각 AWS 리소스 이름에 반영 됩니다. 임의의 값을 설정 해 주세요.</li><li>account : 사용하시는 AWS 계정 번호 입니다.</li><li>shot-batch-vcpu : 배치의 vCPU이지만, 변경할 필요가 없다면 기본값으로 둡니다.</li><li>shot-batch-image : [※Account_No].dkr.ecr.us-east-1.amazonaws.com/golang-test:[※Tag]</li><li>scheduling-batch-interval : 스케줄링 작업이 실행 된 주기 입니다. 테스트를 위해 15분마다로 설정 하였지만, 임의 시간으로 설정 해 주세요.</li></ul><p><a href="https://docs.aws.amazon.com/ko_kr/eventbridge/latest/userguide/eb-rate-expressions.html">https://docs.aws.amazon.com/ko_kr/eventbridge/latest/userguide/eb-rate-expressions.html</a></p><h4><strong>Terraform 실행</strong></h4><pre>$ terraform init<br>$ terraform plan<br><br>// If there are no problems with the results of the execution of the “terraform plan”<br>$ terraform apply</pre><p>디플로이 된 AWS 리소스는 하기와 같습니다.</p><ul><li>네트워크</li></ul><p>퍼블릭 서브넷 * 2 / 프라이빗 서브넷 * 2</p><p>NAT게이트웨이 있음</p><ul><li>AWS Batch</li></ul><p>EventBridge와 연계 시키는 스케줄링 작업 / AWS CLI의 트리거를 가정한 수동 작업을 각각 생성 합니다</p><ul><li>보안 그룹</li><li>ECR 리포지토리</li><li>AWS Batch / EventBridge용 IAM롤</li><li>스케줄링 작업/수동 작업 각각과 연계하는 CloudWatch로그 그룹</li></ul><h4><strong>ECR에 이미지 PUSH</strong></h4><p>에러 없이 디플로이가 완료 되었다면 ECR리포지토리에 이미지를 PUSH합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*BUfkj9uUAawJL2jt" /></figure><p>ECR에 업로드하는 순서는 AWS매니지먼트 콘솔의 ‘View push commands’의 순서에 따라 주세요.</p><p>이상으로 환경 셋업은 완료 입니다.</p><h3>2. 스케줄링 작업의 작동 확인</h3><h4><strong>작업 확인</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*kxYcvKlLIGzLyXrx" /></figure><p>15분 마다 처리가 되는 것으로 실행 된 것을 알 수 있습니다.</p><h4><strong>로그 확인</strong></h4><ul><li>AWS매니지먼트 콘솔의 CloudWatch페이지 =&gt; Log groups=&gt; aws/ecs/blog-dev-scheduling-execution-batch</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E5AYjjkbQ2_p0Ols" /></figure><p>기본 설정인 “Hello golang”이 표시 되어 있습니다.</p><h4><strong>Terraform값으로 환경 변수 지정</strong></h4><p>batch.tf</p><pre># — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -<br># Job Definition for Scheduling Batch<br># — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -<br><br>resource “aws_batch_job_definition” “scheduling_batch_definition” {<br> name = “${var.project}-${var.environment}-scheduling-batch-definition”<br> type = “container”<br><br>platform_capabilities = [<br> “FARGATE”,<br> ]<br><br>container_properties = jsonencode({<br> image = “${var.shot-batch-image}”<br><br>fargatePlatformConfiguration = {<br> platformVersion = “LATEST”<br> }<br> <br> environment = [<br> {<br> name = “ENV1”<br> value = “GoodBye”<br> },<br> {<br> name = “ENV2”<br> value = “All”<br> }<br> ]<br><br>resourceRequirements = [<br> {<br> type = “VCPU”<br> value = “0.25”<br> },<br> {<br> type = “MEMORY”<br> value = “512”<br> }<br> ]<br><br>“logConfiguration” : {<br> “logDriver” : “awslogs”,<br> “options” : {<br> “awslogs-group” : “${aws_cloudwatch_log_group.cloudwatch_log_group-scheduling.name}”,<br> “awslogs-region” : “us-east-1”,<br> “awslogs-stream-prefix” : “ecs”<br> }<br> }<br><br>executionRoleArn = aws_iam_role.aws_batch_service_execution_role.arn<br> })<br>}</pre><p>AWS Batch용 tf파일 =&gt; 스케줄링 배치 작업 정의로 “environment”를 지정 합니다.</p><pre>environment = [<br> {<br> name = “ENV1”<br> value = “GoodBye”<br> },<br> {<br> name = “ENV2”<br> value = “All”<br> }<br> ]</pre><pre>$ terraform plan<br><br>// If there are no problems with the results of the execution of the “terraform<br>$ terraform apply</pre><p>적용 후 CloudWatch Logs를 확인 하면</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G3W3ZyC20ov4ndsz" /></figure><p>처리 결과가 바뀌었습니다.</p><h3>3. 수동 작업 작동 확인</h3><h4><strong>AWS CLI로 2종류 배치 작업 실행</strong></h4><pre># 1<br># Run without specifying environment variables<br>$ aws batch submit-job — job-name “test-job” — job-queue “blog-dev-shot-batch-queue” — job-definition “blog-dev-shot-batch-definition”<br>{<br> “jobName”: “test-job”, <br> “jobArn”: “arn:aws:batch:us-east-1:xxxxxxxx:job/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx”, <br> “jobId”: “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”<br>}<br><br># 2<br># Run again without specifying environment variables<br>$ aws batch submit-job — job-name “test-job” — job-queue “blog-dev-shot-batch-queue” — job-definition “blog-dev-shot-batch-definition”<br>{<br> “jobName”: “test-job”, <br> “jobArn”: “arn:aws:batch:us-east-1:xxxxxxxx:job/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx”, <br> “jobId”: “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”<br>}<br><br># 3<br># Run with environment variable specification<br>$ aws batch submit-job — job-name “test-job” — job-queue “blog-dev-shot-batch-queue” — job-definition “blog-dev-shot-batch-definition” — container-overrides ‘environment = [{name = ENV1 , value = GoodBye},{name = ENV2 , value = all}]’ <br>{<br> “jobName”: “test-job”, <br> “jobArn”: “arn:aws:batch:us-east-1:xxxxxxxx:job/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx”, <br> “jobId”: “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”<br>}</pre><p>작업 큐나 작업 정의명은 자신의 환경값으로 바꿔 주세요.</p><h4><strong>작업 확인</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/0*HpwypTLtiCoD-uPW" /></figure><h4><strong>로그 확인</strong></h4><ul><li>AWS 매니지먼트 콘솔의 CloudWatch 페이지 =&gt; Log groups=&gt; /aws/ecs/blog-dev-shot-batch</li></ul><ol><li>환경 변수 없이 실행</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YOemTzaxiclVDIsT" /></figure><p>2. 환경 변수 없이 한번 더 실행</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DhXDMC7aMZVQnaHg" /></figure><p>3. 환경 변수 있도록 실행</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JhPdY-szs_oFzaC" /></figure><p>여러 번 실행, 환경 변수 지정에 따른 동작 변경이 가능한 것을 확인 하였습니다.</p><h3>마지막으로</h3><p>이상 간단한 처리를 스케줄 실행/CLI로 단발적으로 실행 시켜 보았습니다.</p><p>이 구성을 기초로 여러분의 환경에 맞게 커스터 마이즈 해 보셨으면 합니다.</p><p>지금까지 읽어주셔서 감사드립니다.</p><p>원문게시글 : <a href="https://zenn.dev/megazone_japan/articles/07a516704881fe">https://zenn.dev/megazone_japan/articles/07a516704881fe</a></p><p>메가존 일본 법인 블로그에 업로드 중인 게시글로 작성자 아가(阿河)님의 동의를 얻어 번역한 게시글 입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e50ea6b8c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/terraform-aws-batch-golang%EC%9C%BC%EB%A1%9C-%EC%8A%A4%EC%BC%80%EC%A4%84-%EC%8B%A4%ED%96%89-%EC%88%98%EB%8F%99-%EB%B0%B0%EC%B9%98-%EC%83%9D%EC%84%B1%ED%95%98%EA%B8%B0-d6e50ea6b8c0">Terraform + AWS Batch + Golang으로 스케줄 실행 / 수동 배치 생성하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>