<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>seanson.log</title>
        <link>https://velog.io/</link>
        <description></description>
        <lastBuildDate>Sat, 10 Oct 2026 03:05:36 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>seanson.log</title>
            <url>https://velog.velcdn.com/images/seanson2709/profile/d1c0bb72-3f18-4125-ac53-52602774e0ad/image.png</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. seanson.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/seanson2709" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[쉽게 따라하는 LZA를 활용한 AWS Control Tower 구축 (4) - 보안 Service와 Identity Center, 그리고 시리즈 정리]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-4-%EB%B3%B4%EC%95%88-Service%EC%99%80-Identity-Center-%EA%B7%B8%EB%A6%AC%EA%B3%A0-%EC%8B%9C%EB%A6%AC%EC%A6%88-%EC%A0%95%EB%A6%AC</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-4-%EB%B3%B4%EC%95%88-Service%EC%99%80-Identity-Center-%EA%B7%B8%EB%A6%AC%EA%B3%A0-%EC%8B%9C%EB%A6%AC%EC%A6%88-%EC%A0%95%EB%A6%AC</guid>
            <pubDate>Sat, 10 Oct 2026 03:05:36 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p><a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-3-Transit-Gateway-VPC-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EA%B5%AC%EC%84%B1">3편</a>에서 Network까지 구성했으니 이번에는 보안 쪽입니다. 그리고 이번 편으로 LZA 시리즈를 마무리하려고 합니다.</p>
<p>LZA 설정 파일 6개 중에 2편에서 <code>organization-config.yaml</code>, <code>accounts-config.yaml</code>을, 3편에서 <code>network-config.yaml</code>을 다뤘습니다. 남은 건 <code>security-config.yaml</code>, <code>iam-config.yaml</code>, <code>global-config.yaml</code>입니다. <code>global-config.yaml</code>의 CloudTrail 얘기는 2편에서 이미 했으니, 이번 편은 나머지 두 파일이 중심입니다.</p>
<p>이번 글에서 다루는 내용은 아래와 같습니다.</p>
<ul>
<li><code>security-config.yaml</code> 기본값과 지금까지 바꾼 부분</li>
<li>이미 켜 둔 것 확인하기 (S3 Public Access Block, Config Recorder, IAM 비밀번호 정책)</li>
<li>GuardDuty, Security Hub를 켜고 Audit 계정에서 모아 보기</li>
<li><code>iam-config.yaml</code>로 Identity Center 권한 세트 관리하기</li>
<li>시리즈를 마치며: 실제 비용, LZA가 맞는 경우와 과한 경우</li>
</ul>
<p>사실 3편을 쓸 때 &quot;다음 편에서 GuardDuty, Security Hub를 다룬다&quot;고 예고해 놓고, 막상 설정 파일을 열어 보니 둘 다 <code>enable: false</code>였습니다. 설치하고 나서 한 번도 안 켰던 겁니다. 그래서 이번 글을 쓰면서 실제로 켜 보고, 그 과정을 그대로 적었습니다.</p>
<blockquote>
<p>계정 ID는 <code>111122223333</code>으로 가렸습니다. 설정 파일은 실제로 쓰는 파일에서 필요한 부분만 잘라 왔습니다.</p>
</blockquote>
<hr>
<h2 id="1-기본-security-configyaml">1. 기본 security-config.yaml</h2>
<p>LZA를 처음 설치하면 <code>security-config.yaml</code>은 아래처럼 생겼습니다. 3편과 마찬가지로 S3 config Bucket의 <code>default/</code> 폴더에 있는 설치 직후 파일입니다. 길어서 앞부분만 가져왔습니다.</p>
<pre><code class="language-yaml">centralSecurityServices:
  delegatedAdminAccount: Audit
  ebsDefaultVolumeEncryption:
    enable: false
    excludeRegions: []
  s3PublicAccessBlock:
    enable: false
    excludeAccounts: []
  scpRevertChangesConfig:
    enable: false
  snsSubscriptions: []
  macie:
    enable: false
    ...
  guardduty:
    enable: false
    ...
  securityHub:
    enable: false
    regionAggregation: false
    excludeRegions: []
    standards: []
    ...
accessAnalyzer:
  enable: false
iamPasswordPolicy:
  ...
  minimumPasswordLength: 14
  passwordReusePrevention: 24
  maxPasswordAge: 90
awsConfig:
  enableConfigurationRecorder: false
  ruleSets: []</code></pre>
<p>보안 Service는 거의 다 꺼져 있습니다. 다만 맨 위의 <code>delegatedAdminAccount: Audit</code>는 처음부터 들어 있습니다. GuardDuty, Security Hub, Macie 같은 Service를 켜면 관리 계정이 아니라 Audit 계정이 위임 관리자(delegated administrator)가 되어서, 모든 계정의 결과를 Audit 계정에서 모아 보게 됩니다. Control Tower가 만들어 주는 Audit 계정을 그대로 쓰는 구조입니다.</p>
<p>비밀번호 정책은 기본값부터 꽤 엄격합니다. 14자 이상, 최근 24개 재사용 금지, 90일마다 변경입니다.</p>
<p>설치 후 지금까지 제가 바꾼 건 두 줄뿐이었습니다.</p>
<pre><code class="language-diff">   s3PublicAccessBlock:
-    enable: false
+    enable: true
     excludeAccounts: []
 ...
 awsConfig:
-  enableConfigurationRecorder: false
+  enableConfigurationRecorder: true
   ruleSets: []</code></pre>
<hr>
<h2 id="2-이미-켜-둔-것-확인하기">2. 이미 켜 둔 것 확인하기</h2>
<p>GuardDuty를 켜기 전에, 이미 켜 둔 두 가지와 비밀번호 정책이 실제 계정에 어떻게 들어가 있는지 먼저 확인했습니다. 아래는 workload 계정에서 조회한 결과입니다. 다른 계정도 결과가 같았습니다.</p>
<h3 id="s3-public-access-block">S3 Public Access Block</h3>
<p><code>s3PublicAccessBlock.enable: true</code>로 두면 계정 단위 S3 Public Access Block 4개가 전부 켜집니다. Bucket 단위가 아니라 계정 단위라서, 이 계정에서는 누가 Bucket을 새로 만들어도 공개 설정이 막힙니다.</p>
<pre><code class="language-bash">aws s3control get-public-access-block --account-id 111122223333</code></pre>
<pre><code class="language-json">{
    &quot;PublicAccessBlockConfiguration&quot;: {
        &quot;BlockPublicAcls&quot;: true,
        &quot;IgnorePublicAcls&quot;: true,
        &quot;BlockPublicPolicy&quot;: true,
        &quot;RestrictPublicBuckets&quot;: true
    }
}</code></pre>
<p>정말로 공개 Bucket이 필요한 계정이 있으면 <code>excludeAccounts</code>에 그 계정 이름을 넣으면 됩니다. 저는 아직 그런 계정이 없어서 비워 뒀습니다.</p>
<h3 id="config-recorder">Config Recorder</h3>
<p>여기는 조금 헷갈렸습니다. <code>enableConfigurationRecorder: true</code>로 켰으니 LZA가 모든 계정에 Config Recorder를 만들었을 거라고 생각했는데, workload 계정에 있는 Recorder 이름을 보면 Control Tower 것입니다.</p>
<pre><code class="language-bash">aws configservice describe-configuration-recorder-status \
  --query &#39;ConfigurationRecordersStatus[].[name,recording,lastStatus]&#39; --output text</code></pre>
<pre><code class="language-text">aws-controltower-BaselineConfigRecorder    True    SUCCESS</code></pre>
<p>Control Tower는 등록된 계정마다 <code>aws-controltower-BaselineConfigRecorder</code>를 만들어 둡니다. 그런데 관리 계정은 Control Tower가 Config를 켜 주지 않습니다. 관리 계정에서 같은 명령을 돌려 보면 LZA가 만든 Recorder가 나옵니다.</p>
<pre><code class="language-text">AWSAccelerator-SecurityResourcesStack-111122223333-us-east-1-ConfigRecorder-1JYL5ECSCI9B8    True</code></pre>
<p>정리하면 Control Tower와 같이 쓸 때 이 옵션은 사실상 Control Tower가 비워 둔 관리 계정을 채워 주는 역할입니다. Security Hub를 켜려면 모든 계정에 Config가 켜져 있어야 해서, 이 한 줄은 켜 두는 게 좋습니다.</p>
<h3 id="iam-비밀번호-정책">IAM 비밀번호 정책</h3>
<p><code>iamPasswordPolicy</code>는 기본값 그대로 두었는데, 모든 계정에 실제로 들어가 있습니다.</p>
<pre><code class="language-bash">aws iam get-account-password-policy</code></pre>
<pre><code class="language-json">{
    &quot;PasswordPolicy&quot;: {
        &quot;MinimumPasswordLength&quot;: 14,
        &quot;RequireSymbols&quot;: true,
        &quot;RequireNumbers&quot;: true,
        &quot;RequireUppercaseCharacters&quot;: true,
        &quot;RequireLowercaseCharacters&quot;: true,
        &quot;AllowUsersToChangePassword&quot;: true,
        &quot;ExpirePasswords&quot;: true,
        &quot;MaxPasswordAge&quot;: 90,
        &quot;PasswordReusePrevention&quot;: 24,
        &quot;HardExpiry&quot;: false
    }
}</code></pre>
<p>저는 IAM User 없이 Identity Center로만 로그인해서 이 정책을 직접 겪을 일은 없습니다. 그래도 누가 나중에 IAM User를 만들면 바로 적용되니 그대로 두었습니다.</p>
<hr>
<h2 id="3-guardduty-security-hub-켜기">3. GuardDuty, Security Hub 켜기</h2>
<p>이제 3편에서 예고했던 GuardDuty와 Security Hub를 켜 보겠습니다. <code>security-config.yaml</code>에서 바꾼 부분은 아래와 같습니다.</p>
<pre><code class="language-diff">   guardduty:
-    enable: false
+    enable: true
     excludeRegions: []
     s3Protection:
-      enable: false
+      enable: true
       excludeRegions: []
+    eksProtection:
+      enable: true
+      excludeRegions: []
+    ec2Protection:
+      enable: true
+      keepSnapshots: false
+      excludeRegions: []
+    rdsProtection:
+      enable: true
+      excludeRegions: []
+    lambdaProtection:
+      enable: true
+      excludeRegions: []
     ...
   securityHub:
-    enable: false
+    enable: true
     regionAggregation: false
     excludeRegions: []
-    standards: []
+    standards:
+      - name: AWS Foundational Security Best Practices v1.0.0
+        enable: true
+        controlsToDisable: []</code></pre>
<p>GuardDuty는 <code>enable: true</code>만 바꾸면 기본 위협 탐지만 켜지고, S3, EKS, EC2 Malware Protection, RDS, Lambda 같은 보호 플랜은 항목마다 따로 켜야 합니다. 사실 제 환경은 GuardDuty가 이미 계정마다 따로 켜져 있었고, 이 보호 플랜들도 켜져 있었습니다. 그래서 지금 켜져 있는 상태와 똑같이 맞춰서 적었습니다. 설정 파일과 실제 상태가 다르면 다음 배포에서 LZA가 설정 파일 쪽으로 바꿔 버리기 때문입니다.</p>
<p>Security Hub는 <code>standards</code>에 켜고 싶은 보안 표준을 이름으로 적습니다. 저는 AWS가 만든 기본 표준인 AWS Foundational Security Best Practices(FSBP) 하나만 넣었습니다. 이름은 Security Hub Console이나 CLI에 나오는 이름과 똑같이 적어야 합니다.</p>
<pre><code class="language-bash">aws securityhub describe-standards --query &#39;Standards[].Name&#39; --output text</code></pre>
<pre><code class="language-text">AI Security Best Practices v1.0.0    AWS Foundational Security Best Practices v1.0.0    AWS Resource Tagging Standard v1.0.0    ...    CIS AWS Foundations Benchmark v1.2.0    CIS AWS Foundations Benchmark v1.4.0    CIS AWS Foundations Benchmark v3.0.0    ...</code></pre>
<h3 id="pipeline-실행">Pipeline 실행</h3>
<p>수정한 설정 파일을 zip으로 묶어서 config Bucket에 올리고 Pipeline을 시작합니다. 2편, 3편과 같은 방법입니다.</p>
<pre><code class="language-bash">aws s3api put-object --bucket aws-accelerator-config-111122223333-us-east-1 \
  --key zipped/aws-accelerator-config.zip --body aws-accelerator-config.zip
aws codepipeline start-pipeline-execution --name AWSAccelerator-Pipeline</code></pre>
<p>Review 단계에서 diff를 보면 이번 변경으로 새로 생기는 리소스가 보입니다. 기존 리소스를 지우거나 바꾸는 건 없고, 전부 <code>[+]</code>입니다. 아래는 Organization 단계와 SecurityAudit 단계 diff에서 GuardDuty, Security Hub 관련 Custom Resource만 골라 온 것입니다.</p>
<pre><code class="language-text">[+] Custom::GuardDutyEnableOrganizationAdminAccount GuardDutyEnableOrganizationAdminAccount90D7393E
[+] Custom::SecurityHubEnableOrganizationAdminAccount SecurityHubOrganizationAdminAccount71D5E029
[+] Custom::EnableAwsServiceAccess EnableGuardDutyServiceAccess31BC7ABD
[+] Custom::GuardDutyCreateMembers GuardDutyMembersD34CA003
[+] Custom::GuardDutyUpdateDetector GuardDutyDetectorConfigDD64B103
[+] Custom::SecurityHubCreateMembers SecurityHubMembers2A2B77C4</code></pre>
<p>이름을 보면 LZA가 하는 일이 그대로 보입니다. 관리 계정의 Organization 단계에서 Audit 계정을 GuardDuty, Security Hub 위임 관리자로 지정하고, SecurityAudit 단계에서 Audit 계정이 나머지 계정을 멤버로 추가합니다. 마지막 Deploy 단계의 Security_Resources에서는 계정마다 Security Hub 이벤트를 CloudWatch Logs로 보내는 Lambda와 EventBridge Rule이 생깁니다. 설정 파일의 <code>logging.cloudWatch.enable: true</code>가 기본값이라 같이 들어간 것입니다.</p>
<p>diff를 확인하고 Approve 단계를 승인했습니다. 저는 CLI로 승인했는데, Console에서 &#39;검토&#39; 버튼을 눌러도 됩니다.</p>
<pre><code class="language-bash">TOKEN=$(aws codepipeline get-pipeline-state --name AWSAccelerator-Pipeline \
  --query &#39;stageStates[?stageName==`Review`].actionStates[] | [?actionName==`Approve`].latestExecution.token | [0]&#39; --output text)
aws codepipeline put-approval-result --pipeline-name AWSAccelerator-Pipeline \
  --stage-name Review --action-name Approve --token $TOKEN \
  --result summary=&quot;security-config 변경 확인&quot;,status=Approved</code></pre>
<p>첫 번째 실행은 10시 6분에 시작해서 10시 56분에 끝났습니다. 50분 정도 걸렸는데, 그중 10분은 아래 5-1에서 다룰 문제 때문에 Organization 단계에서 멈춰 있던 시간입니다.</p>
<table>
<thead>
<tr>
<th>단계</th>
<th>걸린 시간</th>
<th>비고</th>
</tr>
</thead>
<tbody><tr>
<td>Source ~ Review</td>
<td>약 13분</td>
<td>Review에서 diff 확인 후 승인</td>
</tr>
<tr>
<td>Logging</td>
<td>약 6분</td>
<td></td>
</tr>
<tr>
<td>Organization</td>
<td>약 13분</td>
<td>5-1 문제로 10분 재시도</td>
</tr>
<tr>
<td>SecurityAudit</td>
<td>약 3분</td>
<td>멤버 계정 추가</td>
</tr>
<tr>
<td>Deploy</td>
<td>약 16분</td>
<td>Security_Resources가 7분으로 제일 김</td>
</tr>
</tbody></table>
<hr>
<h2 id="4-결과-확인">4. 결과 확인</h2>
<h3 id="guardduty">GuardDuty</h3>
<p>배포가 끝나고 Audit 계정에서 GuardDuty 멤버 목록을 조회하면 나머지 6개 계정이 전부 <code>Enabled</code>로 들어와 있습니다.</p>
<pre><code class="language-bash">D=$(aws guardduty list-detectors --query &#39;DetectorIds[0]&#39; --output text)
aws guardduty list-members --detector-id $D \
  --query &#39;Members[].[AccountId,RelationshipStatus]&#39; --output text</code></pre>
<pre><code class="language-text">111122223333    Enabled
111122223333    Enabled
111122223333    Enabled
111122223333    Enabled
111122223333    Enabled
111122223333    Enabled</code></pre>
<p>Console에서 보면 이렇습니다. 위쪽에 &quot;신규 및 기존 계정에 대해 자동 활성화&quot;가 켜져 있어서, 나중에 계정을 새로 만들어도 자동으로 멤버가 됩니다. 보호 플랜이 5/7로 나오는 건 7개 보호 플랜 중 위에서 켠 5개만 켜져 있고, Runtime Monitoring과 S3용 Malware Protection은 켜지 않았기 때문입니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/c117bd00-7586-41cb-8e67-e4f1603d8be1/image.png" alt="Audit 계정 GuardDuty 멤버 계정 목록"></p>
<p>앞에서 말한 것처럼 이 계정들은 GuardDuty가 원래 따로 켜져 있었습니다. Detector 생성일을 보면 6월 그대로라서, LZA가 기존 Detector를 지우고 새로 만들지는 않았고 이미 있는 Detector를 Audit 계정의 멤버로 묶은 것을 알 수 있습니다. 이전에는 GuardDuty 결과를 보려면 계정마다 로그인해야 했는데, 이제 Audit 계정 하나에서 다 보입니다.</p>
<h3 id="security-hub">Security Hub</h3>
<p>Security Hub도 Audit 계정에서 멤버 6개가 전부 <code>Enabled</code>입니다.</p>
<pre><code class="language-bash">aws securityhub list-members --query &#39;Members[].[AccountId,MemberStatus]&#39; --output text</code></pre>
<pre><code class="language-text">111122223333    Enabled
111122223333    Enabled
111122223333    Enabled
111122223333    Enabled
111122223333    Enabled
111122223333    Enabled</code></pre>
<p>Security Hub는 보안 점수가 바로 나오지 않습니다. 표준을 켜고 처음 점수가 나올 때까지 1시간 정도 기다려야 했고, 그 사이 Console에는 &quot;The security score is still being generated&quot;만 떠 있었습니다. 아래 5-2에서 다룰 CIS 표준을 끈 뒤에 다시 들어가 보니 FSBP 점수가 51%로 나왔습니다. Control 57개 중 29개 통과, 28개 실패입니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/210cf7ad-6485-480c-91dd-2df0a5f51cf5/image.png" alt="Audit 계정 Security Hub 보안 표준 점수"></p>
<p>심각도가 CRITICAL, HIGH인 실패 항목만 골라 보면 이렇습니다. Audit 계정에서 us-east-1 기준으로, 점수를 캡처하고 1시간쯤 뒤에 조회한 결과입니다.</p>
<pre><code class="language-bash">aws securityhub get-findings --max-items 1000 \
  --filters &#39;{&quot;RecordState&quot;:[{&quot;Value&quot;:&quot;ACTIVE&quot;,&quot;Comparison&quot;:&quot;EQUALS&quot;}],&quot;ComplianceStatus&quot;:[{&quot;Value&quot;:&quot;FAILED&quot;,&quot;Comparison&quot;:&quot;EQUALS&quot;}],&quot;SeverityLabel&quot;:[{&quot;Value&quot;:&quot;CRITICAL&quot;,&quot;Comparison&quot;:&quot;EQUALS&quot;},{&quot;Value&quot;:&quot;HIGH&quot;,&quot;Comparison&quot;:&quot;EQUALS&quot;}]}&#39; \
  --query &#39;Findings[].[Severity.Label,Compliance.SecurityControlId]&#39; --output text | sort | uniq -c | sort -rn</code></pre>
<pre><code class="language-text">   5 HIGH    Inspector.4
   5 HIGH    Inspector.3
   5 HIGH    Inspector.2
   5 HIGH    Inspector.1
   5 CRITICAL    SSM.7
   2 HIGH    GuardDuty.7
   2 HIGH    GuardDuty.11
   1 HIGH    EC2.182
   1 CRITICAL    Config.1</code></pre>
<ul>
<li><code>Inspector.1~4</code>는 Amazon Inspector를 켜지 않아서 나온 것입니다. LZA에는 Inspector 설정이 없어서 따로 켜야 합니다.</li>
<li><code>SSM.7</code>은 SSM 문서의 공개 공유 차단 설정입니다. 계정마다 한 번만 켜면 되는 설정이라 바로 고칠 수 있는 항목입니다.</li>
<li><code>GuardDuty.7</code>, <code>GuardDuty.11</code>은 위에서 켜지 않은 Runtime Monitoring입니다. Security Hub가 GuardDuty 설정까지 같이 검사한다는 걸 여기서 알 수 있습니다.</li>
<li><code>EC2.182</code>는 EBS Snapshot 공개 차단 설정입니다.</li>
<li><code>Config.1</code>은 관리 계정에서 나왔습니다. 이유는 &quot;The AWS Config recorder is using a custom IAM role instead of the AWS Config service-linked role.&quot;입니다. 2번에서 본 것처럼 관리 계정의 Config Recorder는 LZA가 만든 것이라, LZA가 쓰는 IAM Role이 그대로 걸린 것입니다.</li>
</ul>
<p>같은 Control이 5건씩 나오는 건 계정 5개에서 하나씩 나왔기 때문입니다. 나머지 2개 계정은 이 시점에 아직 검사가 끝나지 않았습니다. 이번 글에서는 켜는 데까지만 하고, 이 항목들은 하나씩 고쳐 나갈 생각입니다.</p>
<hr>
<h2 id="5-겪은-문제들">5. 겪은 문제들</h2>
<h3 id="5-1-guardduty-위임-관리자-지정이-listroots-권한-오류로-멈춤">5-1. GuardDuty 위임 관리자 지정이 ListRoots 권한 오류로 멈춤</h3>
<p>Pipeline이 Organization 단계에서 한참 동안 넘어가지 않았습니다. CloudFormation Event를 보니 <code>AWSAccelerator-OrganizationsStack</code>의 <code>Custom::GuardDutyEnableOrganizationAdminAccount</code>가 계속 <code>CREATE_IN_PROGRESS</code>였고, 이 Custom Resource의 Lambda 로그에는 같은 오류가 반복되고 있었습니다.</p>
<pre><code class="language-text">INFO    BadRequestException: The request failed because you do not have the organizations:ListRoots permission.
  ...
  Type: &#39;AccessDeniedException&#39;,</code></pre>
<p>Audit 계정을 GuardDuty 위임 관리자로 지정하는 Lambda가 <code>organizations:ListRoots</code>를 호출하는데, LZA가 만든 이 Lambda의 Role에 그 권한이 빠져 있습니다. 실패로 끝나지 않고 계속 재시도만 해서, 언제까지 기다려야 할지 알 수 없는 상태였습니다.</p>
<p>찾아보니 LZA GitHub에 이미 이슈가 올라와 있었습니다. <a href="https://github.com/awslabs/landing-zone-accelerator-on-aws/issues/1232">issue #1232</a>이고, 제가 쓰는 v1.15.5뿐 아니라 최신 버전에서도 같은 문제가 난다고 합니다. 이슈에 나온 방법대로 해당 Lambda Role에 권한을 직접 추가했습니다. 제 환경은 Region이 2개라서 Role도 2개였습니다.</p>
<pre><code class="language-bash">cat &gt; listroots-policy.json &lt;&lt;&#39;EOF&#39;
{&quot;Version&quot;:&quot;2012-10-17&quot;,&quot;Statement&quot;:[{&quot;Sid&quot;:&quot;AllowOrgListRoots&quot;,&quot;Effect&quot;:&quot;Allow&quot;,&quot;Action&quot;:[&quot;organizations:ListRoots&quot;,&quot;organizations:DescribeOrganization&quot;],&quot;Resource&quot;:&quot;*&quot;}]}
EOF
for r in $(aws iam list-roles --query &quot;Roles[?contains(RoleName,&#39;CustomGuardDutyEnableOrga&#39;)].RoleName&quot; --output text); do
  aws iam put-role-policy --role-name $r --policy-name LzaIssue1232ListRoots \
    --policy-document file://listroots-policy.json
done</code></pre>
<p>권한을 넣자마자 다음 재시도에서 바로 <code>CREATE_COMPLETE</code>가 됐고, 나머지 단계는 문제없이 끝났습니다. 로그를 보면 첫 오류가 10시 26분, 마지막 오류가 10시 36분이라 10분 정도 재시도한 셈입니다.</p>
<p>다만 이건 설정 파일 밖에서 IAM을 손으로 고친 것입니다. 이 시리즈에서 계속 말한 것처럼 LZA 밖에서 바꾼 건 나중에 어긋날 수 있으니, LZA를 이 문제가 고쳐진 버전으로 올리고 나면 이 인라인 정책은 지울 생각입니다.</p>
<h3 id="5-2-설정하지-않은-cis-표준까지-켜짐">5-2. 설정하지 않은 CIS 표준까지 켜짐</h3>
<p>배포가 끝나고 Security Hub Console을 열어 보니, 설정 파일에는 FSBP 하나만 적었는데 CIS AWS Foundations Benchmark v1.2.0까지 켜져 있었습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/2f38ac08-b85c-46ef-bbbb-e531b915c637/image.png" alt="CIS v1.2.0이 같이 켜진 보안 표준 위젯"></p>
<p>CLI로 봐도 마찬가지입니다. Audit 계정뿐 아니라 다른 계정들도 똑같았습니다.</p>
<pre><code class="language-bash">aws securityhub get-enabled-standards \
  --query &#39;StandardsSubscriptions[].[StandardsArn,StandardsStatus]&#39; --output text</code></pre>
<pre><code class="language-text">arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0    READY
arn:aws:securityhub:us-east-1::standards/aws-foundational-security-best-practices/v/1.0.0    READY</code></pre>
<p>원인은 Organization 단위 자동 활성화 설정이었습니다. Audit 계정에서 조회해 보면 <code>AutoEnableStandards</code>가 <code>DEFAULT</code>로 되어 있습니다.</p>
<pre><code class="language-bash">aws securityhub describe-organization-configuration</code></pre>
<pre><code class="language-json">{
    &quot;AutoEnable&quot;: true,
    &quot;MemberAccountLimitReached&quot;: false,
    &quot;AutoEnableStandards&quot;: &quot;DEFAULT&quot;,
    &quot;OrganizationConfiguration&quot;: {
        &quot;ConfigurationType&quot;: &quot;LOCAL&quot;
    }
}</code></pre>
<p><code>DEFAULT</code>는 멤버 계정에 Security Hub가 켜질 때 AWS가 정한 기본 표준을 같이 켜라는 뜻이고, 여기에 FSBP와 CIS v1.2.0이 들어 있습니다. LZA 소스를 보면 멤버를 추가하는 Lambda가 이 값을 <code>DEFAULT</code>로 넣고, 그다음에 표준을 맞추는 Lambda는 설정 파일에 <code>enable: false</code>로 적힌 표준만 끕니다. 그래서 설정 파일에 아예 안 적은 CIS v1.2.0은 그대로 남습니다.</p>
<p>해결은 간단했습니다. 끄고 싶은 표준을 <code>enable: false</code>로 명시하면 됩니다.</p>
<pre><code class="language-diff">     standards:
       - name: AWS Foundational Security Best Practices v1.0.0
         enable: true
         controlsToDisable: []
+      - name: CIS AWS Foundations Benchmark v1.2.0
+        enable: false
+        controlsToDisable: []</code></pre>
<p>Pipeline을 한 번 더 돌렸습니다. Review 단계 diff에 계정, Region마다 표준 목록이 바뀌는 게 그대로 나옵니다.</p>
<pre><code class="language-text">[~] Custom::SecurityHubBatchEnableStandards SecurityHubStandards294083BB
 └─ [~] standards
     └─ @@ -3,5 +3,10 @@
        [ ]     &quot;name&quot;: &quot;AWS Foundational Security Best Practices v1.0.0&quot;,
        [ ]     &quot;enable&quot;: true,
        [ ]     &quot;controlsToDisable&quot;: []
        [+]   },
        [+]   {
        [+]     &quot;name&quot;: &quot;CIS AWS Foundations Benchmark v1.2.0&quot;,
        [+]     &quot;enable&quot;: false,
        [+]     &quot;controlsToDisable&quot;: []
        [ ]   }
        [ ] ]</code></pre>
<p>Deploy 단계의 Security가 끝난 뒤 다시 조회하니 7개 계정, 2개 Region 모두 FSBP만 남았습니다.</p>
<pre><code class="language-text">arn:aws:securityhub:us-east-1::standards/aws-foundational-security-best-practices/v/1.0.0    READY</code></pre>
<p>Security Hub는 보안 검사 횟수만큼 비용이 나와서, 표준 하나가 더 켜져 있으면 그만큼 비용이 늘어납니다. CIS를 쓸 생각이라면 v1.2.0보다는 최신 버전(v3.0.0, v5.0.0)을 명시해서 켜는 게 낫습니다. Security Hub를 LZA로 켤 때는 쓰지 않을 기본 표준을 <code>enable: false</code>로 같이 적어 두는 걸 추천합니다.</p>
<h2 id="6-identity-center---iam-configyaml">6. Identity Center - iam-config.yaml</h2>
<p><code>iam-config.yaml</code>은 IAM Role, Group, User, Policy와 Identity Center를 관리하는 파일입니다. 설치 직후에는 전부 비어 있습니다.</p>
<pre><code class="language-yaml">providers: []
policySets: []
roleSets: []
groupSets: []
userSets: []</code></pre>
<p>저는 IAM User나 Role을 이 파일로 만들 일이 아직 없어서, Identity Center 부분만 추가했습니다.</p>
<pre><code class="language-yaml">identityCenter:
  name: IdentityCenter
  delegatedAdminAccount: Audit
  identityCenterPermissionSets:
    - name: SeanAdminAccess
      policies:
        awsManaged:
          - arn:aws:iam::aws:policy/AdministratorAccess
  identityCenterAssignments:
    - name: AWSAdmin-AdministratorAccess-Root
      permissionSetName: SeanAdminAccess
      principalType: GROUP
      principalId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
      deploymentTargets:
        organizationalUnits:
          - Root</code></pre>
<p>내용은 세 가지입니다.</p>
<ul>
<li>Identity Center 위임 관리자를 Audit 계정으로 둡니다.</li>
<li><code>SeanAdminAccess</code>라는 권한 세트를 만들고 AWS 관리형 <code>AdministratorAccess</code> 정책을 붙입니다.</li>
<li>Identity Center의 <code>AWSAdmin</code> Group에 이 권한 세트를 Root OU 전체로 할당합니다. <code>principalId</code>는 Group ID입니다.</li>
</ul>
<p><code>deploymentTargets</code>를 OU로 주면 그 OU 아래 계정 전부에 할당됩니다. 나중에 계정이 늘어나도 Pipeline 한 번이면 새 계정에도 같은 권한이 들어갑니다.</p>
<p>실제로 들어간 상태를 보면 이렇습니다. 위임 관리자는 Audit 계정입니다.</p>
<pre><code class="language-bash">aws organizations list-delegated-administrators --service-principal sso.amazonaws.com \
  --query &#39;DelegatedAdministrators[].[Name,DelegationEnabledDate]&#39; --output text</code></pre>
<pre><code class="language-text">seanson-audit    2026-06-23T11:14:50.826000+09:00</code></pre>
<p>권한 세트 목록을 보면 LZA가 만든 건 <code>SeanAdminAccess</code> 하나이고, 나머지 6개는 6월 18일 Control Tower를 설치할 때 Control Tower가 만든 것입니다.</p>
<pre><code class="language-bash">IA=$(aws sso-admin list-instances --query &#39;Instances[0].InstanceArn&#39; --output text)
for p in $(aws sso-admin list-permission-sets --instance-arn $IA --query PermissionSets --output text); do
  aws sso-admin describe-permission-set --instance-arn $IA --permission-set-arn $p \
    --query &#39;PermissionSet.[Name,CreatedDate]&#39; --output text
done</code></pre>
<pre><code class="language-text">SeanAdminAccess    2026-06-23T16:51:21.319000+09:00
AWSServiceCatalogEndUserAccess    2026-06-18T17:58:02.703000+09:00
AWSPowerUserAccess    2026-06-18T17:58:03.147000+09:00
AWSOrganizationsFullAccess    2026-06-18T17:58:03.501000+09:00
AWSServiceCatalogAdminFullAccess    2026-06-18T17:58:02.946000+09:00
AWSReadOnlyAccess    2026-06-18T17:58:03.344000+09:00
AWSAdministratorAccess    2026-06-18T17:58:02.459000+09:00</code></pre>
<p>처음에는 권한 세트 이름을 <code>AWSAdministratorAccess</code>로 했다가 Control Tower가 만든 것과 이름이 겹쳐서 배포가 실패했습니다. 그 얘기는 <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-2-OU-%EA%B3%84%EC%A0%95-SCP%EB%A5%BC-%EC%BD%94%EB%93%9C%EB%A1%9C-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0">2편의 6-3</a>에 적어 뒀습니다. 지금 이 글의 CLI도 이 <code>SeanAdminAccess</code> 권한 세트로 로그인해서 실행하고 있습니다.</p>
<hr>
<h2 id="시리즈를-마치며">시리즈를 마치며</h2>
<p>1편을 올리고 나서 이번 편까지 오는 데 시간이 꽤 걸렸습니다. 마지막이니 시리즈 전체를 한 번 정리해 보겠습니다.</p>
<h3 id="시리즈-목차">시리즈 목차</h3>
<table>
<thead>
<tr>
<th>편</th>
<th>내용</th>
<th>다룬 설정 파일</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95">1편</a></td>
<td>LZA 설치, Stack / CodePipeline 배포</td>
<td>-</td>
</tr>
<tr>
<td><a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-2-OU-%EA%B3%84%EC%A0%95-SCP%EB%A5%BC-%EC%BD%94%EB%93%9C%EB%A1%9C-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0">2편</a></td>
<td>OU, 계정, SCP</td>
<td>organization-config, accounts-config</td>
</tr>
<tr>
<td><a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-3-Transit-Gateway-VPC-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EA%B5%AC%EC%84%B1">3편</a></td>
<td>IPAM, Transit Gateway, VPC</td>
<td>network-config</td>
</tr>
<tr>
<td>4편 (이 글)</td>
<td>보안 Service, Identity Center</td>
<td>security-config, iam-config</td>
</tr>
</tbody></table>
<p><code>global-config.yaml</code>은 따로 한 편을 쓰지는 않았지만, 2편에서 CloudTrail 설정을, 3편에서 <code>enabledRegions</code>에서 Region 뺀 얘기를 다뤘습니다.</p>
<h3 id="실제로-든-비용">실제로 든 비용</h3>
<p>LZA를 쓰면 얼마나 나오는지 궁금해하시는 분이 많을 것 같아서 Cost Explorer에서 뽑아 봤습니다. 이 Organization에는 LZA와 상관없는 Workload도 같이 돌고 있어서, LZA가 기본으로 깔아 두는 Service만 골랐습니다. Network 비용은 <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-3-Transit-Gateway-VPC-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EA%B5%AC%EC%84%B1">3편</a>에서 따로 다뤘으니 여기서는 뺐습니다.</p>
<table>
<thead>
<tr>
<th>Service</th>
<th>7월</th>
<th>8월</th>
<th>9월</th>
<th>비고</th>
</tr>
</thead>
<tbody><tr>
<td>KMS</td>
<td>$99.02</td>
<td>$87.59</td>
<td>$70.57</td>
<td>LZA CMK 67개</td>
</tr>
<tr>
<td>CloudTrail</td>
<td>$96.52</td>
<td>$73.31</td>
<td>$18.27</td>
<td>2편에서 중복 기록 정리</td>
</tr>
<tr>
<td>Config</td>
<td>$13.29</td>
<td>$17.64</td>
<td>$4.59</td>
<td></td>
</tr>
<tr>
<td>CodeBuild</td>
<td>$7.46</td>
<td>$3.60</td>
<td>$0</td>
<td>Pipeline 실행할 때만</td>
</tr>
<tr>
<td>CodePipeline</td>
<td>$0.76</td>
<td>$0.30</td>
<td>$0</td>
<td></td>
</tr>
<tr>
<td>합계</td>
<td>$217.05</td>
<td>$182.44</td>
<td>$93.43</td>
<td></td>
</tr>
</tbody></table>
<p>Organization 전체 금액이라 KMS, CloudTrail에는 LZA 말고 다른 Workload 몫도 조금 섞여 있습니다. GuardDuty는 9월에 $48.74가 나왔는데, 앞에서 말한 것처럼 LZA와 상관없이 원래 켜져 있던 것이라 표에서 뺐습니다. Security Hub는 이번에 켠 거라 아직 30일 무료 체험 기간이고, 체험이 끝나면 계정과 Region마다 보안 검사 횟수만큼 비용이 붙습니다. 무료 체험 동안 Security Hub Console의 사용량 메뉴에서 예상 비용을 보여 주니, 그걸 보고 계속 켜 둘지 정하시면 됩니다.</p>
<p>제일 크게 나가는 건 KMS입니다. LZA는 계정마다, Region마다 CloudWatch Logs, Lambda, S3, SQS용 CMK를 따로 만듭니다. 관리 계정과 Audit, LogArchive 계정에는 몇 개 더 만듭니다. 제 환경은 계정 7개, Region 2개라서 <code>alias/accelerator/</code>로 시작하는 키가 67개였고, CMK는 개당 월 $1이라 이것만 월 $67 정도입니다. 실제로 9월 KMS 비용이 $70.57이었습니다. 계정이나 Region을 늘릴 때마다 이 비용이 같이 늘어난다는 걸 알고 시작하시는 게 좋습니다.</p>
<p>CloudTrail은 2편에서 정리한 대로 관리 이벤트 중복 기록을 끈 8월 이후로 많이 줄었고, CodeBuild는 Pipeline을 돌릴 때만 나옵니다. 9월에는 Pipeline을 한 번도 안 돌려서 0이었습니다.</p>
<h3 id="lza가-맞는-경우-과한-경우">LZA가 맞는 경우, 과한 경우</h3>
<p>몇 달 써 보고 든 생각입니다.</p>
<p>맞는 경우는 이렇습니다.</p>
<ul>
<li>계정이 이미 여러 개이고 앞으로 더 늘어날 때. OU, 계정, SCP, 권한 세트를 설정 파일 한 곳에서 관리할 수 있는 게 제일 큰 장점이었습니다.</li>
<li>보안 기준을 모든 계정에 똑같이 깔아야 할 때. 이번 편의 GuardDuty, Security Hub처럼 한 줄 바꾸고 Pipeline을 돌리면 모든 계정에 들어갑니다.</li>
<li>변경 전에 검토 단계가 필요한 조직. Review 단계에서 diff를 보고 승인하는 흐름은 2편에서도, 이번 편에서도 쓸모가 있었습니다.</li>
</ul>
<p>과한 경우는 이렇습니다.</p>
<ul>
<li>계정이 몇 개 안 되는 개인 환경. 저처럼 혼자 쓰는 환경이면 KMS 같은 고정 비용이 상대적으로 크게 느껴집니다.</li>
<li>빨리 바꾸고 빨리 확인해야 하는 작업. Pipeline 한 번에 30분 넘게 걸려서, 설정 한 줄 고치고 결과를 보는 데 시간이 꽤 듭니다.</li>
<li>설정 파일 밖에서 손으로 만지는 일이 많은 환경. 2편, 3편에서 겪은 것처럼 Console에서 직접 바꾸면 설정 파일과 실제 상태가 어긋나고, 다음 배포에서 문제가 생깁니다.</li>
</ul>
<p>정리하면 Control Tower만으로 부족해지는 시점, 그러니까 계정이 늘고 공통 설정을 코드로 관리하고 싶어질 때 LZA를 얹는 게 맞다고 생각합니다.</p>
<p>여기까지 읽어 주셔서 감사합니다. 궁금한 점이나 틀린 내용이 있으면 댓글로 알려 주세요.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 Amazon Bedrock으로 나만의 AI 어시스턴트 만들기 (4) - iPhone App 마무리: 설정 화면, 실기기, Markdown]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-4-iPhone-App-%EB%A7%88%EB%AC%B4%EB%A6%AC-%EC%84%A4%EC%A0%95-%ED%99%94%EB%A9%B4-%EC%8B%A4%EA%B8%B0%EA%B8%B0-Markdown</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-4-iPhone-App-%EB%A7%88%EB%AC%B4%EB%A6%AC-%EC%84%A4%EC%A0%95-%ED%99%94%EB%A9%B4-%EC%8B%A4%EA%B8%B0%EA%B8%B0-Markdown</guid>
            <pubDate>Sat, 03 Oct 2026 06:02:35 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p>3편에서 SwiftUI 채팅 화면을 만들고 Simulator에서 SSE Streaming과 Multi-turn이 되는 것까지 확인했습니다.
이번 편에서는 그 App을 실제 iPhone에 올립니다. Server 주소 설정 화면, Local Network 권한, <code>Info.plist</code> 때문에 깨진 Build, 그리고 답변에 Markdown 별표가 그대로 보이는 문제까지 정리합니다.</p>
<p>이전 편: <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-3-iPhone-App-%EB%A7%8C%EB%93%A4%EA%B8%B0-SwiftUI-SSE">3편 - iPhone App 만들기: SwiftUI + SSE</a></p>
<table>
<thead>
<tr>
<th>편</th>
<th>내용</th>
</tr>
</thead>
<tbody><tr>
<td>1편</td>
<td>Bedrock 기초: Model 선택, 첫 호출, Parameter, Token, System Prompt, Streaming</td>
</tr>
<tr>
<td>2편</td>
<td>대화 기억, 도구 호출, Prompt Caching, Extended Thinking, FastAPI + SSE Server</td>
</tr>
<tr>
<td>3편</td>
<td>iPhone App 만들기: Xcode Project, SwiftUI 채팅 화면, SSE Parsing</td>
</tr>
<tr>
<td>4편 (이 글)</td>
<td>iPhone App 마무리: Server 주소 설정, Local Network 권한, 실기기 설치, Markdown 표시</td>
</tr>
<tr>
<td>5편</td>
<td>Server를 밖으로: EC2 + ALB + HTTPS, 운영하면서 겪은 문제들</td>
</tr>
<tr>
<td>6편</td>
<td>도구를 MCP로 확장하고, 위험한 도구에는 사람 승인 단계 두기</td>
</tr>
<tr>
<td>7편</td>
<td>Token 원장과 비용 상한, Context 압축, 대화 저장(SQLite)</td>
</tr>
</tbody></table>
<p>환경은 3편과 같습니다(macOS 26.5.1, Xcode 26.5, iPhone 17 Simulator iOS 26.5, Server는 us-east-2 Claude Haiku 4.5). Screenshot은 Simulator에서 찍었습니다.</p>
<hr>
<h2 id="1-설정-화면-추가하고-실기기에-올리기">1. 설정 화면 추가하고 실기기에 올리기</h2>
<p>Simulator는 <code>127.0.0.1</code>로 되지만 실제 iPhone에서 <code>127.0.0.1</code>은 폰 자기 자신입니다. 그래서 Mac의 LAN 주소(예: <code>192.168.0.10</code>)를 넣을 수 있는 화면이 필요합니다.</p>
<h3 id="1-1-settingsviewswift">1-1. <code>SettingsView.swift</code></h3>
<pre><code class="language-swift">import SwiftUI

/// 서버 주소 입력 + 연결 테스트. 주소는 @AppStorage로 저장돼 앱을 다시 켜도 남는다
struct SettingsView: View {
    @AppStorage(&quot;serverURL&quot;) private var serverURL = ChatViewModel.defaultServer
    @State private var status = &quot;&quot;
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Form {
                Section(&quot;백엔드 서버&quot;) {
                    TextField(&quot;http://192.168.0.10:8599&quot;, text: $serverURL)
                        .keyboardType(.URL)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                    Button(&quot;연결 테스트&quot;) { Task { await test() } }
                    if !status.isEmpty { Text(status).font(.footnote) }
                }
                Section {
                    Text(&quot;시뮬레이터 → http://127.0.0.1:8599\n실제 iPhone → http://&lt;Mac의 IP&gt;:8599 (같은 Wi-Fi)&quot;)
                        .font(.footnote).foregroundStyle(.secondary)
                }
            }
            .navigationTitle(&quot;설정&quot;)
            .toolbar { Button(&quot;완료&quot;) { dismiss() } }
        }
    }

    private func test() async {
        guard let url = URL(string: serverURL) else { status = &quot;❌ 주소 형식이 이상합니다&quot;; return }
        do {
            let h = try await ChatAPI(baseURL: url).health()
            status = h.ok ? &quot;✅ 연결 성공 — \(h.model)&quot; : &quot;❌ 서버 응답 이상&quot;
        } catch {
            status = &quot;❌ \(error.localizedDescription)&quot;
        }
    }
}

#Preview {
    SettingsView()
}</code></pre>
<p>이 파일의 핵심은 <code>@AppStorage(&quot;serverURL&quot;)</code> 하나입니다. <code>UserDefaults</code>에 자동으로 저장되고, App을 지우지 않는 한 남아 있습니다.
<code>ChatViewModel</code>이 같은 키를 <code>UserDefaults.standard.string(forKey: &quot;serverURL&quot;)</code>로 읽으니까 두 파일이 같은 값을 보게 됩니다.</p>
<p>&quot;연결 Test&quot; 버튼은 3편 3-2의 <code>health()</code>를 부릅니다. 성공하면 Server가 쓰는 Model ID를 보여 주게 했는데, 지금 어느 Model에 붙어 있는지 App에서 바로 보이는 게 생각보다 쓸모가 있었습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/2bcfc355-30e7-43c8-b8c0-4aae2ac08bcb/image.png" alt="설정: 연결 Test 성공. Server가 돌리는 Model ID가 보인다"></p>
<p>Server를 꺼 두고 질문을 보내면 이렇게 됩니다. 3편 3-3에서 넣은 &quot;한 글자도 못 받았으면 빈 말풍선 제거&quot;가 동작해서 내 말풍선만 남고, 아래에 빨간 한 줄이 뜹니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/9d8db786-ce95-455e-8118-015b0097d4b2/image.png" alt="Server가 꺼져 있을 때: 빈 말풍선 없이 Error 한 줄"></p>
<h3 id="1-2-mac-주소-찾기">1-2. Mac 주소 찾기</h3>
<p>실기기에서 붙을 Mac의 LAN 주소는 Terminal에서 이렇게 확인합니다(Wi-Fi가 <code>en0</code>일 때).</p>
<pre><code class="language-bash">ipconfig getifaddr en0</code></pre>
<pre><code>192.168.123.120</code></pre><p>폰과 Mac이 같은 Wi-Fi에 있어야 하고, Server는 3편 1장처럼 <code>--host 0.0.0.0</code>으로 떠 있어야 합니다.
macOS 방화벽이 켜져 있으면 처음 접속할 때 &quot;python이 들어오는 연결을 허용할까요&quot; 팝업이 뜨는데, 허용하면 됩니다.</p>
<h3 id="1-3-infoplist에-local-network-권한-추가">1-3. <code>Info.plist</code>에 Local Network 권한 추가</h3>
<p>iOS 14부터는 App이 같은 Wi-Fi의 다른 기기(여기서는 Mac)에 붙으려고 하면 시스템이 Local Network 권한을 묻습니다. 이 팝업에 들어갈 설명 문구를 <code>Info.plist</code>에 넣어야 합니다.</p>
<p>Xcode에서 Project, Target <code>SeanChat</code>, Info 탭으로 들어가서 표 위를 우클릭하고 Add Row로 <code>Privacy - Local Network Usage Description</code>을 고른 뒤 문구를 넣으면 됩니다. 결과 파일은 이렇습니다.</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;
&lt;plist version=&quot;1.0&quot;&gt;
&lt;dict&gt;
    &lt;key&gt;NSLocalNetworkUsageDescription&lt;/key&gt;
    &lt;string&gt;Mac에서 실행 중인 SeanChat 백엔드(포트 8599)에 연결하기 위해 로컬 네트워크 접근이 필요합니다.&lt;/string&gt;
    &lt;key&gt;NSAppTransportSecurity&lt;/key&gt;
    &lt;dict&gt;
        &lt;key&gt;NSAllowsLocalNetworking&lt;/key&gt;
        &lt;true/&gt;
    &lt;/dict&gt;
&lt;/dict&gt;
&lt;/plist&gt;</code></pre>
<p><code>NSAppTransportSecurity</code>의 <code>NSAllowsLocalNetworking</code>도 같이 넣었습니다.
iOS는 기본적으로 <code>http://</code>(TLS 없음) 연결을 막는데(ATS), 이 키는 IP 주소, <code>.local</code>, Host 이름만 있는 주소에 한해서 그 제한을 풀어 줍니다.
Apple 문서에 따르면 iOS 16까지는 IP 주소 접속이 기본으로 허용됐지만 iOS 17부터는 이 키가 있어야 합니다.
3편의 Simulator Screenshot은 이 키 없이 <code>127.0.0.1</code>로 찍은 거라 Loopback은 예외인 것 같은데, 실기기에서 <code>192.168.x.x</code>로 붙을 때는 넣어 두는 게 안전합니다.
공인 Domain에 <code>http://</code>로 붙는 건 이 키로도 안 풀립니다. 그때는 HTTPS를 붙이는 게 답이고, 5편에서 EC2 + ALB로 그렇게 합니다.</p>
<p>여기서 한 번 막혔습니다. <code>Multiple commands produce &#39;…/SeanChat.app/Info.plist&#39;</code> Error입니다.
저는 위 XML을 손으로 써서 <code>SeanChat</code> 폴더에 넣고, Build 설정 <code>INFOPLIST_FILE</code>을 그 파일로 지정했습니다. 그랬더니 이 Error로 Build가 깨졌습니다.
3편 2장 끝에서 말한 폴더 자동 동기화 때문입니다. 폴더 안의 <code>Info.plist</code>가 Resource로도 복사되고 Info.plist로도 처리돼서 같은 산출물을 두 번 만들려고 한 겁니다.</p>
<p>Xcode Info 탭에서 키를 추가하는 원래 방법으로 하면 Xcode가 파일 등록을 알아서 처리해서 보통은 이 문제를 안 만납니다.
저처럼 손으로 만들었다면 왼쪽에서 <code>Info.plist</code>를 선택하고, 오른쪽 File Inspector의 Target Membership에서 <code>SeanChat</code> 체크를 끄면 됩니다. 그러면 Resource 복사에서 빠지고 <code>INFOPLIST_FILE</code>로만 쓰입니다. 저는 이렇게 해서 Build가 다시 됐습니다.</p>
<h3 id="1-4-실기기에-올리기">1-4. 실기기에 올리기</h3>
<p>iPhone을 USB로 연결하고(처음엔 폰에서 &quot;이 컴퓨터를 신뢰&quot; 확인), Xcode 상단 기기 목록에서 내 iPhone을 고른 다음 ▶를 누릅니다.</p>
<ol>
<li>Signing: Project, Target, Signing &amp; Capabilities에서 Team을 본인 Apple ID로 고릅니다. 내 폰에서만 쓸 App이라 이걸로 충분합니다.</li>
<li>폰 쪽 설정: 첫 실행 때 &quot;신뢰하지 않는 개발자&quot; 경고가 뜨면 설정, 일반, VPN 및 기기 관리에서 본인 계정을 신뢰합니다.</li>
<li>App 안에서: 설정(톱니바퀴 버튼)에서 Server 주소를 <code>http://192.168.123.120:8599</code>처럼 Mac 주소로 바꾸고 연결 Test를 누릅니다. iOS가 Local Network 권한 팝업을 띄우면 허용합니다.</li>
</ol>
<p>여기까지 되면 소파에 앉아서 폰으로 Mac의 Bedrock Server에 질문을 던질 수 있습니다. 제 SeanChat도 딱 이 단계에서 처음으로 &quot;이거 쓸 만하다&quot;는 느낌이 들었습니다.</p>
<hr>
<h2 id="2-굵게가-그대로-보이는-문제-고치기">2. <code>**굵게**</code>가 그대로 보이는 문제 고치기</h2>
<p>며칠 쓰다 보니 바로 눈에 걸리는 게 있었습니다. Model이 목록을 만들 때 <code>**제목**</code>처럼 Markdown을 섞어 쓰는데, App은 그 별표를 그대로 보여 줍니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/7ae38ed6-614d-4c0e-8a63-d9b1a7e8d4c3/image.png" alt="왼쪽: Text(message.text): 별표가 그대로 보인다 / 오른쪽: AttributedString(markdown:) 적용 후"></p>
<p>SwiftUI의 <code>Text</code>는 문자열 리터럴일 때만 Markdown을 해석하고, 변수로 넘긴 <code>String</code>은 해석하지 않습니다. 변수를 쓰려면 <code>AttributedString(markdown:)</code>으로 한 번 감싸야 합니다.
<code>BubbleView</code>에 이 Property를 넣고 <code>Text(attributed)</code>로 바꾼 게 3편 3-4 코드에 있던 <code>attributed</code>입니다.</p>
<pre><code class="language-swift">    /// **굵게**, *기울임*, `코드` 같은 인라인 마크다운만 해석한다 (한 줄 개선)
    private var attributed: AttributedString {
        (try? AttributedString(markdown: message.text,
                               options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)))
        ?? AttributedString(message.text)
    }</code></pre>
<p>여기서는 Option <code>inlineOnlyPreservingWhitespace</code>가 중요합니다. 기본 Option(<code>.full</code>)으로 하면 Markdown Parser가 줄바꿈을 접어 버려서, Model이 나눠 준 목록이 한 덩어리로 붙어 버립니다. 이 Option은 인라인 문법(굵게, 기울임, 코드)만 해석하고 줄바꿈은 그대로 둡니다.</p>
<p>Screenshot 오른쪽을 보면 첫 줄 <code># iOS 앱 개발 초보자의 흔한 실수 3가지</code>의 헤딩(<code>#</code>)은 그대로 남아 있습니다. 인라인만 해석하니 당연한 결과입니다.
코드 Block, 표, 헤딩까지 제대로 그리려면 Markdown 렌더러가 따로 필요합니다. 제 SeanChat App은 결국 렌더러를 직접 만들었는데(코드 Block 복사 버튼, 표 가로 Scroll 등) 이번 편 범위를 넘어서 여기서 멈춥니다.
대신 Server의 System Prompt에 &quot;Markdown 헤딩은 쓰지 말고 굵게로 대신해라&quot;를 넣는 방법도 있습니다. App을 고치는 것보다 Server Prompt 한 줄이 빠르고, 이게 3편에서 말한 Thin Client 구조의 장점입니다.</p>
<hr>
<h2 id="3편·4편에서-만난-error-모음">3편·4편에서 만난 Error 모음</h2>
<h3 id="could-not-connect-to-the-server-실기기"><code>Could not connect to the server</code> (실기기)</h3>
<p>보통 셋 중 하나였습니다. 위에서부터 확인합니다.</p>
<ol>
<li>Server를 <code>--host 0.0.0.0</code> 없이 띄웠다(3편 1장). <code>lsof -iTCP:8599 -sTCP:LISTEN</code>에서 <code>*:8599</code>가 아니라 <code>127.0.0.1:8599</code>로 보이면 이 경우입니다.</li>
<li>폰과 Mac이 다른 Network에 있다(폰은 LTE, Mac은 Wi-Fi 등).</li>
<li>macOS 방화벽이 python을 막고 있다. 시스템 설정, Network, 방화벽, Option에서 python을 허용합니다.</li>
</ol>
<p>설정 화면의 연결 Test 버튼은 <code>/health</code>만 부르기 때문에, 채팅을 보내기 전에 이걸로 먼저 확인하면 원인을 빨리 좁힐 수 있습니다.</p>
<h3 id="the-internet-connection-appears-to-be-offline-실기기-wi-fi는-켜져-있는데"><code>The Internet connection appears to be offline</code> (실기기, Wi-Fi는 켜져 있는데)</h3>
<p>1번을 고쳐서 Mac에서는 <code>curl http://192.168.x.x:8599/health</code>가 200을 주는데도 폰에서만 이 Message가 나왔습니다.
Internet이 끊긴 게 아니라 iOS가 Local Network 접근을 막았을 때 URLSession이 이렇게(-1009) 포장해서 내보내는 겁니다.
설정, 개인정보 보호 및 보안, Local Network에서 App 토글을 켜면 됩니다.
그런데 그 목록에 App이 아예 없다면 iOS가 권한을 물어본 적도 없다는 뜻입니다. 제 경우 <code>Info.plist</code>에 <code>NSLocalNetworkUsageDescription</code>이 빠진 Build에서 그랬습니다. 1-3의 키를 넣고 다시 설치하면 첫 접속 때 팝업이 뜹니다.</p>
<h3 id="multiple-commands-produce-infoplist"><code>Multiple commands produce &#39;…/Info.plist&#39;</code></h3>
<p>1-3 참고. 손으로 만든 <code>Info.plist</code>가 Resource로도 복사되고 있어서입니다. File Inspector의 Target Membership 체크를 해제합니다.</p>
<h3 id="말풍선이-에서-멈추고-아무것도-안-나온다">말풍선이 &quot;…&quot;에서 멈추고 아무것도 안 나온다</h3>
<p>Server Log를 봅니다. <code>POST /chat 200</code>이 찍혔는데 App에 글자가 안 오면 대부분 Bedrock 쪽 Error입니다(Model Access 미승인, 자격증명 만료 등, 1·2편 Error 정리 참고).
3편 1장의 Server는 이걸 <code>{&quot;type&quot;: &quot;error&quot;}</code> Event로 흘려보내고, App은 빨간 한 줄로 보여 주게 되어 있습니다. 그게 안 보이면 Server가 2편의 <code>step11_server.py</code> 그대로(Error 처리 없음)인지 확인해 보세요.</p>
<h3 id="simulator에서-한글이-안-쳐진다">Simulator에서 한글이 안 쳐진다</h3>
<p>Mac 키보드로 Simulator에 한글을 치려면 Simulator 메뉴 I/O, Keyboard, Connect Hardware Keyboard가 켜져 있어야 합니다. 꺼져 있으면 화면 키보드로만 입력됩니다. 반대로 켜져 있으면 화면 키보드가 안 뜨는데, 이건 정상입니다.</p>
<h3 id="중지■를-눌렀는데-server-log에선-model이-계속-답한다">중지(■)를 눌렀는데 Server Log에선 Model이 계속 답한다</h3>
<p><code>AsyncThrowingStream</code>의 <code>onTermination</code>에서 <code>task.cancel()</code>을 안 했을 때 생깁니다(3편 3-2의 6번). App 화면만 멈추고 Socket은 살아 있어서 Token이 계속 나갑니다. Server Log로만 보이는 문제라 알아채기 어렵습니다.</p>
<h3 id="build는-되는데-observable을-못-찾는다">Build는 되는데 <code>@Observable</code>을 못 찾는다</h3>
<p>Minimum Deployments가 iOS 16 이하로 잡혀 있을 때입니다. Project, Target, General에서 Minimum Deployments를 17.0 이상으로 올립니다.</p>
<hr>
<h2 id="정리">정리</h2>
<table>
<thead>
<tr>
<th>장</th>
<th>한 것</th>
<th>파일</th>
</tr>
</thead>
<tbody><tr>
<td>3편 1~4장</td>
<td>Server 수정, Xcode Project, SSE Parsing, 채팅 화면, Simulator 확인</td>
<td><code>step12_server.py</code> <code>Message</code> <code>ChatAPI</code> <code>ChatViewModel</code> <code>ContentView</code></td>
</tr>
<tr>
<td>4편 1장</td>
<td>Server 주소 설정, Local Network 권한, 실기기</td>
<td><code>SettingsView</code> <code>Info.plist</code></td>
</tr>
<tr>
<td>4편 2장</td>
<td>인라인 Markdown 표시</td>
<td><code>ContentView</code> (<code>attributed</code>)</td>
</tr>
</tbody></table>
<p>3·4편을 하면서 기억에 남은 건 세 가지입니다.</p>
<ol>
<li>SSE는 App 쪽에서 <code>bytes(for:)</code>와 <code>.lines</code> 두 개로 끝납니다. Library가 필요 없었습니다.</li>
<li>대화 기억은 App이 들고 있습니다. Server는 상태가 없어서 아무 때나 껐다 켜도 App은 모릅니다. 2편 1장의 파이썬 리스트가 <code>[Message]</code>가 된 것뿐입니다.</li>
<li>App은 Thin하게, 판단은 Server에서 합니다. Markdown 헤딩 문제도 App을 고치는 대신 Server Prompt 한 줄로 풀 수 있었습니다. 이 구조 덕분에 App을 다시 설치하지 않고 Server만 계속 고쳐 나갈 수 있습니다.</li>
</ol>
<h2 id="다음-편-예고">다음 편 예고</h2>
<p>지금 App에는 아쉬운 점이 세 가지 있습니다. App을 끄면 대화가 사라지고, 대화가 길어질수록 매 요청의 입력 Token이 늘어나고, Server는 Mac이 잠들면 같이 잠듭니다.
5편에서는 마지막 문제부터 풀어 보겠습니다. Server를 EC2로 옮기고 ALB와 HTTPS를 붙이면서 운영 중에 겪은 문제들(재시도, Timeout, 비용)을 정리할 예정입니다.</p>
<p>이 글의 코드는 그대로 복사해서 Build되도록 파일 단위로 실었습니다. 막히는 부분이 있으면 댓글로 남겨 주세요. 저도 Swift는 이 App으로 배운 입장이라, 더 나은 방법이 있으면 배우고 싶습니다.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 Amazon Bedrock으로 나만의 AI 어시스턴트 만들기 (2) - 대화 기억, 도구 호출, SSE Server]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-2-%EB%8C%80%ED%99%94-%EA%B8%B0%EC%96%B5-%EB%8F%84%EA%B5%AC-%ED%98%B8%EC%B6%9C-SSE-Server</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-2-%EB%8C%80%ED%99%94-%EA%B8%B0%EC%96%B5-%EB%8F%84%EA%B5%AC-%ED%98%B8%EC%B6%9C-SSE-Server</guid>
            <pubDate>Sat, 03 Oct 2026 06:02:35 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p>1편에서는 Bedrock을 boto3로 처음 호출해 보고, Parameter와 Token, System Prompt, Streaming Event 구조까지 확인했습니다.
이번 편에서는 그 호출 코드를 조금씩 키워서 실제로 쓸 만한 어시스턴트 Backend까지 만들어 봅니다.</p>
<p>순서는 이렇습니다.
대화를 기억하게 만들고, 도구 호출 Loop를 붙이고, Prompt Caching으로 비용을 줄이고, Extended Thinking을 켜 본 다음, 마지막에 FastAPI + SSE Server로 감쌉니다.
여기까지 오면 Terminal에서 <code>curl</code>로 답변이 흘러나오는 걸 볼 수 있고, 3편에서 iPhone App을 이 Server에 붙입니다.</p>
<p>이전 편: <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-1-%EC%B2%AB-%ED%98%B8%EC%B6%9C%EB%B6%80%ED%84%B0-Streaming%EA%B9%8C%EC%A7%80">1편 - 첫 호출부터 Streaming까지</a></p>
<table>
<thead>
<tr>
<th>편</th>
<th>내용</th>
</tr>
</thead>
<tbody><tr>
<td>1편</td>
<td>Bedrock 기초: Model 선택, 첫 호출, Parameter, Token, System Prompt, Streaming</td>
</tr>
<tr>
<td>2편 (이 글)</td>
<td>대화 기억, 도구 호출, Prompt Caching, Extended Thinking, FastAPI + SSE Server</td>
</tr>
<tr>
<td>3편</td>
<td>iPhone App 만들기: Xcode Project, SwiftUI 채팅 화면, SSE Parsing</td>
</tr>
<tr>
<td>4편</td>
<td>iPhone App 마무리: Server 주소 설정, Local Network 권한, 실기기 설치, Markdown 표시</td>
</tr>
<tr>
<td>5편</td>
<td>Server를 밖으로: EC2 + ALB + HTTPS, 운영하면서 겪은 문제들</td>
</tr>
<tr>
<td>6편</td>
<td>도구를 MCP로 확장하고, 위험한 도구에는 사람 승인 단계 두기</td>
</tr>
<tr>
<td>7편</td>
<td>Token 원장과 비용 상한, Context 압축, 대화 저장(SQLite)</td>
</tr>
</tbody></table>
<p>환경은 1편과 같습니다. 개인 계정의 <code>us-east-2</code>, Model은 Claude Haiku 4.5(<code>us.</code> Inference Profile), 자격증명은 <code>AWS_BEARER_TOKEN_BEDROCK</code>입니다.
아래 실행 결과도 전부 2026년 9월에 실제로 돌린 출력입니다.</p>
<hr>
<h2 id="1-대화-기억시키기">1. 대화 기억시키기</h2>
<p>저는 여기서 처음으로 &quot;이건 채팅 Service가 아니라 그냥 함수구나&quot; 하고 느꼈습니다.
Bedrock은 대화를 기억해 주지 않습니다. Session 개념이 없어서 매 요청마다 지금까지의 대화 전체를 다시 보내야 합니다.</p>
<p><code>step7_chat.py</code></p>
<pre><code class="language-python">messages = []                                    # ← 이게 대화 기억의 전부다

def ask(text):
    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: text}]})
    r = runtime.converse(modelId=MODEL, system=SYSTEM, messages=messages,   # 전체를 보낸다
                         inferenceConfig={&quot;maxTokens&quot;: 300})
    reply = r[&quot;output&quot;][&quot;message&quot;]
    messages.append(reply)                       # ← 응답도 반드시 append (형식이 같아서 그대로 넣는다)
    print(f&quot;👤 {text}\n🤖 {&#39;&#39;.join(b.get(&#39;text&#39;,&#39;&#39;) for b in reply[&#39;content&#39;])}&quot;
          f&quot;   (in={r[&#39;usage&#39;][&#39;inputTokens&#39;]} out={r[&#39;usage&#39;][&#39;outputTokens&#39;]})\n&quot;)

ask(&quot;내 이름은 Sean이고 커피를 좋아해.&quot;)
ask(&quot;내 이름이 뭐라고 했지?&quot;)                     # append 안 하면 이 답을 못 한다
print(&quot;messages 길이:&quot;, len(messages))</code></pre>
<pre><code>$ python step7_chat.py
👤 내 이름은 Sean이고 커피를 좋아해.
🤖 안녕하세요 Sean님, 커피를 좋아하신다니 좋은 취향이시네요.   (in=57 out=38)

👤 내 이름이 뭐라고 했지?
🤖 당신의 이름은 Sean이라고 말씀하셨습니다.   (in=114 out=27)

messages 길이: 4  (user/assistant 교대로 쌓인다)</code></pre><p><code>messages.append(reply)</code> 한 줄을 빼고 돌려 보면 두 번째 답이 &quot;이름을 말씀하지 않으셨습니다&quot;로 바뀝니다.
한 번 직접 지워 보시는 걸 추천합니다. &quot;대화 기억&quot;이 어떻게 돌아가는지 바로 감이 옵니다.</p>
<h3 id="여기서-비용-구조가-보입니다">여기서 비용 구조가 보입니다</h3>
<p><code>in=57</code>이 <code>in=114</code>가 됐습니다. 두 번째 질문은 아홉 글자인데 입력 Token이 두 배로 늘었습니다.
이전 대화(질문과 답변)를 통째로 다시 보냈기 때문입니다.</p>
<pre><code>1턴: [Q1]                          → 입력 = Q1
2턴: [Q1, A1, Q2]                  → 입력 = Q1 + A1 + Q2
3턴: [Q1, A1, Q2, A2, Q3]          → 입력 = 지금까지 전부
...
N턴 누적 입력 토큰 ∝ N²</code></pre><p>턴이 늘어날수록 앞의 대화가 계속 다시 들어가니까, 100턴짜리 대화 하나가 짧은 대화 100개보다 훨씬 비쌉니다.
1편 4장에서 &quot;호출 한 번은 $0.0001도 안 된다&quot;고 했는데, 실제 비용은 여기서 나옵니다.</p>
<p>이 문제를 줄이는 방법이 두 가지 있는데, 하나는 이번 편에서, 하나는 7편에서 다룹니다.</p>
<table>
<thead>
<tr>
<th>방법</th>
<th>하는 일</th>
<th>어디서</th>
</tr>
</thead>
<tbody><tr>
<td>Prompt Caching</td>
<td>매번 똑같이 들어가는 앞부분(System Prompt, 도구 스펙)을 싸게</td>
<td>3장</td>
</tr>
<tr>
<td>Context 압축</td>
<td>오래된 Message를 요약 한 덩어리로 접기</td>
<td>7편</td>
</tr>
</tbody></table>
<p>지금은 <code>messages</code> 배열이 곧 대화이고, 그 배열을 내 코드가 들고 있어야 한다는 것만 기억하면 됩니다.
SeanChat에서는 이 배열을 SQLite에 Session 단위로 저장해 두고, CLI와 iPhone이 같은 Session을 이어서 봅니다.</p>
<hr>
<h2 id="2-도구-호출과-while-loop">2. 도구 호출과 while Loop</h2>
<p>개인적으로 이번 편에서 제일 재미있었던 부분입니다.
AI 어시스턴트가 파일을 읽고 시각을 알려주고 명령을 실행하는 건 사실 Model이 하는 일이 아닙니다.
Model은 &quot;이 도구를 이 인자로 불러줘&quot;라고 말만 하고, 실행은 내 코드가 합니다.
이걸 이해하고 나니 &quot;Agent&quot;라는 단어가 주던 막연한 느낌이 좀 사라졌습니다.</p>
<p>흐름은 이렇게 왕복합니다.</p>
<pre><code>[1] 내 코드 → 모델 : messages + toolConfig(도구 설명서)
[2] 모델 → 내 코드 : stopReason=&quot;tool_use&quot;, content=[{toolUse: {name, input, toolUseId}}]
[3] 내 코드        : 실제 함수 실행 (파일 읽기·API 호출·셸… 뭐든)
[4] 내 코드 → 모델 : toolResult (toolUseId로 짝을 맞춰서)
[5] 모델 → 내 코드 : stopReason=&quot;end_turn&quot; → 최종 답변
                     (또는 다시 tool_use → [3]으로. 그래서 while 루프다)</code></pre><p><code>step8_tool.py</code>는 도구 2개(현재 시각, 파일 읽기)를 붙인 Loop입니다.
먼저 도구 설명서입니다. Model은 이 JSON Schema만 보고 언제, 어떻게 부를지 정합니다.
<code>description</code>이 사실상 Prompt라서 대충 쓰면 엉뚱한 때 부르거나 안 부릅니다.</p>
<pre><code class="language-python">TOOL_CONFIG = {&quot;tools&quot;: [
    {&quot;toolSpec&quot;: {
        &quot;name&quot;: &quot;get_current_time&quot;,
        &quot;description&quot;: &quot;현재 시각을 ISO8601로 반환한다.&quot;,
        &quot;inputSchema&quot;: {&quot;json&quot;: {&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: {}, &quot;required&quot;: []}}}},
    {&quot;toolSpec&quot;: {
        &quot;name&quot;: &quot;read_file&quot;,
        &quot;description&quot;: &quot;텍스트 파일 내용을 읽어 반환한다.&quot;,
        &quot;inputSchema&quot;: {&quot;json&quot;: {
            &quot;type&quot;: &quot;object&quot;,
            &quot;properties&quot;: {&quot;path&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;파일 경로&quot;}},
            &quot;required&quot;: [&quot;path&quot;]}}}},
]}

def run_tool(name, args):                         # 실제 실행은 내 코드가 한다
    if name == &quot;get_current_time&quot;:
        return datetime.datetime.now().astimezone().isoformat(timespec=&quot;seconds&quot;)
    if name == &quot;read_file&quot;:
        return pathlib.Path(args[&quot;path&quot;]).read_text()[:500]
    return f&quot;unknown tool: {name}&quot;</code></pre>
<p>다음은 Loop입니다.</p>
<pre><code class="language-python">messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;지금 몇 시야? 그리고 ./hello.txt 내용도 읽어줘.&quot;}]}]

for round_no in range(1, 6):                      # 무한루프 방지 상한은 필수
    r = runtime.converse(modelId=MODEL, messages=messages,
                         toolConfig=TOOL_CONFIG, inferenceConfig={&quot;maxTokens&quot;: 500})
    msg = r[&quot;output&quot;][&quot;message&quot;]
    messages.append(msg)                          # ① 모델 응답(toolUse 포함)을 그대로 append
    print(f&quot;── round {round_no}  stopReason={r[&#39;stopReason&#39;]}&quot;)

    if r[&quot;stopReason&quot;] != &quot;tool_use&quot;:             # 도구 요청이 아니면 최종 답변
        print(f&quot;\n🤖 최종답변: {&#39;&#39;.join(b.get(&#39;text&#39;,&#39;&#39;) for b in msg[&#39;content&#39;])}&quot;)
        break

    results = []
    for block in msg[&quot;content&quot;]:
        if &quot;toolUse&quot; not in block:
            continue
        tu = block[&quot;toolUse&quot;]
        out = run_tool(tu[&quot;name&quot;], tu.get(&quot;input&quot;, {}))
        print(f&quot;   🔧 {tu[&#39;name&#39;]}({json.dumps(tu.get(&#39;input&#39;, {}), ensure_ascii=False)}) → {out}&quot;)
        results.append({&quot;toolResult&quot;: {           # ② 결과는 toolUseId로 짝 맞춰서
            &quot;toolUseId&quot;: tu[&quot;toolUseId&quot;],
            &quot;content&quot;: [{&quot;text&quot;: out}]}})
    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: results})    # ③ user 역할로 되돌린다</code></pre>
<p>실행해 보면 첫 라운드에서 도구 2개를 한꺼번에 부르고, 다음 라운드에서 답을 냅니다.</p>
<pre><code>$ python step8_tool.py
── round 1  stopReason=tool_use
   🔧 get_current_time({}) → 2026-09-20T22:59:49+09:00
   🔧 read_file({&quot;path&quot;: &quot;./hello.txt&quot;}) → 안녕하세요! 이 파일은 Bedrock 도구 호출 테스트용입니다.

── round 2  stopReason=end_turn

🤖 최종답변: 현재 시간과 파일 내용을 알려드리겠습니다.

**현재 시각:** 2026년 9월 20일 22시 59분 49초 (한국 시간, UTC+9)

**./hello.txt 파일 내용:**
안녕하세요! 이 파일은 Bedrock 도구 호출 테스트용입니다.</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/6b6c692d-1a88-4bcf-9795-c2f1d5720d4c/image.png" alt="도구 호출 Loop"></p>
<p>이 30줄 정도가 SeanChat Backend의 뼈대입니다. 지금은 도구가 수십 개로 늘었고 <code>run_tool</code>이 MCP Server 호출로 바뀌었지만 Loop 모양은 그대로입니다.</p>
<h3 id="처음에-헷갈렸던-규칙들">처음에 헷갈렸던 규칙들</h3>
<ol>
<li><code>toolUseId</code> 짝을 정확히 맞춰야 합니다. 하나라도 빠지면 <code>ValidationException</code>이 납니다.</li>
<li>Model 응답 Message는 그대로 append합니다. <code>toolUse</code> Block을 빼고 Text만 추려 넣으면 다음 호출에서 짝이 안 맞는다고 거부됩니다.</li>
<li><code>toolResult</code>는 <code>role: &quot;user&quot;</code>로 보냅니다. 처음엔 &quot;도구 결과인데 왜 user지?&quot; 싶었는데, Model 입장에서는 바깥에서 들어온 입력이라 user 턴으로 취급합니다. 그냥 규격입니다.</li>
<li>한 라운드에 도구가 여러 개 올 수 있습니다(위 출력처럼). 이때 결과는 Message 하나에 모아서 보냅니다. 따로따로 보내면 2번 규칙에 걸립니다.</li>
<li>라운드 상한은 꼭 둡니다. Model이 같은 도구를 계속 부르는 Loop에 빠지면 요금이 그대로 나갑니다. 위 코드에서 <code>range(1, 6)</code>으로 5번까지만 돌게 한 이유입니다.</li>
</ol>
<h3 id="놓치기-쉬운-부분-빈-도구-배열">놓치기 쉬운 부분: 빈 도구 배열</h3>
<p>권한이나 설정에 따라 도구 목록을 걸러내다 보면 목록이 빈 배열이 될 때가 있는데, 이건 거부됩니다.</p>
<pre><code>ParamValidationError: Invalid length for parameter toolConfig.tools,
value: 0, valid min length: 1</code></pre><p>목록이 비면 <code>toolConfig</code> 키를 아예 빼야 합니다. <code>{&quot;tools&quot;: []}</code>로 보내면 안 됩니다.
저는 <code>kwargs = {...}; if tools: kwargs[&quot;toolConfig&quot;] = {...}</code>처럼 조건부로 넣고 있습니다.</p>
<hr>
<h2 id="3-prompt-caching">3. Prompt Caching</h2>
<p>1장에서 본 것처럼 System Prompt와 도구 설명서는 매 요청에 똑같이 들어갑니다.
똑같은 걸 매번 정가로 내는 대신 Cache해 둘 수 있습니다. <code>system</code> 배열 끝에 <code>cachePoint</code> Block 하나만 넣으면 됩니다.</p>
<p><code>step9_cache.py</code></p>
<pre><code class="language-python"># 캐시는 최소 토큰 수를 넘어야 동작한다(아래에서 실측). 긴 시스템 프롬프트를 흉내낸다.
BIG_SYSTEM = (&quot;너는 사내 인프라 규칙을 따르는 어시스턴트다.\n&quot;
              + &quot;\n&quot;.join(f&quot;규칙 {i}: 리전은 us-east-2를 사용하고, 태그 Owner/Env/CostCenter를 &quot;
                          f&quot;반드시 붙이며, 퍼블릭 S3 버킷은 금지한다.&quot; for i in range(1, 121)))

def call(q, cache: bool):
    system = [{&quot;text&quot;: BIG_SYSTEM}]
    if cache:
        system.append({&quot;cachePoint&quot;: {&quot;type&quot;: &quot;default&quot;}})   # ← 이 한 줄이 전부
    r = runtime.converse(modelId=MODEL, system=system,
                         messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: q}]}],
                         inferenceConfig={&quot;maxTokens&quot;: 100})
    u = r[&quot;usage&quot;]
    print(f&quot;cache={&#39;ON &#39; if cache else &#39;OFF&#39;} | input={u[&#39;inputTokens&#39;]:&gt;5} &quot;
          f&quot;write={u[&#39;cacheWriteInputTokens&#39;]:&gt;5} read={u[&#39;cacheReadInputTokens&#39;]:&gt;5} &quot;
          f&quot;| {r[&#39;metrics&#39;][&#39;latencyMs&#39;]:&gt;5}ms&quot;)

call(&quot;리전 규칙이 뭐야? 한 문장.&quot;, cache=False)
call(&quot;리전 규칙이 뭐야? 한 문장.&quot;, cache=True)    # 1회차 = 캐시 기록
call(&quot;태그 규칙이 뭐야? 한 문장.&quot;, cache=True)    # 2회차 = 캐시 읽기</code></pre>
<pre><code>$ python step9_cache.py
cache=OFF | input= 8214 write=    0 read=    0 |   811ms
cache=ON  | input=   26 write= 8188 read=    0 |   774ms
cache=ON  | input=   26 write=    0 read= 8188 |   772ms</code></pre><table>
<thead>
<tr>
<th>호출</th>
<th>무슨 일이</th>
<th>과금 배수</th>
</tr>
</thead>
<tbody><tr>
<td>1회차 (Cache OFF)</td>
<td>8,214 Token을 정가로 입력</td>
<td>1.0x</td>
</tr>
<tr>
<td>2회차 (Cache ON, 첫 호출)</td>
<td>8,188 Token을 Cache에 기록 (<code>write</code>)</td>
<td>1.25x (기록 수수료)</td>
</tr>
<tr>
<td>3회차 (Cache ON, 재사용)</td>
<td>8,188 Token을 Cache에서 읽음 (<code>read</code>)</td>
<td>0.1x</td>
</tr>
</tbody></table>
<p>세 번째 줄이 핵심입니다. 반복되는 입력 Token이 90% 싸집니다.
<code>input</code>이 8,214에서 26으로 떨어졌고, 정가로 내는 건 질문 26 Token뿐입니다.
System Prompt와 도구 스펙이 수만 Token씩 되는 Agent라면 이 한 줄이 월 요금을 크게 좌우합니다.
1편 2장의 응답 구조에 <code>cacheReadInputTokens</code>, <code>cacheWriteInputTokens</code>가 항상 붙어 있던 이유가 이것입니다.</p>
<h3 id="cache가-안-걸렸던-이유-최소-token-수">Cache가 안 걸렸던 이유: 최소 Token 수</h3>
<p>처음 Cache를 켰을 때는 <code>write=0 read=0</code>만 나와서 한참 헤맸습니다.
알고 보니 Cache에는 최소 Token 수가 있었습니다. Prompt 길이를 바꿔 가며 어디서부터 걸리는지 재 봤습니다.</p>
<pre><code>$ python step9b_cache_min.py
규칙  10줄 | 총입력   670 | write=    0 read=    0 | 캐시 안 됨 ❌
규칙  30줄 | 총입력  1990 | write=    0 read=    0 | 캐시 안 됨 ❌
규칙  60줄 | 총입력  3970 | write=    0 read=    0 | 캐시 안 됨 ❌
규칙 120줄 | 총입력  7930 | write= 7921 read=    0 | 캐시 됨 ✅</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/89697d48-f1de-48d8-8aec-f7f4b88a27de/image.png" alt="Prompt Caching 실측"></p>
<p>Haiku 4.5는 4천 Token 조금 아래까지는 Cache가 걸리지 않았습니다. 이 하한은 Model마다 다릅니다(1,024~4,096 사이).
<code>cachePoint</code>를 넣었는데 <code>write</code>가 0이면 Error가 아니라 Prompt가 짧아서 그냥 무시된 겁니다.
Error가 안 나니까 오히려 더 헷갈렸습니다.</p>
<h3 id="caching-쓸-때-알아-둘-것">Caching 쓸 때 알아 둘 것</h3>
<ul>
<li>TTL은 5분이고 읽힐 때마다 갱신됩니다. 5분 넘게 쉬면 다시 기록(1.25x)부터 시작하고, 대화가 이어지는 동안은 계속 살아 있습니다.</li>
<li>Cache 포인트는 요청당 최대 4개입니다. 저는 <code>system</code> 끝, 도구 스펙 끝, 대화 중간, 마지막 Message 앞 정도에 둡니다.</li>
<li>Cache는 앞에서부터 똑같은 부분까지만 적중합니다. 앞쪽이 한 글자만 바뀌어도 뒤는 전부 미스입니다.
1편 5장에서 &quot;바뀌는 값은 끝에 두라&quot;고 한 게 이 때문입니다. System Prompt 맨 앞에 현재 시각을 넣으면 매 요청마다 Cache가 통째로 무효가 됩니다. 저도 처음에 이렇게 해 놓고 왜 <code>read</code>가 안 나오나 한참 봤습니다.</li>
<li>Caching을 지원하지 않는 Model에 <code>cachePoint</code>를 넣으면 <code>ValidationException</code>이 아니라 <code>AccessDeniedException</code>이 오는 경우가 있습니다. 권한 문제로 착각하기 쉽습니다.</li>
</ul>
<hr>
<h2 id="4-extended-thinking으로-추론-과정-보기">4. Extended Thinking으로 추론 과정 보기</h2>
<p>Claude는 답하기 전에 &quot;생각하는 과정&quot;을 따로 받아 볼 수 있습니다. 계산이나 계획처럼 복잡한 질문에서 정확도가 올라갑니다.
Converse에서는 <code>additionalModelRequestFields</code>로 켜는데, Model 전용 Option은 전부 여기로 들어갑니다.</p>
<p><code>step10_thinking.py</code></p>
<pre><code class="language-python">resp = runtime.converse_stream(
    modelId=&quot;us.anthropic.claude-sonnet-4-5-20250929-v1:0&quot;,
    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;17 * 23을 계산하고 검산까지 해줘.&quot;}]}],
    inferenceConfig={&quot;maxTokens&quot;: 3000},          # ← thinking budget보다 커야 한다
    additionalModelRequestFields={&quot;thinking&quot;: {&quot;type&quot;: &quot;enabled&quot;, &quot;budget_tokens&quot;: 1024}},
)
mode = None
for ev in resp[&quot;stream&quot;]:
    d = ev.get(&quot;contentBlockDelta&quot;, {}).get(&quot;delta&quot;, {})
    if &quot;reasoningContent&quot; in d:                               # 🧠 추론 블록
        if mode != &quot;think&quot;:
            print(&quot;\n🧠 [추론]&quot;, end=&quot; &quot;); mode = &quot;think&quot;
        print(d[&quot;reasoningContent&quot;].get(&quot;text&quot;, &quot;&quot;), end=&quot;&quot;)
    elif &quot;text&quot; in d:                                         # 💬 답변 블록
        if mode != &quot;text&quot;:
            print(&quot;\n\n💬 [답변]&quot;, end=&quot; &quot;); mode = &quot;text&quot;
        print(d[&quot;text&quot;], end=&quot;&quot;)</code></pre>
<pre><code>$ python step10_thinking.py

🧠 [추론] 17 * 23을 계산하겠습니다.

17 * 23
= 17 * 20 + 17 * 3
= 340 + 51
= 391

검산을 위해 다른 방법으로도 계산해보겠습니다.

방법 2:
23 * 17
= 23 * 10 + 23 * 7
= 230 + 161
= 391

또는 나눗셈으로 검산:
391 ÷ 17 = 23 ✓
391 ÷ 23 = 17 ✓

💬 [답변] # 17 × 23 계산

## 계산 과정
    23
  × 17
  ----
   161  (23 × 7)
  230   (23 × 10)
  ----
   391
...
**답: 391**</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/0550dde3-5854-4a5c-9c8e-f9b23f24b238/image.png" alt="Extended Thinking: 추론 Block과 답변 Block"></p>
<p><code>content</code>에 <code>text</code> 말고 <code>reasoningContent</code>라는 Block이 하나 더 생겼습니다.
1편에서 &quot;content는 Block 배열&quot;이라고 계속 말했던 이유가 하나 더 늘었습니다.</p>
<p>처음 켰을 때는 연달아 두 번 거부당했습니다. 아래가 실제 Error Message입니다.</p>
<pre><code>ValidationException: `temperature` may only be set to 1 when thinking is enabled.
ValidationException: `max_tokens` must be greater than `thinking.budget_tokens`.</code></pre><table>
<thead>
<tr>
<th>제약</th>
<th>대응</th>
</tr>
</thead>
<tbody><tr>
<td><code>temperature</code> 지정 불가</td>
<td>thinking을 켤 때는 <code>inferenceConfig</code>에서 <code>temperature</code>를 뺀다</td>
</tr>
<tr>
<td><code>maxTokens</code>가 <code>budget_tokens</code>보다 커야 함</td>
<td>추론 Token도 출력 Token에 포함되므로 <code>maxTokens</code>를 <code>budget + 답변 여유</code>로 잡는다</td>
</tr>
</tbody></table>
<p>두 번째 제약을 아슬아슬하게 맞추면 추론이 출력 예산을 다 써 버려서 답변이 0자로 잘립니다.
<code>stopReason</code>이 <code>max_tokens</code>인데 Text가 비어 있다면 이 경우입니다. 1편 3장에서 <code>stopReason</code>을 꼭 보라고 했던 게 여기서도 나옵니다.</p>
<hr>
<h2 id="5-fastapi--sse-server-만들기">5. FastAPI + SSE Server 만들기</h2>
<p>지금까지는 스크립트였습니다. 이걸 HTTP로 감싸면 Terminal이든 모바일 App이든 붙일 수 있습니다.
Streaming 전송은 SSE(Server-Sent Events)를 씁니다. <code>data: {...}\n\n</code> 형식으로 Event를 흘려보내는 단순한 HTTP 규격입니다.</p>
<p><code>step11_server.py</code> (핵심 부분만)</p>
<pre><code class="language-python">from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

app = FastAPI()
class Ask(BaseModel):
    text: str

def sse(obj) -&gt; str:                       # SSE 프레이밍: &quot;data: {...}\n\n&quot;
    return f&quot;data: {json.dumps(obj, ensure_ascii=False)}\n\n&quot;

@app.post(&quot;/chat&quot;)
def chat(body: Ask):
    def gen():
        resp = runtime.converse_stream(
            modelId=MODEL,
            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: body.text}]}],
            inferenceConfig={&quot;maxTokens&quot;: 500})
        for ev in resp[&quot;stream&quot;]:                        # 1편 6장의 이벤트를 그대로 중계
            if &quot;contentBlockDelta&quot; in ev:
                t = ev[&quot;contentBlockDelta&quot;][&quot;delta&quot;].get(&quot;text&quot;)
                if t:
                    yield sse({&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: t})
            elif &quot;metadata&quot; in ev:
                yield sse({&quot;type&quot;: &quot;usage&quot;, &quot;usage&quot;: ev[&quot;metadata&quot;][&quot;usage&quot;]})
        yield sse({&quot;type&quot;: &quot;done&quot;})
    return StreamingResponse(gen(), media_type=&quot;text/event-stream&quot;)</code></pre>
<pre><code class="language-bash">uvicorn step11_server:app --port 8599
curl -sN -X POST http://127.0.0.1:8599/chat \
  -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;text&quot;:&quot;SSE가 뭔지 두 문장으로 설명해줘.&quot;}&#39;</code></pre>
<pre><code>data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;#&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot; SSE (&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Server-Sent Events)&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;\n\nSSE는 서&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;버에&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;서 클&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;라이언트로&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot; 실시간 데이터&quot;}
...
data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;.&quot;}

data: {&quot;type&quot;: &quot;usage&quot;, &quot;usage&quot;: {&quot;inputTokens&quot;: 29, &quot;outputTokens&quot;: 145, &quot;totalTokens&quot;: 174}}

data: {&quot;type&quot;: &quot;done&quot;}</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/3f4e5309-8fe6-44e5-aa63-9be9d7aaaea7/image.png" alt="curl로 받은 SSE Stream"></p>
<p><code>curl -N</code>(버퍼링 끄기)으로 글자가 실시간으로 떨어지는 걸 처음 봤을 때 &quot;이제 App으로 만들 수 있겠다&quot; 싶었습니다.
<code>data:</code> 한 줄이 Event 하나고, 빈 줄이 Event의 끝입니다. 조각이 <code>&quot;서&quot;</code>, <code>&quot;버에&quot;</code>, <code>&quot;서 클&quot;</code>처럼 어절 중간에서 잘리는 것도 그대로 보입니다.
1편 6장에서 본 &quot;Chunk 크기는 정해져 있지 않다&quot;는 게 HTTP 위에서도 똑같습니다.</p>
<h3 id="websocket-대신-sse를-쓴-이유">WebSocket 대신 SSE를 쓴 이유</h3>
<table>
<thead>
<tr>
<th></th>
<th>SSE</th>
<th>WebSocket</th>
</tr>
</thead>
<tbody><tr>
<td>방향</td>
<td>Server -&gt; Client 단방향</td>
<td>양방향</td>
</tr>
<tr>
<td>Protocol</td>
<td>그냥 HTTP</td>
<td>업그레이드 핸드셰이크 필요</td>
</tr>
<tr>
<td>Proxy, ALB, CDN</td>
<td>대부분 그대로 통과</td>
<td>설정 추가 필요</td>
</tr>
<tr>
<td>Debugging</td>
<td><code>curl</code>로 확인 가능</td>
<td>전용 Client 필요</td>
</tr>
</tbody></table>
<p>챗봇은 &quot;질문 한 번, 응답 Stream 한 번&quot;이라 단방향이면 충분했습니다.
HTTP라서 <code>curl</code>로 바로 Debugging할 수 있다는 게 직접 써 보니 생각보다 큰 장점이었습니다.</p>
<p>여기까지가 개인 챗봇 Backend의 최소 형태입니다. SeanChat도 이 구조를 그대로 키워서 CLI와 iOS App이 같은 Backend에 붙어 있습니다.
다만 이 코드를 그대로 EC2에 올리면 문제가 몇 가지 생깁니다. 60초 넘게 생각하는 요청을 ALB가 끊어 버린다거나, Stream 도중에 끊기면 재시도가 안 된다거나 하는 것들인데, 이건 5편에서 다룹니다.</p>
<hr>
<h2 id="1·2편에서-만난-error-정리">1·2편에서 만난 Error 정리</h2>
<p>1편에서 정리한 4개에 이번 편에서 만난 3개를 더하면 아래 7개가 됩니다. 전부 실제로 받은 Message입니다.</p>
<table>
<thead>
<tr>
<th>#</th>
<th>Error Message(일부)</th>
<th>원인</th>
<th>해결</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td><code>NoCredentialsError: Unable to locate credentials</code></td>
<td>자격증명 없음</td>
<td><code>AWS_BEARER_TOKEN_BEDROCK</code> 또는 <code>AWS_PROFILE</code> 확인</td>
</tr>
<tr>
<td>2</td>
<td><code>AccessDeniedException: ... is not authorized to perform: bedrock:CountTokens</code></td>
<td>IAM에 그 Action이 없음</td>
<td>Message에 나온 Action을 정책에 추가</td>
</tr>
<tr>
<td>3</td>
<td><code>ValidationException: Invocation of model ID ... with on-demand throughput isn&#39;t supported</code></td>
<td>Inference Profile 없이 호출</td>
<td><code>us.</code> 접두어 ID 사용 (1편 1장)</td>
</tr>
<tr>
<td>4</td>
<td><code>ValidationException: The text field in the ContentBlock object at messages.0.content.0 is blank</code></td>
<td>빈 문자열을 보냄</td>
<td>빈 입력은 호출 전에 걸러냄</td>
</tr>
<tr>
<td>5</td>
<td><code>ParamValidationError: Invalid length for parameter toolConfig.tools, value: 0, valid min length: 1</code></td>
<td>도구 배열이 빔</td>
<td><code>toolConfig</code> 키 자체를 뺀다 (2장)</td>
</tr>
<tr>
<td>6</td>
<td><code>ValidationException: \</code>temperature` may only be set to 1 when thinking is enabled`</td>
<td>thinking과 temperature를 같이 씀</td>
<td><code>temperature</code> 제거 (4장)</td>
</tr>
<tr>
<td>7</td>
<td><code>ValidationException: \</code>max_tokens` must be greater than `thinking.budget_tokens``</td>
<td>출력 상한이 추론 예산보다 작음</td>
<td><code>maxTokens</code> 올리기 (4장)</td>
</tr>
</tbody></table>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/6ef49ff5-fada-4486-add8-d27496ec9e4e/image.png" alt="첫날 만나는 Error 7종: 실제 Message"></p>
<p><code>AccessDeniedException</code>이 IAM 문제인지, Model Access 문제인지, 기능 미지원인지 구분하는 방법은 1편 마지막에 적어 두었습니다.</p>
<hr>
<h2 id="정리">정리</h2>
<pre><code>step7_chat.py         대화 기억: messages 배열이 전부 (in 57 -&gt; 114)
step8_tool.py         도구 호출 Loop (tool_use -&gt; toolResult -&gt; end_turn)
step9_cache.py        Prompt Caching (input 8,214 -&gt; read 8,188) + 최소 Token 실측
step10_thinking.py    Extended Thinking (reasoningContent)
step11_server.py      FastAPI + SSE Backend</code></pre><p>1편과 합쳐 파일 10개, 다 합해도 250줄 정도입니다. Framework 없이도 여기까지는 충분히 됩니다.</p>
<p>이번 편에서 기억해 두면 좋은 것들입니다.</p>
<ol>
<li>대화 기억은 내 코드가 들고 있는 <code>messages</code> 배열입니다. 턴이 늘수록 입력 Token이 계속 쌓입니다.</li>
<li>반복되는 앞부분은 <code>cachePoint</code> 한 줄로 Cache할 수 있습니다. 최소 Token 수보다 짧으면 조용히 무시됩니다.</li>
<li>Agent는 결국 <code>stopReason == &quot;tool_use&quot;</code>인 동안 도는 while Loop입니다. 도구 실행은 내 코드가 합니다.</li>
<li>Extended Thinking을 켜면 <code>temperature</code>를 빼고 <code>maxTokens</code>를 넉넉히 잡아야 합니다.</li>
<li>SSE는 그냥 HTTP라서 <code>curl -N</code>으로 바로 확인할 수 있습니다.</li>
</ol>
<h2 id="다음-편-예고">다음 편 예고</h2>
<p>이번 편은 Terminal에서 <code>curl</code>로 SSE가 흘러나오는 화면에서 끝났습니다. 그 화면을 보고 있으니 이걸 폰에서 보고 싶어졌습니다.
3편에서는 iPhone App을 만듭니다. Xcode 새 Project부터 SwiftUI 채팅 화면, <code>URLSession.bytes(for:)</code>로 SSE를 받는 부분까지 파일 단위로 따라가 보겠습니다.</p>
<p>다음 편: <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-3-iPhone-App-%EB%A7%8C%EB%93%A4%EA%B8%B0-SwiftUI-SSE">3편 - iPhone App 만들기: SwiftUI + SSE</a></p>
<hr>
<p><em>이 글은 개인 AWS 계정에서 실험한 결과입니다.
요금과 Model 지원 사항은 작성 시점(2026년 9월, us-east-2) 기준입니다.</em></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 LZA를 활용한 AWS Control Tower 구축 (3) - Transit Gateway / VPC Network 구성]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-3-Transit-Gateway-VPC-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EA%B5%AC%EC%84%B1</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-3-Transit-Gateway-VPC-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EA%B5%AC%EC%84%B1</guid>
            <pubDate>Sat, 03 Oct 2026 05:12:14 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p><a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-2-OU-%EA%B3%84%EC%A0%95-SCP%EB%A5%BC-%EC%BD%94%EB%93%9C%EB%A1%9C-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0">2편</a>에서 OU, 계정, SCP까지 구성했으니 이번에는 Network입니다.
LZA에서 Network는 <code>network-config.yaml</code> 파일 하나로 관리합니다. IPAM, Transit Gateway, VPC, Routing이 전부 이 파일에 들어가서 설정 파일 6개 중에 제일 깁니다. 제 환경에서도 지금 20KB 정도 됩니다.</p>
<p>이번 글에서 다루는 내용은 아래와 같습니다.</p>
<ul>
<li>기본 VPC 삭제</li>
<li>IPAM으로 CIDR 나누기</li>
<li>서울 Region Transit Gateway 만들고 다른 계정에 공유하기</li>
<li>중앙 egress용 inspection VPC, Workload VPC 만들기</li>
<li>배포하다 실패한 것, 안 쓰는 Network 비용 정리한 것</li>
</ul>
<p>처음에는 서울 / 버지니아 / 오레곤 세 Region에 TGW를 하나씩 두고 peering으로 다 엮었습니다. 그런데 막상 써 보니 실제로 쓰는 건 서울뿐이라 나머지는 정리했고, 그 얘기도 뒤에 같이 적었습니다.</p>
<blockquote>
<p>계정 ID는 <code>111122223333</code>으로 가렸습니다. 설정 파일은 실제로 쓰는 파일에서 필요한 부분만 잘라 왔습니다.</p>
</blockquote>
<hr>
<h2 id="이번-편의-최종-구성">이번 편의 최종 구성</h2>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/a213c487-84c1-4f42-aa7b-432b9b79496a/image.png" alt=""></p>
<p>network 계정에 Transit Gateway와 inspection VPC를 두고, 다른 계정의 VPC들은 TGW에 붙여서 Internet으로 나갈 때 inspection VPC의 NAT Gateway를 같이 쓰는 구조입니다. 흔히 말하는 중앙 집중식 egress입니다.</p>
<p>그림에 점선으로 그린 Workload 쪽 attachment는 지금은 꺼 둔 상태입니다. 이유는 뒤에 비용 얘기할 때 설명하겠습니다.</p>
<hr>
<h2 id="1-기본-network-configyaml">1. 기본 network-config.yaml</h2>
<p>LZA를 처음 설치하면 <code>network-config.yaml</code>은 이렇게 생겼습니다. S3 config Bucket의 <code>default/</code> 폴더에 설치 직후 파일이 남아 있어서 그대로 가져왔습니다.</p>
<pre><code class="language-yaml">defaultVpc:
  delete: false
  excludeAccounts: []
transitGateways: []
endpointPolicies: []
vpcs: []</code></pre>
<p>이게 전부입니다. 여기서부터 하나씩 채워 나가면 됩니다.</p>
<p>제일 먼저 바꾼 건 <code>defaultVpc.delete</code>입니다. 계정을 새로 만들면 Region마다 기본 VPC가 하나씩 생기는데, 이 값을 <code>true</code>로 두면 LZA가 배포하는 계정/Region에서 기본 VPC를 지워 줍니다.</p>
<pre><code class="language-yaml">defaultVpc:
  delete: true
  excludeAccounts: []</code></pre>
<p>기본 VPC가 남아 있으면 누군가 실수로 거기에 EC2를 띄울 수도 있어서 저는 그냥 지웠습니다. 특정 계정만 남기고 싶으면 <code>excludeAccounts</code>에 넣으면 됩니다.</p>
<hr>
<h2 id="2-ipam으로-cidr-나누기">2. IPAM으로 CIDR 나누기</h2>
<p>계정마다 VPC를 만들다 보면 CIDR 겹치는 게 제일 귀찮습니다. 나중에 TGW로 연결하려고 보면 이미 대역이 겹쳐 있어서 VPC를 다시 만들어야 하는 경우도 생기고요.
그래서 VPC CIDR을 직접 적지 않고 IPAM 풀에서 받아 오도록 했습니다.</p>
<p>먼저 전체 대역을 정했습니다. <code>172.16.0.0/12</code>를 <code>/15</code> 8개로 나눠서 Region마다 하나씩 줬습니다.</p>
<table>
<thead>
<tr>
<th>CIDR</th>
<th>Region</th>
<th>비고</th>
</tr>
</thead>
<tbody><tr>
<td>172.16.0.0/15</td>
<td>ap-northeast-2</td>
<td>서울 (실제 사용)</td>
</tr>
<tr>
<td>172.18.0.0/15</td>
<td>us-east-1</td>
<td>버지니아</td>
</tr>
<tr>
<td>172.20.0.0/15</td>
<td>us-west-2</td>
<td>오레곤</td>
</tr>
<tr>
<td>172.22.0.0/15 ~ 172.30.0.0/15</td>
<td>-</td>
<td>예약</td>
</tr>
</tbody></table>
<p><code>10.0.0.0/8</code>은 일부러 안 썼습니다. 나중에 외부 Network와 연결할 일이 생기면 10 대역이 제일 잘 겹쳐서 피했습니다.</p>
<p>IPAM 설정은 <code>centralNetworkServices</code> 아래에 들어갑니다. 아래는 서울 풀 부분입니다.</p>
<pre><code class="language-yaml">centralNetworkServices:
  delegatedAdminAccount: network
  ipams:
    - name: ipam-network
      region: us-east-1
      description: Organization IPAM
      operatingRegions:
        - us-east-1
        - us-west-2
        - ap-northeast-2
      pools:
        - name: pool-network-ane2
          description: Regional pool - ap-northeast-2 (172.16.0.0/15)
          locale: ap-northeast-2
          provisionedCidrs:
            - 172.16.0.0/15
          allocationDefaultNetmaskLength: 20
          allocationMinNetmaskLength: 17
          allocationMaxNetmaskLength: 24
          shareTargets:
            organizationalUnits:
              - Infrastructure
              - Security</code></pre>
<p><code>delegatedAdminAccount: network</code>로 Network 관리를 network 계정에 위임하고, 풀은 <code>shareTargets</code>로 OU 단위로 공유합니다.
VPC 쪽에서는 풀 이름이랑 크기만 적으면 됩니다.</p>
<pre><code class="language-yaml">    ipamAllocations:
      - ipamPoolName: pool-network-ane2
        netmaskLength: 24</code></pre>
<p>Subnet도 <code>ipamAllocation</code>에 <code>netmaskLength</code>만 적어 두면 VPC가 받은 대역 안에서 잘라서 줍니다. 덕분에 설정 파일에 CIDR 숫자를 거의 안 적어도 됩니다.</p>
<hr>
<h2 id="3-transit-gateway">3. Transit Gateway</h2>
<p>TGW는 network 계정 서울 Region에 하나 만들었습니다.</p>
<pre><code class="language-yaml">transitGateways:
  - name: tgw-network-ane2
    account: network
    region: ap-northeast-2
    shareTargets:
      organizationalUnits:
        - Infrastructure
        - Security
        - Sandbox
        - Workload
    asn: 65020
    dnsSupport: enable
    vpnEcmpSupport: enable
    defaultRouteTableAssociation: disable
    defaultRouteTablePropagation: disable
    autoAcceptSharingAttachments: enable</code></pre>
<p>몇 가지만 짚고 넘어가겠습니다.</p>
<ul>
<li><code>shareTargets</code>: RAM으로 TGW를 OU에 공유합니다. 이걸 해야 다른 계정 VPC가 이 TGW에 붙을 수 있습니다.</li>
<li><code>defaultRouteTableAssociation / Propagation: disable</code>: 기본 Route Table을 쓰면 붙은 VPC끼리 전부 통신이 됩니다. 그래서 끄고 Route Table을 직접 만들었습니다.</li>
<li><code>autoAcceptSharingAttachments: enable</code>: 다른 계정에서 attachment 요청이 오면 자동으로 수락합니다. 이걸 안 켜면 network 계정에서 하나씩 수락해 줘야 합니다.</li>
<li><code>asn</code>: Region별로 다르게 줬습니다. (버지니아 65010, 서울 65020, 오레곤 65030)</li>
</ul>
<p>Route Table은 두 개입니다.</p>
<table>
<thead>
<tr>
<th>TGW Route Table</th>
<th>연결(association)</th>
<th>하는 일</th>
</tr>
</thead>
<tbody><tr>
<td>rt-tgw-network-ane2</td>
<td>inspection VPC attachment</td>
<td>각 VPC 대역이 propagation돼서 돌아오는 경로</td>
</tr>
<tr>
<td>rt-tgw-network-ane2-dev</td>
<td>dev VPC attachment들</td>
<td>0.0.0.0/0 -&gt; inspection VPC</td>
</tr>
</tbody></table>
<p>dev VPC에서 Internet으로 나가는 Traffic은 <code>rt-tgw-network-ane2-dev</code>의 0/0 경로를 타고 inspection VPC로 가고, 거기 NAT Gateway를 통해 나갑니다. 돌아오는 Traffic은 <code>rt-tgw-network-ane2</code>에 propagation된 VPC 대역을 보고 원래 VPC로 돌아옵니다.
처음에는 stg / prd 테이블도 따로 만들 생각이었는데, 지금은 dev만 있어서 두 개만 두고 있습니다.</p>
<hr>
<h2 id="4-vpc-구성">4. VPC 구성</h2>
<h3 id="inspection-vpc-network-계정">inspection VPC (network 계정)</h3>
<p>다른 VPC들이 Internet으로 나갈 때 거쳐 가는 VPC입니다. Subnet은 용도별로 3개입니다.</p>
<pre><code class="language-yaml">vpcs:
  - name: vpc-network-ane2-inspection
    account: network
    region: ap-northeast-2
    ipamAllocations:
      - ipamPoolName: pool-network-ane2
        netmaskLength: 24
    internetGateway: true
    routeTables:
      - name: rt-network-ane2-tgw
        routes:
          - name: route-default-natgw
            destination: 0.0.0.0/0
            type: natGateway
            target: natgw-network-ane2a
      - name: rt-network-ane2-natgw
        routes:
          - name: route-default-igw
            destination: 0.0.0.0/0
            type: internetGateway
            target: IGW
          - name: route-internal-tgw
            destination: 172.16.0.0/12
            type: transitGateway
            target: tgw-network-ane2
    # (rt-network-ane2-nfw, subnets 생략)
    natGateways:
      - name: natgw-network-ane2a
        subnet: subnet-network-ane2a-natgw
    transitGatewayAttachments:
      - name: tgwatt-network-ane2-inspection
        transitGateway:
          name: tgw-network-ane2
          account: network
        routeTableAssociations:
          - rt-tgw-network-ane2
        routeTablePropagations:
          - rt-tgw-network-ane2-dev
        subnets:
          - subnet-network-ane2a-tgw</code></pre>
<p>흐름은 이렇습니다. TGW에서 들어온 Traffic은 <code>tgw</code> Subnet에 도착하고, 0/0이 NAT Gateway로 가 있어서 NAT를 거쳐 IGW로 나갑니다. 돌아올 때는 <code>natgw</code> Subnet Route Table에 <code>172.16.0.0/12 → TGW</code>가 있어서 다시 TGW로 들어갑니다.</p>
<p><code>nfw</code> Subnet은 원래 Network Firewall Endpoint 자리였습니다. 방화벽은 8월에 비용 때문에 지웠고, 지금은 Subnet만 남아 있습니다. 그리고 NAT Gateway는 비용 때문에 a존에 하나만 뒀습니다. 운영 환경이면 AZ마다 하나씩 두는 게 맞습니다.</p>
<p>배포하고 Console에서 Resource Map을 보면 이렇게 나옵니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/17c5d771-0d4f-423f-a314-205571166c98/image.png" alt=""></p>
<h3 id="workload-vpc-seanson-workload-dev-계정">Workload VPC (seanson-workload-dev 계정)</h3>
<p>Workload VPC는 다른 계정에 있지만 설정은 같은 <code>network-config.yaml</code>에 적습니다. <code>account</code>만 바꿔 주면 LZA가 그 계정에 VPC를 만들어 줍니다.</p>
<pre><code class="language-yaml">  - name: vpc-workload-ane2-dev
    account: seanson-workload-dev
    region: ap-northeast-2
    ipamAllocations:
      - ipamPoolName: pool-network-ane2
        netmaskLength: 24
    internetGateway: true
    routeTables:
      - name: rt-workload-ane2-private
        routes:
          - name: route-default-tgw
            destination: 0.0.0.0/0
            type: transitGateway
            target: tgw-network-ane2
          - name: route-internal-tgw
            destination: 172.16.0.0/12
            type: transitGateway
            target: tgw-network-ane2</code></pre>
<p>private Subnet의 0/0이 NAT Gateway가 아니라 TGW로 가 있습니다. 이렇게 하면 Workload 계정마다 NAT Gateway를 만들 필요가 없습니다.
Subnet은 public(/28), private(/26), database(/27), tgw(/28)를 a·c 두 AZ에 하나씩 해서 8개입니다. TGW attachment용 Subnet은 작게 따로 빼 두었습니다.</p>
<hr>
<h2 id="5-배포하고-확인하기">5. 배포하고 확인하기</h2>
<p>배포는 2편과 똑같습니다. 설정 파일을 zip으로 묶어서 config Bucket <code>zipped/</code>에 올리면 <code>AWSAccelerator-Pipeline</code>이 돌기 시작합니다.</p>
<p>Network 쪽은 Deploy 단계의 <code>Network_Prepare</code> -&gt; <code>Network_VPCs</code> -&gt; <code>Network_Associations</code> 순서로 진행됩니다. 대략 TGW·IPAM 같은 공용 Resource를 먼저 만들고, VPC·Subnet·Routing을 만든 다음, 마지막에 TGW 연결과 공유 쪽을 정리하는 순서입니다.</p>
<p>배포가 끝나고 network 계정에서 확인해 봤습니다.</p>
<pre><code class="language-bash">$ aws ec2 describe-transit-gateways --region ap-northeast-2 \
    --query &#39;TransitGateways[].[Tags[?Key==`Name`]|[0].Value,State,Options.AmazonSideAsn]&#39; --output table
--------------------------------------------
|          DescribeTransitGateways         |
+-------------------+-------------+--------+
|  tgw-network-ane2 |  available  |  65020 |
+-------------------+-------------+--------+

$ aws ec2 describe-transit-gateway-attachments --region ap-northeast-2 \
    --query &#39;TransitGatewayAttachments[].[Tags[?Key==`Name`]|[0].Value,ResourceType,State]&#39; --output table
--------------------------------------------------------
|           DescribeTransitGatewayAttachments          |
+---------------------------------+------+-------------+
|  tgwatt-network-ane2-inspection |  vpc |  available  |
|  None                           |  vpc |  available  |
+---------------------------------+------+-------------+</code></pre>
<p>이름이 <code>None</code>으로 나오는 attachment는 LZA 밖에서 따로 붙인 것이라 이름 Tag가 없습니다.</p>
<hr>
<h2 id="6-겪은-문제들">6. 겪은 문제들</h2>
<h3 id="6-1-route-이름-바꿨다가-network_vpcs-실패-2026-07-15">6-1. Route 이름 바꿨다가 Network_VPCs 실패 (2026-07-15)</h3>
<p>shared service VPC는 처음에 NAT Gateway를 따로 두고 있었습니다. 이걸 inspection VPC로 나가게 바꾸려고 private Route Table의 0/0을 NAT -&gt; TGW로 바꿨는데, 이왕 바꾸는 김에 Route 이름도 내용에 맞게 <code>route-default-tgw</code>로 바꿨습니다.</p>
<pre><code class="language-diff">       - name: rt-sharedservice-ane2-private
         routes:
-          - name: route-default-natgw
+          - name: route-default-tgw
             destination: 0.0.0.0/0
-            type: natGateway
-            target: natgw-sharedservice-ane2a
+            type: transitGateway
+            target: tgw-network-ane2</code></pre>
<p>그리고 Pipeline을 돌렸더니 <code>Network_VPCs</code>에서 실패했습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/456bb4f8-6b98-43f3-8c7d-2f015a090675/image.png" alt=""></p>
<p>CodeBuild Log를 보면 이렇게 나와 있습니다.</p>
<pre><code>AWSAccelerator-RouteEntriesStack-vpc-sharedservice-ane2-111122223333-ap-northeast-2 | 6 | 1:21:46 AM | CREATE_FAILED | AWS::EC2::Route | VpcSharedserviceAne2VpcRtSharedserviceAne2PrivateRouteTableRouteDefaultTgwRouteEntry Resource handler returned message: &quot;The route identified by 0.0.0.0/0 already exists. (Service: Ec2, Status Code: 400, ...)&quot;</code></pre><p>Resource 이름을 보면 <code>...PrivateRouteTable</code><strong><code>RouteDefaultTgw</code></strong><code>RouteEntry</code>처럼 Route 이름이 CloudFormation Logical ID에 그대로 들어갑니다. 그래서 이름을 바꾸면 CloudFormation은 &quot;기존 Route 수정&quot;이 아니라 &quot;새 Route 추가 + 기존 Route 삭제&quot;로 처리합니다. 문제는 새 걸 먼저 만들려고 하는데, 같은 Route Table에 0.0.0.0/0이 이미 있으니 만들 수가 없는 거죠.</p>
<p>해결은 간단했습니다. 이름은 원래대로 두고 type / target만 바꿨습니다.</p>
<pre><code class="language-yaml">      - name: rt-sharedservice-ane2-private
        routes:
          # NOTE: route name kept as route-default-natgw for CFN logical-ID stability.
          # Only the TARGET changed (NAT gateway -&gt; TGW) so private egress flows through the
          # inspection VPC/NFW. Renaming the route makes CFN CREATE a duplicate 0/0 route while
          # the old one still exists -&gt; &quot;route already exists&quot; (2026-07-15 Network_VPCs failure).
          - name: route-default-natgw
            destination: 0.0.0.0/0
            type: transitGateway
            target: tgw-network-ane2</code></pre>
<p>이렇게 다시 올리니 같은 날 바로 성공했습니다. 이름이 <code>natgw</code>인데 실제로는 TGW로 가니까 좀 어색하긴 합니다. 그래서 주석을 꼭 남겨 뒀습니다.
이 일 이후로 Route 이름에는 Target 종류를 안 넣으려고 합니다. 한번 배포한 Route 이름은 바꾸지 않는 게 속 편합니다.</p>
<h3 id="6-2-안-쓰는-tgw에도-비용이-나간다">6-2. 안 쓰는 TGW에도 비용이 나간다</h3>
<p>처음에는 서울 / 버지니아 / 오레곤에 TGW를 하나씩 만들고 peering 3개로 다 엮어 뒀습니다. 그런데 VPC가 실제로 붙어 있는 건 서울뿐이었습니다.</p>
<p>TGW는 attachment 단위로 시간당 요금이 붙는데, peering attachment도 여기에 들어갑니다. VPC가 하나도 안 붙은 버지니아 / 오레곤 TGW에서도 peering 때문에 계속 돈이 나가고 있었습니다. Cost Explorer로 TGW 시간 요금만 뽑아 보면 이렇습니다. (조직 전체, USD)</p>
<pre><code class="language-bash">$ aws ce get-cost-and-usage --profile sean-lza \
  --time-period Start=2026-06-01,End=2026-10-01 --granularity MONTHLY --metrics UnblendedCost \
  --filter &#39;{&quot;Dimensions&quot;:{&quot;Key&quot;:&quot;USAGE_TYPE&quot;,&quot;Values&quot;:[&quot;APN2-TransitGateway-Hours&quot;,&quot;USE1-TransitGateway-Hours&quot;,&quot;USW2-TransitGateway-Hours&quot;]}}&#39; \
  --group-by Type=DIMENSION,Key=USAGE_TYPE \
  --query &#39;ResultsByTime[].{month:TimePeriod.Start,cost:Groups[].[Keys[0],Metrics.UnblendedCost.Amount]}&#39; --output json | python3 -c &quot;
import json,sys
for r in json.load(sys.stdin): print(r[&#39;month&#39;], &#39;, &#39;.join(f&#39;{k.split(\&quot;-\&quot;)[0]} {float(v):.2f}&#39; for k,v in r[&#39;cost&#39;]))&quot;
2026-06-01 APN2 53.34, USE1 18.80, USW2 18.80
2026-07-01 APN2 283.78, USE1 62.40, USW2 62.40
2026-08-01 APN2 162.40
2026-09-01 APN2 100.66</code></pre>
<p>정리는 두 번에 나눠서 했습니다.</p>
<ul>
<li>7/27: 버지니아 / 오레곤 TGW와 peering 3개 삭제 -&gt; 8월부터 USE1 / USW2 요금 0</li>
<li>8/18: 안에 아무것도 없는 VPC 두 개(workload-dev, sharedservice)의 attachment 정리, Network Firewall 삭제</li>
</ul>
<p>서울 기준으로 attachment 하나가 시간당 $0.07, 한 달이면 약 $51입니다. Test 환경에서 VPC 하나 붙여 놓고 잊어버리면 그냥 매달 이만큼 나갑니다.</p>
<p>설정 파일에서는 지우지 않고 주석으로 남겨 뒀습니다. 다시 필요하면 주석만 풀고 배포하면 됩니다.</p>
<pre><code class="language-yaml"># ===== [DISABLED 2026-08-18 cost cleanup] idle TGW attachment =====
#    transitGatewayAttachments:
#      - name: tgwatt-workload-ane2-dev
#        transitGateway:
#          name: tgw-network-ane2
#          account: network
#        routeTableAssociations:
#          - rt-tgw-network-ane2-dev</code></pre>
<p>놓치기 쉬운 부분이 두 가지 있었습니다.</p>
<ul>
<li>7/27 정리는 Pipeline을 거치지 않고 직접 지웠습니다. 그러다 보니 8/18 배포 전까지는 설정 파일과 실제 상태가 안 맞았습니다. LZA를 쓰면 지우는 것도 설정 파일로 하는 게 맞습니다.</li>
<li>같은 날 <code>global-config.yaml</code>의 <code>enabledRegions</code>에서 us-west-2도 뺐는데, LZA는 Region을 빼도 그 Region에 만들어 둔 Stack을 자동으로 지워 주지 않습니다. 배포가 끝난 다음 남은 Stack은 따로 정리해야 합니다.</li>
</ul>
<p>그리고 attachment를 꺼 둔 두 VPC는 private 0/0이 갈 곳이 없어서 지금은 밖으로 못 나갑니다. 둘 다 비어 있는 VPC라 일단 이렇게 뒀습니다.</p>
<hr>
<h2 id="정리">정리</h2>
<ul>
<li><code>network-config.yaml</code> 기본값은 거의 비어 있고, <code>defaultVpc.delete: true</code>부터 시작하면 됩니다.</li>
<li>VPC CIDR은 IPAM 풀에서 받게 하면 계정이 늘어나도 대역이 안 겹칩니다.</li>
<li>TGW는 기본 Route Table을 끄고, Route Table을 직접 나눠서 쓰는 게 관리하기 편했습니다.</li>
<li>한번 배포한 Route 이름은 바꾸지 마세요. CloudFormation Logical ID가 바뀌면서 배포가 실패할 수 있습니다.</li>
<li>TGW는 attachment 단위로 과금됩니다. 안 쓰는 Region TGW, peering, 비어 있는 VPC attachment는 생각보다 많이 나갑니다.</li>
</ul>
<p>다음 편 <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-4-%EB%B3%B4%EC%95%88-Service%EC%99%80-Identity-Center-%EA%B7%B8%EB%A6%AC%EA%B3%A0-%EC%8B%9C%EB%A6%AC%EC%A6%88-%EC%A0%95%EB%A6%AC">(4) 보안 Service와 Identity Center, 그리고 시리즈 정리</a>에서는 <code>security-config.yaml</code>로 GuardDuty, Security Hub 같은 보안 Service를 구성하고 시리즈를 마무리합니다.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 LZA를 활용한 AWS Control Tower 구축 (2) - OU / 계정 / SCP를 코드로 관리하기]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-2-OU-%EA%B3%84%EC%A0%95-SCP%EB%A5%BC-%EC%BD%94%EB%93%9C%EB%A1%9C-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95-2-OU-%EA%B3%84%EC%A0%95-SCP%EB%A5%BC-%EC%BD%94%EB%93%9C%EB%A1%9C-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0</guid>
            <pubDate>Thu, 24 Sep 2026 02:12:50 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p><a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95">1편</a>에서는 Control Tower를 켜고 LZA Stack을 올려서 <code>AWSAccelerator-Pipeline</code>이 처음 돌아가는 데까지 진행했습니다. 1편 마지막에 &quot;OU / Accounts 구성 및 Network 구성&quot;을 다음 편에서 다루겠다고 적었는데, 막상 정리해 보니 Network 설정 파일 하나만 20KB가 넘어서 두 편으로 나눴습니다.</p>
<ul>
<li>2편(이 글): OU, 계정, SCP, <code>organization-config.yaml</code>, <code>accounts-config.yaml</code>, SCP JSON</li>
<li>3편(다음 글): Network, <code>network-config.yaml</code>(Transit Gateway, VPC)</li>
</ul>
<p>이 글은 제가 실제로 쓰고 있는 LZA 환경의 설정 파일, CLI 출력, Console 화면을 그대로 옮긴 것입니다. 계정 ID는 <code>111122223333</code>, Email은 <code>example.com</code>, OU/정책 ID는 <code>xxxx</code>로 가렸습니다. 중간에 실패했던 배포도 숨기지 않고 넣었습니다. 사실 이 글에서 제일 쓸모 있는 부분은 뒤쪽의 &quot;겪은 문제들&quot;일 수도 있습니다.</p>
<blockquote>
<p>1편을 쓴 뒤 다른 계정에 환경을 새로 설치했습니다. 1편 예시의 Template Bucket은 us-west-2였고, 이 글의 환경은 <strong>홈 Region us-east-1</strong>로 2026년 6월에 설치한 것입니다. 설치 절차는 1편과 같습니다. 그리고 1편의 명령어 경로(<code>cd landing-zone-accelerator-on-aws/source</code>)와 Parameter 예시도 이번에 바로잡았습니다.</p>
</blockquote>
<hr>
<h2 id="이번-편의-최종-구성">이번 편의 최종 구성</h2>
<p>먼저 결과부터 보겠습니다. 이 글이 끝나면 조직이 아래처럼 됩니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/59d3689a-0f80-4199-b24b-ae854ee33315/image.png" alt="조직 구성도"></p>
<ul>
<li>OU 4개: Security, Infrastructure, Workload, Sandbox</li>
<li>계정 7개: Management 1개 + OU 아래 6개</li>
<li>SCP: 모든 OU에 &quot;조직 탈퇴 금지&quot; 정책. Region 제한 정책은 만들어 두었지만 지금은 꺼 둔 상태입니다(이유는 SCP Section에서).</li>
</ul>
<p>Console의 AWS Organizations 화면으로 보면 이렇습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/be205a70-0b9f-4ae2-bfda-41b6b10e87d1/image.png" alt="AWS Organizations 조직 구조"></p>
<hr>
<h2 id="lza-설정-파일-6종">LZA 설정 파일 6종</h2>
<p>LZA는 &quot;설정 파일을 고치면 Pipeline이 그 상태로 맞춰 준다&quot;는 방식입니다. 설정 파일은 설치할 때 지정한 S3 Bucket(또는 CodeCommit)에 zip으로 들어 있고, 파일마다 맡는 영역이 나뉘어 있습니다.</p>
<table>
<thead>
<tr>
<th>파일</th>
<th>담당</th>
<th>이번 편</th>
</tr>
</thead>
<tbody><tr>
<td><code>organization-config.yaml</code></td>
<td>OU, SCP, Tag 정책 등 조직 정책</td>
<td></td>
</tr>
<tr>
<td><code>accounts-config.yaml</code></td>
<td>필수 계정(Management/LogArchive/Audit)과 Workload 계정</td>
<td></td>
</tr>
<tr>
<td><code>global-config.yaml</code></td>
<td>홈 Region, 배포 Region, 로깅(CloudTrail 등)</td>
<td>일부(겪은 문제)</td>
</tr>
<tr>
<td><code>iam-config.yaml</code></td>
<td>IAM, IAM Identity Center 권한 세트</td>
<td>일부(겪은 문제)</td>
</tr>
<tr>
<td><code>security-config.yaml</code></td>
<td>GuardDuty, Security Hub, Config 등 보안 Service</td>
<td>-</td>
</tr>
<tr>
<td><code>network-config.yaml</code></td>
<td>VPC, Transit Gateway, Routing</td>
<td>3편</td>
</tr>
</tbody></table>
<p>SCP처럼 정책 본문이 필요한 경우에는 JSON 파일을 zip 안에 같이 넣고 yaml에서 파일 이름으로 가리킵니다.</p>
<hr>
<h2 id="1-현재-설정-받아오기">1. 현재 설정 받아오기</h2>
<p>설정을 고치기 전에 지금 들어 있는 zip부터 받아 봅니다. 관리 계정 자격증명으로 실행했습니다.</p>
<pre><code class="language-bash">$ ACCT=$(aws sts get-caller-identity --query Account --output text)
$ BUCKET=aws-accelerator-config-${ACCT}-us-east-1
$ aws s3 ls s3://$BUCKET/ --recursive
2026-06-22 16:59:55       2212 default/aws-accelerator-config.zip
2026-08-18 16:16:41       8548 zipped/aws-accelerator-config.zip</code></pre>
<p>Bucket 안에 zip이 두 개 있습니다.</p>
<ul>
<li><code>default/</code> : LZA가 설치될 때 만들어 둔 <strong>기본값</strong>입니다. Pipeline은 이 파일을 보지 않습니다. 처음 상태와 비교할 때 쓰기 좋습니다.</li>
<li><code>zipped/</code> : Pipeline이 실제로 읽는 <strong>현재 설정</strong>입니다. 설정을 바꾼다는 건 이 파일을 새로 올린다는 뜻입니다.</li>
</ul>
<p>둘 다 받아서 풀어 봅니다.</p>
<pre><code class="language-bash">$ aws s3 cp s3://$BUCKET/zipped/aws-accelerator-config.zip .
download: s3://aws-accelerator-config-111122223333-us-east-1/zipped/aws-accelerator-config.zip to ./aws-accelerator-config.zip
$ unzip -o aws-accelerator-config.zip -d config
$ aws s3 cp s3://$BUCKET/default/aws-accelerator-config.zip default.zip
$ unzip -o default.zip -d default
$ ls default config
config:
accounts-config.yaml
global-config.yaml
iam-config.yaml
network-config.yaml
organization-config.yaml
scp-deny-leave-org.json
scp-deny-regions.json
security-config.yaml

default:
accounts-config.yaml
global-config.yaml
iam-config.yaml
network-config.yaml
organization-config.yaml
security-config.yaml</code></pre>
<p>기본값에는 yaml 6개만 있고, 제 설정에는 SCP JSON 2개가 더 들어 있습니다. yaml 6개도 기본값과 비교하면 전부 바뀌어 있습니다. 이 중 이번 편에서 다룰 조직/계정/SCP 부분을 하나씩 보겠습니다.</p>
<p>그 전에, 설정을 고친 뒤 <strong>어떻게 반영되는지</strong>부터 짚고 가겠습니다. 이걸 먼저 알아야 뒤의 실패 기록이 읽힙니다.</p>
<hr>
<h2 id="2-설정이-반영되는-흐름">2. 설정이 반영되는 흐름</h2>
<p>LZA의 반영 흐름은 단순합니다.</p>
<ol>
<li>zip을 풀어서 yaml을 고친다</li>
<li>다시 zip으로 묶어서 S3 <code>zipped/</code> 경로에 덮어쓴다</li>
<li>S3 Upload가 <code>AWSAccelerator-Pipeline</code>을 자동으로 시작시킨다</li>
<li>Pipeline 중간의 <strong>Review</strong> 단계에서 사람이 승인하면 나머지 단계가 배포된다</li>
</ol>
<p>압축할 때 한 가지 주의할 점이 있습니다. <strong>yaml이 zip의 최상위에 있어야 합니다.</strong> <code>config</code> 폴더째 압축하면 zip 안에 <code>config/accounts-config.yaml</code>처럼 폴더가 한 겹 생기니까, 폴더 안으로 들어가서 압축합니다.</p>
<pre><code class="language-bash">$ cd config &amp;&amp; zip -r ../new.zip . &amp;&amp; cd ..
  adding: accounts-config.yaml (deflated 73%)
  adding: network-config.yaml (deflated 84%)
  adding: scp-deny-regions.json (deflated 61%)
  adding: global-config.yaml (deflated 50%)
  adding: security-config.yaml (deflated 60%)
  adding: scp-deny-leave-org.json (deflated 34%)
  adding: organization-config.yaml (deflated 58%)
  adding: iam-config.yaml (deflated 50%)
$ unzip -l new.zip
Archive:  new.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
     1721  07-08-2026 09:59   accounts-config.yaml
    20529  08-18-2026 15:12   network-config.yaml
     1076  06-26-2026 14:27   scp-deny-regions.json
     3302  08-18-2026 16:16   global-config.yaml
     1367  06-24-2026 13:46   security-config.yaml
      190  06-23-2026 10:39   scp-deny-leave-org.json
      888  06-26-2026 14:23   organization-config.yaml
      561  06-26-2026 10:03   iam-config.yaml
---------                     -------
    29634                     8 files</code></pre>
<p>그리고 이 zip을 <code>zipped/aws-accelerator-config.zip</code>이라는 이름으로 덮어쓰면 됩니다.</p>
<pre><code class="language-bash">aws s3 cp new.zip s3://$BUCKET/zipped/aws-accelerator-config.zip</code></pre>
<p>이 명령은 이 글을 쓰면서 다시 실행하지는 않았습니다. 올리는 순간 배포가 시작되기 때문입니다. 대신 마지막 Upload와 Pipeline 기록을 비교해 보면 흐름이 그대로 보입니다. 위 <code>aws s3 ls</code>에서 <code>zipped/</code> 파일의 Upload 시각은 <strong>16:16:41</strong>이었습니다.</p>
<pre><code class="language-bash">$ aws codepipeline list-pipeline-executions --pipeline-name AWSAccelerator-Pipeline --max-items 3 --query &quot;pipelineExecutionSummaries[].[startTime,status]&quot; --output table
---------------------------------------------------
|             ListPipelineExecutions              |
+-----------------------------------+-------------+
|  2026-08-18T16:16:42.177000+09:00 |  Succeeded  |
|  2026-08-18T15:36:18.370000+09:00 |  Succeeded  |
|  2026-08-18T15:17:12.211000+09:00 |  Failed     |
+-----------------------------------+-------------+</code></pre>
<p>Upload 1초 뒤인 <strong>16:16:42</strong>에 Pipeline이 시작됐습니다. S3에 올리는 것이 곧 배포 버튼이라는 뜻이라, 올리기 전에 한 번 더 보는 습관이 필요합니다. 맨 아래 15:17의 <code>Failed</code>는 제가 Review 단계에서 일부러 거절한 실행인데, 뒤의 &quot;겪은 문제들&quot;에서 다룹니다.</p>
<p>Pipeline 단계는 이렇게 생겼습니다.</p>
<pre><code class="language-bash">$ aws codepipeline get-pipeline --name AWSAccelerator-Pipeline --query &quot;pipeline.stages[].name&quot; --output text
Source    Prepare    Accounts    Bootstrap    Review    Logging    Organization    SecurityAudit    Deploy</code></pre>
<ul>
<li>Prepare: 설정 파일 문법과 현재 환경을 검사합니다. 설정이 틀리면 대부분 여기서 멈춥니다.</li>
<li>Accounts: <code>accounts-config.yaml</code>에 새 계정이 있으면 이 단계에서 만듭니다.</li>
<li>Review: 사람이 승인하는 단계입니다. 앞 단계에서 만든 변경 내용(diff)을 확인하고 승인하거나 거절합니다.</li>
<li>Organization / Deploy: SCP, Network 등 실제 Resource를 배포합니다.</li>
</ul>
<p>한 번 도는 데 보통 30~40분, 계정을 새로 만들 때는 1시간 넘게 걸리기도 했습니다. Console의 실행 기록은 이렇습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/67360353-d618-41e1-af15-e988c16ea724/image.png" alt="CodePipeline 실행 기록"></p>
<p>지금까지 이 Pipeline은 <strong>43번</strong> 실행됐고, 그중 <strong>성공 21 / 실패 17 / 중지 5</strong>입니다. 실패의 대부분은 처음 설치하고 일주일 동안 설정을 맞추면서 나왔습니다. 설정 파일로 관리한다고 한 번에 되는 건 아니었습니다.</p>
<hr>
<h2 id="3-ou-구성---organization-configyaml">3. OU 구성 - organization-config.yaml</h2>
<p>기본값과 현재 설정을 비교해 보겠습니다.</p>
<pre><code class="language-bash">$ diff default/organization-config.yaml config/organization-config.yaml
5c5,29
&lt; serviceControlPolicies: []
---
&gt;   - name: Sandbox
&gt;   - name: Workload
&gt; serviceControlPolicies:
&gt; # Temporarily disabled for Bedrock Marketplace subscription
&gt; #  - name: DenyRegionsExceptAllowed
&gt; #    description: Deny all actions outside us-east-1, us-west-2, ap-northeast-2
&gt; #    policy: scp-deny-regions.json
&gt; #    type: customerManaged
&gt; #    strategy: deny-list
&gt; #    deploymentTargets:
&gt; #      organizationalUnits:
&gt; #        - Infrastructure
&gt; #        - Security
&gt; #        - Sandbox
&gt;   - name: DenyLeaveOrganization
&gt;     description: Deny accounts from leaving the organization
&gt;     policy: scp-deny-leave-org.json
&gt;     type: customerManaged
&gt;     strategy: deny-list
&gt;     deploymentTargets:
&gt;       organizationalUnits:
&gt;         - Infrastructure
&gt;         - Security
&gt;         - Sandbox
&gt;         - Workload</code></pre>
<p>OU 부분만 떼어 보면 현재 설정은 이렇습니다.</p>
<pre><code class="language-yaml">enable: true
organizationalUnits:
  - name: Security
  - name: Infrastructure
  - name: Sandbox
  - name: Workload</code></pre>
<p>기본값에는 <code>Security</code>, <code>Infrastructure</code> 두 개만 있고, 저는 <code>Sandbox</code>, <code>Workload</code>를 추가했습니다. 여기서 알아둘 점이 있습니다.</p>
<ul>
<li><strong><code>Security</code>는 Control Tower가 만드는 OU</strong>입니다. LZA 기본값에도 들어 있어서 따로 손댈 게 없습니다.</li>
<li><strong><code>Sandbox</code>도 Control Tower 설정 과정에서 생긴 OU</strong>입니다. 그런데 LZA 기본값에는 없습니다. 조직에 있는 OU가 설정에 없으면 LZA는 Prepare 단계에서 멈춥니다. 저는 설치 직후 첫 실행에서 바로 이 문제를 만났습니다(겪은 문제 6-1).</li>
<li><strong><code>Workload</code>는 제가 Workload 계정을 넣으려고 추가</strong>한 OU입니다.</li>
</ul>
<p>반영된 결과는 CLI로 확인합니다.</p>
<pre><code class="language-bash">$ ROOT=$(aws organizations list-roots --query &quot;Roots[0].Id&quot; --output text)
$ aws organizations list-organizational-units-for-parent --parent-id $ROOT --query &quot;OrganizationalUnits[].Name&quot; --output text
Infrastructure    Sandbox    Workload    Security</code></pre>
<hr>
<h2 id="4-계정-구성---accounts-configyaml">4. 계정 구성 - accounts-config.yaml</h2>
<p>계정 파일은 <code>mandatoryAccounts</code>(필수 계정 3개)와 <code>workloadAccounts</code>(나머지)로 나뉩니다. 기본값에는 필수 계정만 있고 <code>workloadAccounts: []</code>로 비어 있습니다. 제 현재 설정은 이렇습니다(Email은 가렸고, 필수 계정의 긴 description은 줄였습니다).</p>
<pre><code class="language-yaml">mandatoryAccounts:
  - name: Management
    description: &gt;-
      The management (primary) account. ...
    email: you@example.com
    organizationalUnit: Root
    warm: false
  - name: LogArchive
    description: &gt;-
      The log archive account. ...
    email: you+logarchive@example.com
    organizationalUnit: Security
    warm: false
  - name: Audit
    description: &gt;-
      The security audit account ...
    email: you+audit@example.com
    organizationalUnit: Security
    warm: false
workloadAccounts:
  - name: network
    description: Shared network account for Transit Gateway and connectivity
    email: you+network@example.com
    organizationalUnit: Infrastructure
    warm: false
  - name: seanson-workload
    description: Workload account (legacy - to be decommissioned)
    email: you+workload@example.com
    organizationalUnit: Workload
    warm: false
  - name: seanson-workload-dev
    description: Workload account for development
    email: you+workload-dev@example.com
    organizationalUnit: Workload
    warm: false
  - name: seanson-sharedservice
    description: Shared services account (EKS platform, ArgoCD GitOps)
    email: you+sharedservice@example.com
    organizationalUnit: Infrastructure
    warm: false</code></pre>
<p>계정 하나를 추가하는 데 필요한 건 <code>name</code>, <code>email</code>, <code>organizationalUnit</code> 세 가지입니다.</p>
<ul>
<li><code>name</code>: LZA 설정 안에서 쓰는 이름입니다. 다른 설정 파일(Network, SCP 대상 등)에서 이 이름으로 계정을 가리킵니다. 필수 계정 3개의 <code>name</code>은 바꾸면 안 됩니다.</li>
<li><code>email</code>: AWS 계정마다 Email은 고유해야 합니다. Gmail이라면 <code>you+network@gmail.com</code>처럼 <code>+</code> 별칭을 쓰면 메일함 하나로 여러 계정을 받을 수 있습니다.</li>
<li><code>organizationalUnit</code>: <code>organization-config.yaml</code>에 있는 OU 이름이어야 합니다.</li>
</ul>
<p>계정이 실제로 언제 만들어졌는지 보면 Pipeline의 Accounts 단계가 계정을 만든다는 게 확인됩니다.</p>
<table>
<thead>
<tr>
<th>계정</th>
<th>계정 생성 시각</th>
<th>Pipeline 시작 시각</th>
</tr>
</thead>
<tbody><tr>
<td>network</td>
<td>2026-06-23 10:49</td>
<td>2026-06-23 10:46</td>
</tr>
<tr>
<td>seanson-workload-dev</td>
<td>2026-06-29 12:29</td>
<td>2026-06-29 12:26</td>
</tr>
<tr>
<td>seanson-sharedservice</td>
<td>2026-07-08 10:28</td>
<td>2026-07-08 10:25</td>
</tr>
</tbody></table>
<p>생성 시각은 <code>aws organizations list-accounts</code>의 <code>JoinedTimestamp</code>, 시작 시각은 Pipeline 실행 기록에서 가져왔습니다. 세 계정 모두 Pipeline이 시작되고 약 3분 뒤, Accounts 단계가 도는 시점에 생겼습니다. (<code>seanson-workload</code>는 Pipeline을 중지/재실행하던 도중에 생겨서 표에서 뺐습니다. 이 얘기도 겪은 문제에 있습니다.) yaml에 몇 줄 추가하고 zip을 올리는 것만으로 계정이 생긴다는 게 LZA를 쓰는 가장 큰 이유입니다.</p>
<pre><code class="language-bash">$ aws organizations list-accounts --query &quot;Accounts[].[Name,Status]&quot; --output table
-------------------------------------
|           ListAccounts            |
+------------------------+----------+
|  seanson-workload-dev  |  ACTIVE  |
|  seanson-sharedservice |  ACTIVE  |
|  seanson-org           |  ACTIVE  |
|  seanson-audit         |  ACTIVE  |
|  network               |  ACTIVE  |
|  seanson-workload      |  ACTIVE  |
|  seanson-logarchive    |  ACTIVE  |
+------------------------+----------+</code></pre>
<p><code>seanson-org</code>가 Management, <code>seanson-logarchive</code>/<code>seanson-audit</code>이 필수 계정이고 나머지 4개가 Workload 계정입니다. yaml의 <code>name</code>(예: <code>LogArchive</code>)과 실제 AWS 계정 이름(예: <code>seanson-logarchive</code>)이 달라도 됩니다. 필수 계정 description에도 &quot;the account name key does not need to match the AWS account name&quot;이라고 적혀 있습니다.</p>
<hr>
<h2 id="5-scp---조직-탈퇴-금지-region-제한">5. SCP - 조직 탈퇴 금지, Region 제한</h2>
<p>SCP(Service Control Policy)는 OU나 계정에 붙이는 &quot;상한선&quot; 정책입니다. IAM 정책이 무엇을 허용하든 SCP에서 막으면 할 수 없습니다. 단, <strong>관리(Management) 계정에는 SCP가 적용되지 않습니다.</strong> LZA에서는 <code>organization-config.yaml</code>의 <code>serviceControlPolicies</code>에 정책을 적고, 정책 본문은 JSON 파일로 zip에 같이 넣습니다.</p>
<h3 id="조직-탈퇴-금지-켜-둔-정책">조직 탈퇴 금지 (켜 둔 정책)</h3>
<p>가장 간단하고 거의 모든 조직에 넣어도 되는 정책입니다. 멤버 계정이 스스로 조직을 떠나지 못하게 합니다.</p>
<pre><code class="language-json">{
  &quot;Version&quot;: &quot;2012-10-17&quot;,
  &quot;Statement&quot;: [
    {
      &quot;Sid&quot;: &quot;DenyLeaveOrg&quot;,
      &quot;Effect&quot;: &quot;Deny&quot;,
      &quot;Action&quot;: &quot;organizations:LeaveOrganization&quot;,
      &quot;Resource&quot;: &quot;*&quot;
    }
  ]
}</code></pre>
<p>yaml 쪽은 앞의 diff에 나온 그대로입니다. <code>policy</code>에 JSON 파일 이름을, <code>deploymentTargets.organizationalUnits</code>에 붙일 OU를 적습니다. 배포 후 정책이 어디에 붙었는지 확인해 봤습니다.</p>
<pre><code class="language-bash">$ PID=$(aws organizations list-policies --filter SERVICE_CONTROL_POLICY --query &quot;Policies[?Name==\`DenyLeaveOrganization\`].Id&quot; --output text)
$ aws organizations list-targets-for-policy --policy-id $PID --query &quot;Targets[].[Name,Type]&quot; --output table
-------------------------------------------
|          ListTargetsForPolicy           |
+-----------------+-----------------------+
|  Sandbox        |  ORGANIZATIONAL_UNIT  |
|  Workload       |  ORGANIZATIONAL_UNIT  |
|  Infrastructure |  ORGANIZATIONAL_UNIT  |
|  Security       |  ORGANIZATIONAL_UNIT  |
+-----------------+-----------------------+</code></pre>
<p>yaml에 적은 OU 4개에 그대로 붙어 있습니다.</p>
<h3 id="region-제한-만들어-두고-꺼-둔-정책">Region 제한 (만들어 두고 꺼 둔 정책)</h3>
<p>두 번째는 허용한 Region 밖의 API 호출을 막는 정책입니다. 쓰지 않는 Region에 실수로 Resource를 만드는 일을 막아 줍니다.</p>
<pre><code class="language-json">{
  &quot;Version&quot;: &quot;2012-10-17&quot;,
  &quot;Statement&quot;: [
    {
      &quot;Sid&quot;: &quot;DenyUnapprovedRegions&quot;,
      &quot;Effect&quot;: &quot;Deny&quot;,
      &quot;NotAction&quot;: [
        &quot;iam:*&quot;,
        &quot;sts:*&quot;,
        &quot;account:*&quot;,
        &quot;aws-marketplace:*&quot;,
        &quot;support:*&quot;,
        &quot;trustedadvisor:*&quot;,
        &quot;route53:*&quot;,
        &quot;cloudfront:*&quot;,
        &quot;waf:*&quot;,
        &quot;wafv2:*&quot;,
        &quot;organizations:*&quot;,
        &quot;health:*&quot;,
        &quot;bedrock:CreateFoundationModelAgreement&quot;,
        &quot;bedrock:DeleteFoundationModelAgreement&quot;,
        &quot;bedrock:ListFoundationModelAgreementOffers&quot;,
        &quot;bedrock:GetFoundationModelAvailability&quot;
      ],
      &quot;Resource&quot;: &quot;*&quot;,
      &quot;Condition&quot;: {
        &quot;StringNotEquals&quot;: {
          &quot;aws:RequestedRegion&quot;: [
            &quot;us-east-1&quot;,
            &quot;us-east-2&quot;,
            &quot;us-west-1&quot;,
            &quot;us-west-2&quot;,
            &quot;ap-northeast-2&quot;
          ]
        },
        &quot;ArnNotLike&quot;: {
          &quot;aws:PrincipalARN&quot;: [
            &quot;arn:aws:iam::*:role/AWSControlTowerExecution&quot;,
            &quot;arn:aws:iam::*:role/AWSAccelerator*&quot;
          ]
        }
      }
    }
  ]
}</code></pre>
<p>이 정책을 쓸 때 놓치기 쉬운 부분이 두 가지 있습니다.</p>
<ul>
<li><code>NotAction</code>의 글로벌 Service: IAM, STS, Route 53, CloudFront, Organizations 같은 글로벌 Service는 요청이 us-east-1로 들어갑니다. 이걸 빼 두지 않으면 허용 Region 목록과 상관없이 막힐 수 있습니다.</li>
<li><code>ArnNotLike</code>의 배포 역할: Control Tower(<code>AWSControlTowerExecution</code>)와 LZA(<code>AWSAccelerator*</code>)가 쓰는 역할은 예외로 둡니다. 이 역할까지 막으면 LZA가 자기 Resource를 관리하지 못합니다.</li>
</ul>
<p>그런데 지금 이 정책은 <strong>꺼져 있습니다.</strong> 앞의 diff를 다시 보면 <code>DenyRegionsExceptAllowed</code> Block 전체가 주석 처리돼 있고, 위에 <code># Temporarily disabled for Bedrock Marketplace subscription</code>이라고 적어 뒀습니다. Bedrock에서 일부 Model을 쓰려면 AWS Marketplace 구독이 필요한데, 그 구독 작업을 하면서 이 정책을 잠시 꺼 두었습니다. JSON에 <code>aws-marketplace:*</code>와 Bedrock 약관 관련 Action이 예외로 들어 있는 것도 그 작업 때 넣은 것입니다. (Bedrock 자체는 따로 연재 중인 <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-1-%EC%B2%AB-%ED%98%B8%EC%B6%9C%EB%B6%80%ED%84%B0-Streaming%EA%B9%8C%EC%A7%80">Bedrock 시리즈</a>에서 다루고 있습니다.)</p>
<p>조직에 실제로 붙어 있는 SCP 목록을 보면 이 정책은 없습니다.</p>
<pre><code class="language-bash">$ aws organizations list-policies --filter SERVICE_CONTROL_POLICY --query &quot;Policies[].[Name,AwsManaged]&quot; --output table
------------------------------------
|           ListPolicies           |
+------------------------+---------+
|  DenyLeaveOrganization |  False  |
|  aws-guardrails-pxaOwo |  False  |
|  FullAWSAccess         |  True   |
|  aws-guardrails-iyjJZZ |  False  |
|  aws-guardrails-OFTBQq |  False  |
|  aws-guardrails-riIrGv |  False  |
+------------------------+---------+</code></pre>
<p><code>aws-guardrails-*</code>는 Control Tower가 컨트롤(가드레일)을 켜면서 만든 SCP이고, <code>FullAWSAccess</code>는 AWS 기본 정책입니다. LZA가 만든 건 <code>DenyLeaveOrganization</code> 하나입니다.</p>
<p>다시 켤 때 확인할 것도 하나 적어 둡니다. yaml의 description은 <code>us-east-1, us-west-2, ap-northeast-2</code> 3개 Region인데, JSON에는 5개 Region이 들어 있습니다. JSON만 고치고 description은 그대로 둬서 생긴 차이입니다. 실제로 적용되는 건 JSON이지만, 나중에 보는 사람은 description을 먼저 읽으니 켜기 전에 맞춰 둘 생각입니다.</p>
<hr>
<h2 id="6-겪은-문제들">6. 겪은 문제들</h2>
<p>43번 실행 중 실패 17번, 중지 5번이었습니다. 이 편 범위(조직/계정/SCP와 배포 흐름)에 해당하는 것만 골랐습니다. 날짜와 Error Message는 CodePipeline/CodeBuild 기록 그대로입니다.</p>
<h3 id="6-1-설치-직후-첫-실행-설정에-없는-ou-2026-06-22">6-1. 설치 직후 첫 실행: 설정에 없는 OU (2026-06-22)</h3>
<p>설치하고 처음 돈 Pipeline이 Prepare 단계에서 바로 실패했습니다.</p>
<pre><code class="language-text">Organizational Unit &#39;Sandbox&#39; with id of &#39;ou-xxxx-xxxxxxxx&#39; was not found in the organization configuration.</code></pre>
<p>Control Tower를 설정하면서 <code>Sandbox</code> OU가 생겼는데, LZA 기본 설정에는 <code>Security</code>와 <code>Infrastructure</code>만 있었기 때문입니다. <strong>LZA는 조직에 있는 OU가 전부 설정에 있어야 합니다.</strong> <code>organizationalUnits</code>에 <code>- name: Sandbox</code>를 넣는 것으로 해결했습니다.</p>
<h3 id="6-2-scp에-policy-field-누락-2026-06-23">6-2. SCP에 <code>policy</code> Field 누락 (2026-06-23)</h3>
<p>SCP를 처음 넣을 때 yaml만 쓰고 정책 파일을 연결하지 않았더니 Prepare 단계의 설정 검사에서 막혔습니다.</p>
<pre><code class="language-text">parsing organization-config failed Could not parse content in organization-config:

* /serviceControlPolicies/0 =&gt; must have required property &#39;policy&#39; (name,description,policy,type,deploymentTargets)
* /serviceControlPolicies/1 =&gt; must have required property &#39;policy&#39; (name,description,policy,type,deploymentTargets)</code></pre>
<p>SCP 한 개에는 <code>name</code>, <code>description</code>, <code>policy</code>, <code>type</code>, <code>deploymentTargets</code>가 모두 필요합니다. <code>policy</code>에는 zip 안의 JSON 파일 이름을 적고, 그 JSON 파일을 zip에 같이 넣어야 합니다. Error Message에 필수 항목이 다 나와 있어서 고치기는 쉬웠습니다. 이렇게 Prepare 단계에서 걸리면 2~3분 만에 실패가 나니, 오히려 다행인 실패였습니다.</p>
<h3 id="6-3-권한-세트-이름-충돌-2026-06-23">6-3. 권한 세트 이름 충돌 (2026-06-23)</h3>
<p>같은 날 Deploy 단계의 <code>Identity_Center</code>에서 실패했습니다.</p>
<pre><code class="language-text">CREATE_FAILED | AWS::SSO::PermissionSet | AwsAdministratorAccessIdentityCenterPermissionSet Resource handler returned message: &quot;PermissionSet with name AWSAdministratorAccess already exists.&quot;</code></pre>
<p>Control Tower가 IAM Identity Center에 <code>AWSAdministratorAccess</code>라는 권한 세트를 이미 만들어 두는데, <code>iam-config.yaml</code>에서 같은 이름으로 또 만들려고 했기 때문입니다. 지금 설정에서는 LZA가 만드는 권한 세트 이름을 <code>SeanAdminAccess</code>로 바꿔 두었습니다. Control Tower와 LZA를 같이 쓸 때는 <strong>Control Tower가 먼저 만든 Resource 이름과 겹치지 않는지</strong> 확인해야 합니다.</p>
<h3 id="6-4-중지하고-바로-재실행---stack-update-중-2026-06-24">6-4. 중지하고 바로 재실행 -&gt; Stack Update 중 (2026-06-24)</h3>
<p>실행 중인 Pipeline을 중지하고 곧바로 다시 실행했더니 Prepare 단계에서 실패했습니다.</p>
<pre><code class="language-text">Error: Stack:arn:aws:cloudformation:us-east-1:111122223333:stack/AWSAccelerator-PrepareStack-111122223333-us-east-1/... is in UPDATE_IN_PROGRESS state and can not be updated</code></pre>
<p>Pipeline을 &quot;중지&quot;해도 <strong>이미 시작된 CloudFormation Stack Update는 끝까지 진행됩니다.</strong> 앞 실행의 Stack Update가 끝나기 전에 새 실행이 같은 Stack을 건드리려다 막힌 것입니다. 2분쯤 뒤에 다시 시작한 실행은 성공했습니다. 중지한 뒤에는 CloudFormation Console에서 <code>AWSAccelerator-*</code> Stack이 <code>*_IN_PROGRESS</code> 상태를 벗어났는지 확인하고 재실행하는 게 안전합니다. 앞의 계정 생성 시각 표에서 <code>seanson-workload</code>를 뺀 것도 이 때문입니다. 계정이 생긴 시각이 중지/재실행 사이에 끼어 있어서 어느 실행이 만들었는지 딱 잘라 말할 수 없었습니다.</p>
<h3 id="6-5-설정-밖에서-만든-계정-2026-06-29">6-5. 설정 밖에서 만든 계정 (2026-06-29)</h3>
<p>Control Tower Console에서 계정 하나를 <code>Workload</code> OU에 등록해 둔 상태로 Pipeline을 돌렸더니 Prepare 단계에서 실패했습니다.</p>
<pre><code class="language-text">Found account with id 444455556666 in OU Workload that is not in the configuration.,Account with Id 444455556666 and email &lt;email&gt; is not in the accounts configuration and is not a member of an ignored OU.</code></pre>
<p>6-1과 같은 원리입니다. LZA가 관리하는 OU 안에 있는 계정은 전부 <code>accounts-config.yaml</code>에 있어야 합니다. Error Message가 알려 주는 대로 방법은 두 가지입니다.</p>
<ul>
<li>계정을 <code>accounts-config.yaml</code>의 <code>workloadAccounts</code>에 추가한다</li>
<li>LZA가 관리하지 않을 OU라면 <code>organization-config.yaml</code>에서 그 OU에 <code>ignore: true</code>를 준다</li>
</ul>
<p>LZA를 도입했다면 계정 생성은 Console이 아니라 설정 파일로 한다고 정해 두는 편이 편합니다.</p>
<h3 id="6-6-review-단계에서-직접-거절한-변경-2026-08-18">6-6. Review 단계에서 직접 거절한 변경 (2026-08-18)</h3>
<p>이건 실패라기보다 <strong>Review 단계가 제 역할을 한 사례</strong>입니다.</p>
<p>이 조직에는 관리 Event를 기록하는 CloudTrail 트레일이 3개 있었습니다. LZA의 조직 트레일, Control Tower의 조직 트레일, 그리고 관리 계정에만 있는 트레일 하나입니다. CloudTrail 관리 Event는 첫 번째 사본만 무료이고 추가 사본부터는 10만 건당 $2.00이 청구됩니다. 비용을 줄이려고 LZA 쪽 조직 트레일을 끄기로 하고, <code>global-config.yaml</code>에서 <code>organizationTrail: false</code>로 바꿔 올렸습니다.</p>
<p>Pipeline이 Review 단계에서 승인을 기다리는 동안 이 변경이 실제로 무엇을 지우는지 확인했습니다. <code>organizationTrail: false</code>로 바꾸면 트레일과 함께 LZA의 <code>Custom::EnableAwsServiceAccess</code> Resource도 삭제되는데, 이 Resource는 삭제될 때 <code>DisableAWSServiceAccess(cloudtrail.amazonaws.com)</code>를 호출합니다. 즉 <strong>Organizations에서 CloudTrail 신뢰 Access가 꺼지고, Control Tower의 조직 트레일까지 망가질 수 있습니다.</strong> 그래서 승인하지 않고 거절했습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/4038e46b-eddf-400c-9f08-704755a35997/image.png" alt="Review 단계에서 거절한 실행"></p>
<p>거절할 때 적은 사유가 그대로 실행 요약에 남습니다. 이후 방법을 바꿨습니다. 트레일은 그대로 두고 <strong>관리 Event 기록만 끄는</strong> 방식입니다.</p>
<pre><code class="language-yaml">  cloudtrail:
    enable: true
    organizationTrail: true
    organizationTrailSettings:
      multiRegionTrail: true
      globalServiceEvents: true
      managementEvents: false
      s3DataEvents: false
      lambdaDataEvents: true
      sendToCloudWatchLogs: false
      apiErrorRateInsight: false
      apiCallRateInsight: false</code></pre>
<p><code>lambdaDataEvents: true</code>는 일부러 남겼습니다. 관리 Event를 끄고 Data Event도 하나도 없으면 Event 선택기(event selector)가 0개가 되는데, 이 경우 CDK 합성(synth) 단계에서 실패합니다. 그래서 최소한의 선택기 하나로 Lambda Data Event를 남겨 뒀습니다. 다만 Data Event는 따로 과금되니 Lambda 호출이 많은 환경이라면 따져 보셔야 합니다. 이렇게 바꾼 15:36 실행은 성공했습니다.</p>
<p>이 경험 때문에 <strong>Review 단계(수동 승인)는 꼭 켜 두시길</strong> 권합니다. 설정 한 줄이 조직 전체에 영향을 주는 도구라서, 승인 전에 한 번 멈춰서 보는 단계가 있다는 게 생각보다 중요합니다.</p>
<hr>
<h2 id="정리">정리</h2>
<ul>
<li>LZA 설정은 S3의 <code>zipped/aws-accelerator-config.zip</code> 하나입니다. <strong>이 파일을 올리는 게 곧 배포</strong>이고, Pipeline은 Upload 1초 뒤에 시작됐습니다.</li>
<li>OU는 <code>organization-config.yaml</code>, 계정은 <code>accounts-config.yaml</code>에 적습니다. <strong>조직에 있는 OU와 계정은 전부 설정에 있어야</strong> 하고, 없으면 Prepare 단계에서 멈춥니다(6-1, 6-5).</li>
<li>SCP는 yaml + JSON 파일 조합입니다. 조직 탈퇴 금지는 부담 없이 켜 둘 만하고, Region 제한은 글로벌 Service와 배포 역할 예외를 꼭 챙겨야 합니다.</li>
<li>Control Tower가 먼저 만든 Resource(OU, 권한 세트 등)와 겹치지 않는지 확인합니다(6-1, 6-3).</li>
<li>Pipeline을 중지해도 CloudFormation은 계속 돕니다. Stack이 끝난 뒤 재실행합니다(6-4).</li>
<li>Review 단계는 켜 둡니다(6-6).</li>
</ul>
<p>다음 편에서는 원래 이번에 같이 다루려던 <strong>Network 구성</strong>(<code>network-config.yaml</code>)을 다룹니다. Transit Gateway 허브와 VPC 구성, 그리고 7월에 <code>Network_VPCs</code> 단계에서 실패했던 이야기와 안 쓰는 Region의 Network를 정리해 비용을 줄인 과정을 정리하겠습니다.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 Amazon Bedrock으로 나만의 AI 어시스턴트 만들기 (3) - iPhone App 만들기: SwiftUI + SSE]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-3-iPhone-App-%EB%A7%8C%EB%93%A4%EA%B8%B0-SwiftUI-SSE</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-3-iPhone-App-%EB%A7%8C%EB%93%A4%EA%B8%B0-SwiftUI-SSE</guid>
            <pubDate>Tue, 22 Sep 2026 12:14:25 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p>2편은 <code>curl</code>로 SSE Stream이 흘러나오는 Terminal 화면에서 끝났습니다.
그 화면을 보고 있으니 이걸 폰에서 보고 싶다는 생각이 먼저 들어서, 이번 편과 다음 편에서는 iPhone App을 붙입니다.
운영하면서 겪은 문제들(재시도, Timeout, 비용)은 App을 실제로 매일 써 봐야 만나는 것들이라, 먼저 쓸 수 있는 물건을 만들고 운영 이야기는 5편에서 하기로 했습니다.</p>
<p>이전 편: <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-2-%EB%8C%80%ED%99%94-%EA%B8%B0%EC%96%B5-%EB%8F%84%EA%B5%AC-%ED%98%B8%EC%B6%9C-SSE-Server">2편 - 대화 기억, 도구 호출, SSE Server</a></p>
<table>
<thead>
<tr>
<th>편</th>
<th>내용</th>
</tr>
</thead>
<tbody><tr>
<td>1편</td>
<td>Bedrock 기초: Model 선택, 첫 호출, Parameter, Token, System Prompt, Streaming</td>
</tr>
<tr>
<td>2편</td>
<td>대화 기억, 도구 호출, Prompt Caching, Extended Thinking, FastAPI + SSE Server</td>
</tr>
<tr>
<td>3편 (이 글)</td>
<td>iPhone App 만들기: Xcode Project, SwiftUI 채팅 화면, SSE Parsing</td>
</tr>
<tr>
<td>4편</td>
<td>iPhone App 마무리: Server 주소 설정, Local Network 권한, 실기기 설치, Markdown 표시</td>
</tr>
<tr>
<td>5편</td>
<td>Server를 밖으로: EC2 + ALB + HTTPS, 운영하면서 겪은 문제들</td>
</tr>
<tr>
<td>6편</td>
<td>도구를 MCP로 확장하고, 위험한 도구에는 사람 승인 단계 두기</td>
</tr>
<tr>
<td>7편</td>
<td>Token 원장과 비용 상한, Context 압축, 대화 저장(SQLite)</td>
</tr>
</tbody></table>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/2d456b95-ee26-4048-a229-542f0d5a3eee/image.png" alt="SeanChat 전체 구성. App은 Bedrock을 직접 부르지 않고 2편에서 만든 FastAPI Server에 붙는다"></p>
<p>구성은 위 그림이 전부입니다. App은 Thin Client입니다.
iPhone App은 Bedrock을 직접 부르지 않습니다. 2편 5장에서 만든 FastAPI Server에 HTTP로 붙고, 답은 SSE로 조금씩 받습니다.
AWS 자격증명은 Mac(나중엔 EC2)에만 있고, 폰에는 아무것도 들어가지 않습니다.
대화 기억(Message 배열)은 App이 들고 있습니다. 2편 1장에서 본 &quot;상태는 Server가 아니라 내 코드가 들고 있다&quot;가 그대로 이어집니다.</p>
<p>이렇게 나눠 두면 Model을 바꾸거나 도구를 붙이거나 Prompt를 고칠 때 App은 손대지 않고 Server만 고치면 됩니다.
제 SeanChat App도 올해 초 이후로 Server는 수십 번 바뀌었지만 App의 Network 코드는 거의 그대로입니다.</p>
<p>이번 편과 다음 편에서 만드는 파일입니다.</p>
<table>
<thead>
<tr>
<th>파일</th>
<th>줄 수</th>
<th>역할</th>
<th>편</th>
</tr>
</thead>
<tbody><tr>
<td><code>step12_server.py</code> (Mac)</td>
<td>56</td>
<td>2편 <code>step11_server.py</code>에 Multi-turn, System Prompt, Error Event 추가</td>
<td>3편</td>
</tr>
<tr>
<td><code>Message.swift</code></td>
<td>9</td>
<td>말풍선 하나</td>
<td>3편</td>
</tr>
<tr>
<td><code>ChatAPI.swift</code></td>
<td>62</td>
<td>Server와 통신하는 유일한 파일, SSE Parsing</td>
<td>3편</td>
</tr>
<tr>
<td><code>ChatViewModel.swift</code></td>
<td>44</td>
<td>상태와 보내기/중지</td>
<td>3편</td>
</tr>
<tr>
<td><code>ContentView.swift</code></td>
<td>101</td>
<td>채팅 화면</td>
<td>3편</td>
</tr>
<tr>
<td><code>SettingsView.swift</code></td>
<td>43</td>
<td>Server 주소 입력과 연결 Test</td>
<td>4편</td>
</tr>
<tr>
<td><code>Info.plist</code></td>
<td>-</td>
<td>Local Network 권한 문구</td>
<td>4편</td>
</tr>
</tbody></table>
<p>Swift는 다 합쳐 260줄 정도입니다. 저도 Swift는 이 App을 만들면서 처음 제대로 써 봤기 때문에, iOS 개발자라면 당연히 아는 내용도 하나씩 적었습니다.</p>
<p>Screenshot은 전부 2026년 9월에 macOS 26.5.1, Xcode 26.5, iPhone 17 Simulator(iOS 26.5)에서 실제로 돌린 것입니다. Server는 1·2편과 같은 개인 계정(us-east-2, Claude Haiku 4.5)입니다.</p>
<hr>
<h2 id="sse-간단히-보기">SSE 간단히 보기</h2>
<p>2편 5장에서 Server는 이렇게 내보냈습니다.</p>
<pre><code>data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;당&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;신의 이름은 Sean&quot;}

data: {&quot;type&quot;: &quot;done&quot;}</code></pre><p>App 쪽에서 SSE를 받는 건 생각보다 단순합니다.</p>
<ol>
<li>그냥 HTTP 응답입니다. Server가 연결을 끊지 않고 계속 써 내려갈 뿐이고, WebSocket처럼 별도 Protocol이 있는 게 아닙니다.</li>
<li>Event 하나는 <code>data:</code>로 시작하는 한 줄과 빈 줄입니다. 그래서 줄 단위로 읽어서 <code>data:</code>를 떼고 JSON을 Parsing하면 끝입니다.</li>
<li>iOS에는 이걸 위한 API가 이미 있습니다. <code>URLSession.bytes(for:)</code>가 응답을 Byte Stream으로 주고, 여기에 <code>.lines</code>를 붙이면 줄이 도착하는 대로 <code>for try await</code>로 받을 수 있습니다.</li>
</ol>
<p>저는 처음에 SSE Library부터 검색했는데, 결국 표준 API 두 개(<code>bytes(for:)</code>, <code>.lines</code>)로 끝났습니다. 이 글에서도 Library는 쓰지 않습니다.</p>
<hr>
<h2 id="0-사전-준비">0. 사전 준비</h2>
<h3 id="0-1-2편-환경-그대로">0-1. 2편 환경 그대로</h3>
<p>2편에서 쓴 파이썬 환경(venv, <code>boto3</code>, <code>fastapi</code>, <code>uvicorn</code>)과 자격증명이 그대로 필요합니다. 2편 5장의 <code>step11_server.py</code>가 돌아갔다면 준비는 끝난 겁니다.</p>
<pre><code class="language-bash">python -c &quot;import boto3, fastapi, uvicorn; print(&#39;ok&#39;)&quot;
aws sts get-caller-identity --query Account --output text</code></pre>
<p>1편에서 쓴 <code>us.anthropic.claude-haiku-4-5-…</code>가 지금도 호출 가능한지, 새 Model이 열렸는지는 <a href="https://hub.seanson.com/bedrock/">hub.seanson.com/bedrock</a>에서 확인할 수 있습니다. Bedrock Model과 Inference Profile 목록을 매일 자동으로 갱신하는 Page입니다.</p>
<h3 id="0-2-xcode">0-2. Xcode</h3>
<p>Mac App Store에서 Xcode를 설치합니다. 저는 26.5를 썼지만 Xcode 16 이상이면 이 글의 코드가 그대로 Build됩니다.
이 글에서 쓰는 <code>@Observable</code>, <code>ContentUnavailableView</code>가 iOS 17 이상 API라서 그보다 오래된 Xcode에서는 안 됩니다.
처음 실행하면 iOS Simulator 런타임 같은 추가 컴포넌트를 받는데, 수 GB라 시간이 좀 걸립니다. 저는 기다리는 동안 1장 Server 작업을 했습니다.</p>
<h3 id="0-3-apple-개발자-계정은-필요-없습니다">0-3. Apple 개발자 계정은 필요 없습니다</h3>
<p>Simulator에서 돌리는 데는 계정이 필요 없고, 이 글의 Screenshot도 전부 Simulator입니다.
실제 iPhone에 올릴 때도 Xcode에 본인 Apple ID로 Login하면 됩니다. 이 App은 내 폰에서 나만 쓰는 App이라 그 이상은 필요 없습니다. 실기기 설치는 4편에서 다룹니다.</p>
<hr>
<h2 id="1-backend-수정-step12_serverpy">1. Backend 수정: <code>step12_server.py</code></h2>
<p>2편의 <code>step11_server.py</code>는 <code>{&quot;prompt&quot;: &quot;...&quot;}</code> 한 문장만 받았습니다. App을 붙이려면 세 가지를 더해야 했습니다.</p>
<ol>
<li>Multi-turn: App이 대화 전체(<code>messages</code>)를 들고 옵니다. Server는 그걸 그대로 Bedrock에 넘기기만 합니다.</li>
<li>System Prompt: 1편 5장에서 본 그것입니다. App 이름과 말투를 여기서 정합니다.</li>
<li>Error를 SSE Event로: Model 호출이 실패하면 HTTP 500 대신 <code>{&quot;type&quot;: &quot;error&quot;}</code> Event를 흘려보냅니다. App이 빈 말풍선 대신 이유를 보여줄 수 있게 하려는 겁니다.</li>
</ol>
<pre><code class="language-python">&quot;&quot;&quot;3편: 2편의 step11_server.py에 세 가지만 더한다.
   1) 멀티턴: 앱이 대화 전체(messages)를 들고 온다 (2편 1장, 상태는 &#39;내&#39;가 들고 있다)
   2) 시스템 프롬프트 (1편 5장)
   3) 에러를 SSE 이벤트로 흘려보내기: 앱이 빈 말풍선 대신 이유를 보여줄 수 있게
&quot;&quot;&quot;
import json
import boto3
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

app = FastAPI()
runtime = boto3.client(&quot;bedrock-runtime&quot;, region_name=&quot;us-east-2&quot;)
MODEL = &quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;
SYSTEM = [{&quot;text&quot;: &quot;너는 SeanChat, 한국어로 답하는 개인 비서다. 간결하게 답한다.&quot;}]


class Msg(BaseModel):
    role: str          # &quot;user&quot; | &quot;assistant&quot;
    text: str


class ChatReq(BaseModel):
    messages: list[Msg]   # ← 앱이 대화 전체를 들고 온다


def sse(obj) -&gt; str:                       # SSE 프레이밍: &quot;data: {...}\n\n&quot;
    return f&quot;data: {json.dumps(obj, ensure_ascii=False)}\n\n&quot;


@app.get(&quot;/health&quot;)                        # 앱의 &#39;연결 테스트&#39; 버튼이 부른다
def health():
    return {&quot;ok&quot;: True, &quot;model&quot;: MODEL}


@app.post(&quot;/chat&quot;)
def chat(body: ChatReq):
    msgs = [{&quot;role&quot;: m.role, &quot;content&quot;: [{&quot;text&quot;: m.text}]}
            for m in body.messages if m.text.strip()]      # 빈 문자열은 Bedrock이 거부한다 (1편 Error 4번)

    def gen():
        try:
            resp = runtime.converse_stream(
                modelId=MODEL, system=SYSTEM, messages=msgs,
                inferenceConfig={&quot;maxTokens&quot;: 1000})
            for ev in resp[&quot;stream&quot;]:
                if &quot;contentBlockDelta&quot; in ev:
                    t = ev[&quot;contentBlockDelta&quot;][&quot;delta&quot;].get(&quot;text&quot;)
                    if t:
                        yield sse({&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: t})
                elif &quot;metadata&quot; in ev:
                    yield sse({&quot;type&quot;: &quot;usage&quot;, &quot;usage&quot;: ev[&quot;metadata&quot;][&quot;usage&quot;]})
        except Exception as e:                              # 모델 에러도 이벤트로: 앱이 이유를 보여준다
            yield sse({&quot;type&quot;: &quot;error&quot;, &quot;message&quot;: f&quot;{type(e).__name__}: {e}&quot;})
        yield sse({&quot;type&quot;: &quot;done&quot;})
    return StreamingResponse(gen(), media_type=&quot;text/event-stream&quot;)</code></pre>
<p><code>/health</code>는 App의 &quot;연결 Test&quot; 버튼이 부르려고 넣었습니다. 4편에서 실기기를 붙일 때 이게 있어서 편했습니다.</p>
<p>띄울 때는 <code>--host 0.0.0.0</code>을 꼭 붙입니다. 기본값 <code>127.0.0.1</code>로 띄우면 같은 Mac의 Simulator는 붙지만 실제 iPhone은 못 붙습니다.
저는 처음에 이걸 빼먹고 폰에서 &quot;Could not connect to the server&quot;를 한참 봤습니다.</p>
<pre><code class="language-bash">uvicorn step12_server:app --host 0.0.0.0 --port 8599</code></pre>
<p>App을 만들기 전에 <code>curl</code>로 새 형식(<code>messages</code> 배열)이 잘 받아지는지 먼저 확인했습니다. 2편 1장의 &quot;이름 기억하기&quot;를 그대로 던졌습니다.</p>
<pre><code class="language-bash">curl -N -s http://127.0.0.1:8599/chat -H &#39;Content-Type: application/json&#39; -d &#39;{
  &quot;messages&quot;: [
    {&quot;role&quot;: &quot;user&quot;,      &quot;text&quot;: &quot;내 이름은 Sean이야&quot;},
    {&quot;role&quot;: &quot;assistant&quot;, &quot;text&quot;: &quot;반갑습니다, Sean님.&quot;},
    {&quot;role&quot;: &quot;user&quot;,      &quot;text&quot;: &quot;내 이름이 뭐라고?&quot;}
  ]}&#39;</code></pre>
<pre><code>data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;당&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;신의 이름은 Sean&quot;}

data: {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;입니다.&quot;}

data: {&quot;type&quot;: &quot;usage&quot;, &quot;usage&quot;: {&quot;inputTokens&quot;: 81, &quot;outputTokens&quot;: 17, &quot;totalTokens&quot;: 98}}

data: {&quot;type&quot;: &quot;done&quot;}</code></pre><p>App이 Parsing해야 하는 Event는 <code>text</code>, <code>usage</code>, <code>error</code>, <code>done</code> 네 종류입니다. 이 몇 줄이 App과 Server 사이의 약속 전부입니다.</p>
<hr>
<h2 id="2-xcode-project-만들기">2. Xcode Project 만들기</h2>
<p>Xcode를 열고 Create New Project를 누릅니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/3632889f-3f2a-431e-a709-eefd7db88db9/image.png" alt="Xcode 시작 화면: Create New Project"></p>
<p>Template은 iOS 탭의 App입니다. 다른 건 고르지 않습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/296d141d-2f2b-45db-8430-ea1f861c092f/image.png" alt="Template 선택: iOS 탭의 App"></p>
<p>Option 화면에는 이렇게 넣었습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/3053aa34-4bd5-4ab3-90f1-fa76b487b7ed/image.png" alt="Project Option: SwiftUI / Swift / Storage None / Testing None"></p>
<table>
<thead>
<tr>
<th>항목</th>
<th>값</th>
<th>이유</th>
</tr>
</thead>
<tbody><tr>
<td>Product Name</td>
<td><code>SeanChat</code></td>
<td>App 이름. 원하는 이름으로</td>
</tr>
<tr>
<td>Team</td>
<td>본인 Apple ID (없으면 None)</td>
<td>Simulator만 쓰면 None으로도 됩니다. 저는 계정이 연결돼 있어서 제 이름이 뜹니다</td>
</tr>
<tr>
<td>Organization Identifier</td>
<td><code>com.sean-chloe</code></td>
<td>역방향 Domain. Bundle ID가 <code>com.sean-chloe.SeanChat</code>이 됩니다</td>
</tr>
<tr>
<td>Interface</td>
<td>SwiftUI</td>
<td>UIKit 아님</td>
</tr>
<tr>
<td>Language</td>
<td>Swift</td>
<td></td>
</tr>
<tr>
<td>Testing System</td>
<td>None</td>
<td>이번 편에서는 Test를 안 씁니다</td>
</tr>
<tr>
<td>Storage</td>
<td>None</td>
<td>SwiftData, Core Data 안 씁니다. 대화는 메모리에만</td>
</tr>
</tbody></table>
<p>저장 위치를 고르면 Project가 열립니다. 왼쪽에 <code>SeanChatApp.swift</code>와 <code>ContentView.swift</code>가 자동으로 만들어져 있습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/0f2ccba7-27f9-4a11-b8df-4c0e5697daa0/image.png" alt="Project 생성 직후: ContentView.swift와 오른쪽 미리보기(Canvas)"></p>
<p>이 상태에서 상단의 실행(▶) 버튼을 누르면 Simulator가 뜨고 &quot;Hello, world!&quot;가 나옵니다. 여기까지 확인하고 넘어갑니다. 첫 Build는 Simulator 부팅까지 포함해서 2분 정도 걸렸습니다.</p>
<p>Xcode 16부터 바뀐 게 하나 있습니다. 왼쪽 파일 목록의 <code>SeanChat</code> 폴더가 디스크 폴더와 자동으로 동기화됩니다(Xcode 15까지의 &quot;그룹&quot;과 다릅니다).
그래서 Finder나 Terminal에서 <code>.swift</code> 파일을 폴더에 넣으면 그냥 Project에 포함되고, 이 글의 파일들도 그렇게 넣었습니다.
대신 이것 때문에 <code>Info.plist</code>에서 한 번 막혔는데, 그 이야기는 4편에서 합니다.</p>
<hr>
<h2 id="3-swift-파일-4개-만들기">3. Swift 파일 4개 만들기</h2>
<p><code>SeanChat</code> 폴더 안에 파일을 하나씩 만듭니다. Xcode에서 폴더를 우클릭하고 New File from Template…에서 Swift File을 고르거나, Finder에서 <code>.swift</code> 파일을 폴더에 넣어도 됩니다(2장 끝 참고).</p>
<h3 id="3-1-messageswift">3-1. <code>Message.swift</code></h3>
<pre><code class="language-swift">import Foundation

/// 말풍선 하나. role은 백엔드(Bedrock)와 같은 단어를 쓴다: user / assistant
struct Message: Identifiable, Equatable {
    enum Role: String, Codable { case user, assistant }
    let id = UUID()
    let role: Role
    var text: String
}</code></pre>
<p><code>role</code>을 <code>user</code> / <code>assistant</code>로 둔 건 Bedrock이 쓰는 단어와 맞추려고입니다. 그러면 Server에서 따로 변환할 게 없습니다. 1편 2장의 <code>messages</code> 배열에 들어가던 그 <code>role</code>입니다.
<code>text</code>만 <code>var</code>인 건 Streaming 때문입니다. Model 말풍선을 빈 문자열로 만들어 두고, 조각이 올 때마다 뒤에 붙입니다.</p>
<h3 id="3-2-chatapiswift">3-2. <code>ChatAPI.swift</code></h3>
<p>이번 편에서 제일 중요한 파일입니다. 62줄인데 실제로 SSE를 읽는 부분은 열 줄이 안 됩니다.</p>
<pre><code class="language-swift">import Foundation

/// 백엔드(step12_server.py)와 이야기하는 유일한 파일.
///   GET  /health → 연결 테스트
///   POST /chat   → SSE 스트림 (&quot;data: {...}&quot; 한 줄이 이벤트 하나)
struct ChatAPI {
    let baseURL: URL

    struct WireMessage: Encodable { let role: String; let text: String }
    struct Event: Decodable { let type: String; let text: String?; let message: String? }
    struct Health: Decodable { let ok: Bool; let model: String }

    enum ChatError: LocalizedError {
        case http(Int), server(String)
        var errorDescription: String? {
            switch self {
            case .http(let code):  return &quot;서버가 HTTP \(code)를 돌려줬습니다&quot;
            case .server(let msg): return &quot;서버 오류: \(msg)&quot;
            }
        }
    }

    func health() async throws -&gt; Health {
        let (data, _) = try await URLSession.shared.data(from: baseURL.appending(path: &quot;health&quot;))
        return try JSONDecoder().decode(Health.self, from: data)
    }

    /// 대화 전체를 보내고, 모델이 뱉는 글자 조각(delta)을 순서대로 흘려준다
    func stream(_ messages: [Message]) -&gt; AsyncThrowingStream&lt;String, Error&gt; {
        AsyncThrowingStream { continuation in
            let task = Task {
                do {
                    var req = URLRequest(url: baseURL.appending(path: &quot;chat&quot;))
                    req.httpMethod = &quot;POST&quot;
                    req.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)
                    req.timeoutInterval = 120
                    let wire = messages.map { WireMessage(role: $0.role.rawValue, text: $0.text) }
                    req.httpBody = try JSONEncoder().encode([&quot;messages&quot;: wire])

                    let (bytes, response) = try await URLSession.shared.bytes(for: req)
                    let status = (response as? HTTPURLResponse)?.statusCode ?? 0
                    guard status == 200 else { throw ChatError.http(status) }

                    for try await line in bytes.lines {              // 줄 단위로 도착하는 대로 읽는다
                        guard line.hasPrefix(&quot;data: &quot;) else { continue }
                        let ev = try JSONDecoder().decode(Event.self, from: Data(line.dropFirst(6).utf8))
                        switch ev.type {
                        case &quot;text&quot;:  if let t = ev.text { continuation.yield(t) }
                        case &quot;error&quot;: throw ChatError.server(ev.message ?? &quot;unknown&quot;)
                        case &quot;done&quot;:  continuation.finish(); return
                        default:      break                          // usage 등은 지금은 무시
                        }
                    }
                    continuation.finish()
                } catch {
                    continuation.finish(throwing: error)
                }
            }
            continuation.onTermination = { _ in task.cancel() }     // 화면에서 &#39;중지&#39;하면 요청도 끊는다
        }
    }
}</code></pre>
<p>위에서부터 순서대로 보겠습니다.</p>
<p>1) 요청 만들기
<code>URLRequest</code>에 <code>POST</code>, JSON Header, 본문을 넣습니다. 본문은 <code>{&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;text&quot;: &quot;...&quot;}, ...]}</code>로, 1장에서 <code>curl</code>로 보낸 것과 같은 모양입니다.
<code>Message</code>를 그대로 Encoding하지 않고 <code>WireMessage</code>로 한 번 옮기는 건 <code>id</code>(UUID)를 Server에 보내지 않기 위해서입니다.
<code>timeoutInterval = 120</code>은 기본값 60초를 늘린 겁니다. 이 값은 전체 시간이 아니라 Data가 안 오는 상태가 이어지는 시간입니다. Streaming 중에는 조각이 계속 오니 상관없고, 첫 글자가 나오기 전에 Model이 오래 생각하는 경우(2편 4장 Extended Thinking)를 생각해서 여유를 뒀습니다.</p>
<p>2) <code>bytes(for:)</code>
보통 쓰는 <code>data(for:)</code>는 응답이 다 끝나야 돌아오기 때문에 Streaming에는 못 씁니다. <code>bytes(for:)</code>는 Header가 오는 즉시 돌아오고, 본문은 <code>AsyncSequence</code>로 뒤따라 흘러옵니다.</p>
<p>3) <code>.lines</code>
Byte Sequence에 <code>.lines</code>를 붙이면 개행 단위로 잘라서 <code>String</code>으로 줍니다. SSE는 줄 단위 Protocol이라 이게 그대로 Parser가 됩니다. <code>&quot;data: &quot;</code>로 시작하지 않는 줄(빈 줄)은 버리고, 나머지는 앞 6글자를 떼고 JSON으로 Decoding합니다.</p>
<p>4) Event 분기
<code>text</code>면 조각을 내보내고(<code>yield</code>), <code>error</code>면 던지고, <code>done</code>이면 끝냅니다. <code>usage</code>는 지금은 무시합니다. Token 표시는 7편에서 다룹니다.</p>
<p>5) <code>AsyncThrowingStream</code>
이 함수는 호출한 쪽에 &quot;글자 조각이 흘러나오는 Sequence&quot;를 돌려줍니다. ViewModel은 <code>for try await chunk in api.stream(...)</code>으로 받기만 하면 되고, Network 코드는 이 파일 밖으로 나가지 않습니다.</p>
<p>6) <code>onTermination</code>
화면에서 중지(■)를 눌러 Sequence를 끊으면 이 Closure가 불리고, 안에서 돌던 <code>Task</code>를 취소합니다. 그러면 <code>bytes.lines</code> Loop가 <code>CancellationError</code>로 빠져나오고 Socket이 닫힙니다.
이걸 빼먹으면 화면은 멈춰도 요청은 끝까지 살아서 Token을 계속 씁니다. 제 SeanChat 초기 Version이 딱 그랬습니다. 중지를 눌렀는데 Server Log를 보니 Model이 계속 답하고 있었습니다.</p>
<p><code>health()</code>를 따로 둔 건 4편의 설정 화면에 있는 &quot;연결 Test&quot; 버튼 때문입니다. 실기기가 Mac에 안 붙을 때 문제가 주소인지, 방화벽인지, Server인지를 채팅을 보내 보지 않고도 알 수 있습니다.</p>
<h3 id="3-3-chatviewmodelswift">3-3. <code>ChatViewModel.swift</code></h3>
<p>화면이 보여줄 상태(<code>messages</code>, <code>input</code>, <code>isStreaming</code>, <code>errorText</code>)와 보내기, 중지, 지우기 세 동작이 들어 있습니다.</p>
<pre><code class="language-swift">import SwiftUI
import Observation

/// 화면 상태 + 보내기/중지.
/// 대화 이력(messages)은 앱이 들고 있다. 서버는 아무것도 기억하지 않는다 (2편 1장)
@Observable @MainActor
final class ChatViewModel {
    var messages: [Message] = []
    var input = &quot;&quot;
    var isStreaming = false
    var errorText: String?
    private var task: Task&lt;Void, Never&gt;?

    static let defaultServer = &quot;http://127.0.0.1:8599&quot;
    var serverURL: String { UserDefaults.standard.string(forKey: &quot;serverURL&quot;) ?? Self.defaultServer }

    func send() {
        let text = input.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !text.isEmpty, !isStreaming else { return }
        guard let url = URL(string: serverURL) else { errorText = &quot;서버 주소가 이상합니다: \(serverURL)&quot;; return }

        input = &quot;&quot;
        errorText = nil
        messages.append(Message(role: .user, text: text))
        messages.append(Message(role: .assistant, text: &quot;&quot;))   // 빈 말풍선을 먼저 만들어 두고
        let history = Array(messages.dropLast())                // 그 빈 말풍선은 빼고 서버에 보낸다
        isStreaming = true

        task = Task {
            defer { isStreaming = false }
            do {
                for try await delta in ChatAPI(baseURL: url).stream(history) {
                    messages[messages.count - 1].text += delta    // 조각이 올 때마다 마지막 말풍선에 붙인다
                }
            } catch {
                errorText = error.localizedDescription
                if messages.last?.text.isEmpty == true { messages.removeLast() }  // 한 글자도 못 받았으면 빈 말풍선 제거
            }
        }
    }

    func stop() { task?.cancel() }                 // 지금까지 받은 글자는 그대로 남는다
    func clear() { stop(); messages.removeAll(); errorText = nil }
}</code></pre>
<p>이 파일에서 제일 중요한 건 빈 말풍선을 먼저 만드는 순서입니다.
보내기를 누르면 내 말풍선을 붙이고, Model 말풍선을 빈 문자열로 하나 더 붙인 다음, 그 빈 것만 빼고 Server에 보냅니다.
그리고 조각이 올 때마다 <code>messages[messages.count - 1].text += delta</code>로 마지막 말풍선에 이어 붙입니다.
<code>messages</code>가 바뀌면 SwiftUI가 알아서 다시 그리니까, 타이핑되는 것처럼 보이는 효과는 이 한 줄이 전부입니다.</p>
<p>Class에는 <code>@Observable</code>과 <code>@MainActor</code>를 같이 붙였습니다.</p>
<p><code>@Observable</code>(iOS 17+)은 Property가 바뀌면 그걸 읽는 View만 다시 그려 줍니다. 예전 방식(<code>ObservableObject</code> + <code>@Published</code>)보다 코드가 짧습니다.
iOS 17 API라서 Project 설정의 Minimum Deployments를 <code>iOS 17.0</code>으로 두었습니다. 기본값은 Xcode Version에 따라 18이나 26으로 잡혀 있는데, 낮추는 건 자유입니다.</p>
<p><code>@MainActor</code>는 이 Class의 코드가 전부 메인 Thread에서 돈다고 선언하는 겁니다. Network <code>Task</code> 안에서 <code>messages</code>를 고치는데, UI 상태는 메인 Thread에서만 건드려야 하니 이 한 줄로 Compiler가 대신 지켜 줍니다.
참고로 Xcode 26이 만든 새 Project는 Build 설정에 <code>Default Actor Isolation = MainActor</code>가 켜져 있어서 안 붙여도 같은 뜻이 됩니다. Xcode 16에는 이 설정이 없어서 빼면 동시성 경고나 Error가 나니, 어느 쪽에서든 되도록 명시해 두었습니다.</p>
<p><code>stop()</code>은 <code>task?.cancel()</code> 한 줄입니다. 취소 신호가 <code>ChatAPI</code>의 <code>onTermination</code>까지 전달돼서 Socket이 닫힙니다(3-2의 6번). 그때까지 받은 글자는 지우지 않고 그대로 둡니다.
<code>catch</code> Block에는 한 글자도 못 받았으면 빈 말풍선을 지우는 처리를 넣었습니다. Server가 꺼져 있을 때 &quot;…&quot; 말풍선만 덩그러니 남는 게 보기 싫어서인데, 4편의 Error Screenshot에서 이 동작이 보입니다.</p>
<h3 id="3-4-contentviewswift">3-4. <code>ContentView.swift</code></h3>
<p>자동으로 만들어진 <code>ContentView.swift</code>의 내용을 전부 지우고 아래로 바꿉니다. 101줄이지만 말풍선 목록, 입력창, 말풍선 하나, 이렇게 세 덩어리입니다.</p>
<pre><code class="language-swift">import SwiftUI

struct ContentView: View {
    @State private var vm = ChatViewModel()
    @State private var showSettings = false

    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                messageList
                if let err = vm.errorText {
                    Text(err).font(.footnote).foregroundStyle(.red)
                        .padding(.horizontal).padding(.bottom, 4)
                }
                inputBar
            }
            .navigationTitle(&quot;SeanChat&quot;)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button(&quot;지우기&quot;, systemImage: &quot;trash&quot;) { vm.clear() }
                        .disabled(vm.messages.isEmpty)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button(&quot;설정&quot;, systemImage: &quot;gearshape&quot;) { showSettings = true }
                }
            }
            .sheet(isPresented: $showSettings) { SettingsView() }
        }
    }

    // MARK: 말풍선 목록
    private var messageList: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(spacing: 12) {
                    if vm.messages.isEmpty {
                        ContentUnavailableView(&quot;무엇이든 물어보세요&quot;,
                                               systemImage: &quot;bubble.left.and.text.bubble.right&quot;,
                                               description: Text(&quot;Mac에서 step12_server.py가 켜져 있어야 합니다&quot;))
                            .padding(.top, 80)
                    }
                    ForEach(vm.messages) { BubbleView(message: $0) }
                    Color.clear.frame(height: 1).id(&quot;bottom&quot;)
                }
                .padding()
            }
            .scrollDismissesKeyboard(.interactively)
            .onChange(of: vm.messages.last?.text) {            // 글자가 늘어날 때마다 바닥으로
                proxy.scrollTo(&quot;bottom&quot;, anchor: .bottom)
            }
        }
    }

    // MARK: 입력창
    private var inputBar: some View {
        HStack(alignment: .bottom, spacing: 8) {
            TextField(&quot;메시지&quot;, text: $vm.input, axis: .vertical)
                .lineLimit(1...5)
                .textFieldStyle(.roundedBorder)
            if vm.isStreaming {
                Button { vm.stop() } label: { Image(systemName: &quot;stop.circle.fill&quot;).font(.title) }
            } else {
                Button { vm.send() } label: { Image(systemName: &quot;arrow.up.circle.fill&quot;).font(.title) }
                    .disabled(vm.input.trimmingCharacters(in: .whitespaces).isEmpty)
            }
        }
        .padding()
        .background(.bar)
    }
}

/// 말풍선 하나: 내 말은 오른쪽 파란색, 모델 말은 왼쪽 회색
struct BubbleView: View {
    let message: Message
    private var isUser: Bool { message.role == .user }

    /// **굵게**, *기울임*, `코드` 같은 인라인 마크다운만 해석한다 (한 줄 개선)
    private var attributed: AttributedString {
        (try? AttributedString(markdown: message.text,
                               options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)))
        ?? AttributedString(message.text)
    }

    var body: some View {
        HStack {
            if isUser { Spacer(minLength: 48) }
            Text(message.text.isEmpty ? AttributedString(&quot;…&quot;) : attributed)
                .padding(.horizontal, 14).padding(.vertical, 10)
                .background(isUser ? Color.accentColor : Color(.secondarySystemBackground),
                            in: RoundedRectangle(cornerRadius: 18))
                .foregroundStyle(isUser ? .white : .primary)
                .textSelection(.enabled)
            if !isUser { Spacer(minLength: 48) }
        }
    }
}

#Preview {
    ContentView()
}</code></pre>
<p>위에서부터 보겠습니다.</p>
<p><code>@State private var vm = ChatViewModel()</code>: <code>@Observable</code> Class는 <code>@StateObject</code>가 아니라 <code>@State</code>로 들고 있습니다. 이 화면이 살아 있는 동안 ViewModel도 같이 살아 있습니다.</p>
<p><code>ScrollViewReader</code> + <code>id(&quot;bottom&quot;)</code>: 목록 맨 끝에 높이 1짜리 투명 View를 두고, <code>messages.last?.text</code>가 바뀔 때마다(글자가 한 조각 붙을 때마다) 그 위치로 Scroll합니다. Streaming 중에 답이 길어져도 화면이 따라 내려가는 건 이 세 줄 덕분입니다. 배열 전체를 감시해도 되지만 Streaming 중에 바뀌는 건 항상 마지막 말풍선의 글자라서 그것만 봅니다.</p>
<p><code>ContentUnavailableView</code>: Message가 없을 때 보이는 빈 화면입니다(iOS 17+). 안내 문구에 &quot;Mac에서 step12_server.py가 켜져 있어야 합니다&quot;를 넣었습니다. 몇 달 뒤의 제가 Server는 안 켜고 App만 켜서 헤맬 게 뻔해서입니다.</p>
<p>입력창: <code>TextField(..., axis: .vertical)</code>와 <code>lineLimit(1...5)</code>로 여러 줄 입력이 됩니다. Streaming 중에는 보내기(↑) 대신 중지(■) 버튼이 나오는데, 버튼 하나를 상태에 따라 바꾸는 게 아니라 <code>if vm.isStreaming</code>으로 아예 다른 버튼을 그립니다.</p>
<p><code>BubbleView</code>: 내 말은 오른쪽 파란색, Model 말은 왼쪽 회색입니다. 반대쪽에 <code>Spacer(minLength: 48)</code>를 둬서 말풍선이 화면 폭을 다 차지하지 않게 했습니다. Text가 비어 있으면(첫 조각이 오기 전) &quot;…&quot;을 보여 줍니다. <code>attributed</code> Property는 4편에서 설명합니다. 처음 만들 땐 <code>Text(message.text)</code> 한 줄이었습니다.</p>
<p>여기까지 하면 Build가 거의 됩니다. <code>SettingsView</code>가 아직 없어서 Error가 나는데, 임시로 <code>.sheet(...)</code> 줄을 주석 처리하거나 4편의 <code>SettingsView.swift</code>를 먼저 만들어 두면 됩니다. 저는 후자로 했습니다.</p>
<hr>
<h2 id="4-simulator에서-첫-실행">4. Simulator에서 첫 실행</h2>
<p>Mac에서 Server를 켜 둔 상태로(1장), Xcode 상단에서 Simulator(iPhone 17)를 고르고 ▶를 누릅니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/e2651269-ce6d-4e5f-9d8d-07ee6bdafdef/image.png" alt="첫 실행: 빈 화면. 상단에 지우기·설정, 하단에 입력창"></p>
<p>기본 Server 주소는 <code>http://127.0.0.1:8599</code>입니다. Simulator는 Mac과 Network를 공유하기 때문에 이 주소로 바로 붙습니다. 별도 설정 없이 첫 질문을 보냈습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/b336896a-42f4-4ed4-a491-f93e76223676/image.png" alt="Streaming: &quot;…&quot;(첫 조각 대기) -&gt; &quot;Amazon&quot; -&gt; 문장 중간 -&gt; 완성. 마지막 장에서 ■가 ↑로 돌아온다"></p>
<p>2편 5장의 <code>curl</code> 출력이 그대로 말풍선에 타이핑되는 게 보입니다.
보내기를 누르면 빈 말풍선에 &quot;…&quot;이 먼저 뜨고, 첫 조각 <code>&quot;Amazon&quot;</code>이 도착하는 순간 &quot;…&quot;이 사라지고, 그 뒤로 조각이 붙는 대로 말풍선이 커집니다.
연속 캡처 30장 중에서 내용이 달라진 4장만 골랐고, 실제로는 2초가 안 걸립니다.</p>
<p>두 번째 질문에서 확인하고 싶었던 건 기억이었습니다. Server는 아무것도 저장하지 않습니다(1장 코드에 상태가 없습니다). 그런데 App이 매 요청에 대화 전체를 실어 보내니까 Model 입장에서는 이어지는 대화입니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/af4d0c07-1d8d-4656-9c21-902acd8c8c12/image.png" alt="Multi-turn: 앞 대화의 조건(&quot;두 문장으로&quot;)을 다음 답에서 그대로 지킨다"></p>
<p>첫 질문에서 &quot;두 문장으로 설명해줘&quot;라고 한 조건을 두 번째 답이 정확히 짚어 냅니다(&quot;당신은 두 문장으로 설명하라고 했고 …&quot;).
2편 1장에서 파이썬 리스트로 했던 걸 이번엔 <code>[Message]</code> 배열로 했을 뿐이고 원리는 같습니다.
2편에서 본 비용 구조도 그대로입니다. 대화가 길어질수록 매 요청의 입력 Token이 늘어나는데, 이 App에는 아직 아무 대책이 없습니다. 이건 7편에서 다룹니다.</p>
<hr>
<h2 id="정리">정리</h2>
<table>
<thead>
<tr>
<th>장</th>
<th>한 것</th>
<th>파일</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Server에 Multi-turn, System Prompt, Error Event 추가</td>
<td><code>step12_server.py</code></td>
</tr>
<tr>
<td>2</td>
<td>Xcode Project 생성 (SwiftUI, Storage None)</td>
<td>-</td>
</tr>
<tr>
<td>3</td>
<td>Model, API(SSE Parsing), ViewModel, 화면</td>
<td><code>Message</code> <code>ChatAPI</code> <code>ChatViewModel</code> <code>ContentView</code></td>
</tr>
<tr>
<td>4</td>
<td>Simulator에서 Streaming, Multi-turn 확인</td>
<td>-</td>
</tr>
</tbody></table>
<p>이번 편에서 기억해 두면 좋은 것들입니다.</p>
<ol>
<li>SSE는 App 쪽에서 <code>bytes(for:)</code>와 <code>.lines</code> 두 개로 끝납니다. Library가 필요 없었습니다.</li>
<li>대화 기억은 App이 들고 있습니다. Server는 상태가 없어서 아무 때나 껐다 켜도 App은 모릅니다.</li>
<li>중지 버튼은 화면만 멈추면 안 되고, <code>onTermination</code>에서 요청까지 취소해야 Token이 안 샙니다.</li>
</ol>
<h2 id="다음-편-예고">다음 편 예고</h2>
<p>지금 App은 Simulator에서만 돕니다. 실제 iPhone에서 <code>127.0.0.1</code>은 폰 자기 자신이라 Mac에 붙지 못합니다.
4편에서는 Server 주소 설정 화면을 만들고, Local Network 권한과 <code>Info.plist</code> 문제를 해결해서 실기기에 올립니다. 그리고 답변에 <code>**굵게**</code>가 그대로 보이는 문제도 고쳐 보겠습니다.</p>
<p>다음 편: <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-4-iPhone-App-%EB%A7%88%EB%AC%B4%EB%A6%AC-%EC%84%A4%EC%A0%95-%ED%99%94%EB%A9%B4-%EC%8B%A4%EA%B8%B0%EA%B8%B0-Markdown">4편 - iPhone App 마무리: 설정 화면, 실기기, Markdown</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 Amazon Bedrock으로 나만의 AI 어시스턴트 만들기 (1) - 첫 호출부터 Streaming까지]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-1-%EC%B2%AB-%ED%98%B8%EC%B6%9C%EB%B6%80%ED%84%B0-Streaming%EA%B9%8C%EC%A7%80</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-1-%EC%B2%AB-%ED%98%B8%EC%B6%9C%EB%B6%80%ED%84%B0-Streaming%EA%B9%8C%EC%A7%80</guid>
            <pubDate>Sun, 20 Sep 2026 15:26:39 GMT</pubDate>
            <description><![CDATA[<h2 id="지금-쓰고-있는-모습">지금 쓰고 있는 모습</h2>
<p>이 시리즈에서 만드는 SeanChat을 요즘 실제로 쓰고 있는 화면입니다.
Terminal(CLI), 맥북 App, iPhone App이 모두 같은 Backend에 붙어 있어서 한쪽에서 시작한 대화를 다른 쪽에서 그대로 이어서 볼 수 있습니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/4fbc0108-362b-4f7c-9463-dd51c88565b5/image.png" alt="Terminal(CLI): 질문 -&gt; 셸 도구로 sw_vers, date 실행 -&gt; 답변 -&gt; Token 사용량"></p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/a46b933b-7e18-411d-b43a-2ce5c3a27b98/image.png" alt="맥북 App: iPhone App에서 보낸 대화가 사이드바와 본문에 그대로 보입니다 (에이전트와 다른 대화 목록은 가렸습니다)"></p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/4ad1a096-d87d-40dd-9534-3acb915875c1/image.png" alt="iPhone App: 날씨 질문 -&gt; 셸 도구 실행 -&gt; 답변 (시뮬레이터 화면)"></p>
<p>맥북 App은 iPhone App과 같은 Xcode Project에서 빌드합니다. iPhone 화면은 실기기가 아니라 시뮬레이터에서 찍었습니다.</p>
<h2 id="개요">개요</h2>
<p>이 글에서는 Amazon Bedrock으로 개인용 AI 어시스턴트를 처음부터 만들어 봅니다.
LangChain 같은 Framework 없이 boto3로 직접 호출하면서 Bedrock 기본 기능을 하나씩 확인합니다.</p>
<p>저는 올해 초부터 SeanChat이라는 개인 어시스턴트를 만들어서 쓰고 있습니다.
Terminal(CLI), 맥북 App, iPhone App이 같은 Backend에 붙고, Backend가 Bedrock의 Claude Model을 호출하는 구조입니다.
파일 읽기, 셸 명령, 웹 검색 같은 도구도 붙어 있어서 요즘은 거의 항상 켜놓고 씁니다.</p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/97b2193f-8479-4a8a-9d90-eb91257d68f3/image.png" alt="SeanChat CLI: 질문 -&gt; bash 도구 호출 -&gt; 답변 -&gt; Token 사용량"></p>
<p>처음에는 &quot;Bedrock 호출하는 게 어렵겠어?&quot; 싶었는데, Model ID를 그대로 넣었다가 거부당한 것부터 시작해서 생각보다 많이 헤맸습니다.
그때 하나씩 실험하면서 정리한 내용을 옮겨 봤습니다.</p>
<p>시리즈는 이렇게 진행할 예정입니다.</p>
<table>
<thead>
<tr>
<th>편</th>
<th>내용</th>
</tr>
</thead>
<tbody><tr>
<td>1편 (이 글)</td>
<td>Bedrock 기초: Model 선택, 첫 호출, Parameter, Token, System Prompt, Streaming</td>
</tr>
<tr>
<td>2편</td>
<td>대화 기억, 도구 호출, Prompt Caching, Extended Thinking, FastAPI + SSE Server</td>
</tr>
<tr>
<td>3편</td>
<td>iPhone App 만들기: Xcode Project, SwiftUI 채팅 화면, SSE Parsing</td>
</tr>
<tr>
<td>4편</td>
<td>iPhone App 마무리: Server 주소 설정, Local Network 권한, 실기기 설치, Markdown 표시</td>
</tr>
<tr>
<td>5편</td>
<td>Server를 밖으로: EC2 + ALB + HTTPS, 운영하면서 겪은 문제들</td>
</tr>
<tr>
<td>6편</td>
<td>도구를 MCP로 확장하고, 위험한 도구에는 사람 승인 단계 두기</td>
</tr>
<tr>
<td>7편</td>
<td>Token 원장과 비용 상한, Context 압축, 대화 저장(SQLite)</td>
</tr>
</tbody></table>
<p>이 글의 실행 결과는 전부 제 개인 계정(us-east-2)에서 2026년 9월에 실제로 돌린 출력입니다.
단계마다 파이썬 파일 하나씩이고, 이번 편 코드는 다 합쳐도 100줄 정도입니다.</p>
<hr>
<h2 id="시작-전에-용어-정리">시작 전에 용어 정리</h2>
<p>코드를 치기 전에 용어 몇 개만 짚고 가겠습니다. 이걸 알아야 Error Message가 읽힙니다.</p>
<table>
<thead>
<tr>
<th>용어</th>
<th>뜻</th>
<th>이 글에서</th>
</tr>
</thead>
<tbody><tr>
<td>Foundation Model(FM)</td>
<td>Claude, Nova, Llama 같은 Large Language Model</td>
<td>Claude Haiku 4.5를 주로 씀</td>
</tr>
<tr>
<td>Model ID</td>
<td>Model을 가리키는 문자열 (<code>anthropic.claude-haiku-4-5-...</code>)</td>
<td>1장에서 처음 막힌 곳</td>
</tr>
<tr>
<td>Inference Profile</td>
<td>여러 Region에 걸쳐 Model을 호출하는 Routing ID (<code>us.</code> / <code>global.</code> 접두어)</td>
<td>최신 Model은 이걸로만 호출 가능</td>
</tr>
<tr>
<td>Token</td>
<td>Model이 글을 처리하는 단위. 글자 수와 다름</td>
<td>4장에서 직접 재봄</td>
</tr>
<tr>
<td>System Prompt</td>
<td>Model에게 역할과 규칙을 주는 첫 지시문</td>
<td>5장</td>
</tr>
<tr>
<td>Context Window</td>
<td>한 번에 넣을 수 있는 Token 총량</td>
<td>대화가 길어지면 여기 부딪힘</td>
</tr>
<tr>
<td>Streaming</td>
<td>답변을 다 만든 뒤 보내지 않고 조각으로 흘려보내기</td>
<td>6장</td>
</tr>
<tr>
<td>도구 호출(Tool Use)</td>
<td>Model이 &quot;이 함수를 불러줘&quot;라고 요청하는 기능</td>
<td>2편</td>
</tr>
</tbody></table>
<p>Bedrock API는 크게 두 층으로 나뉩니다. 처음에 이것도 헷갈렸습니다.</p>
<pre><code>bedrock          ← 컨트롤 플레인: 모델 목록 조회, 액세스 관리 (aws bedrock list-foundation-models)
bedrock-runtime  ← 데이터 플레인: 실제로 모델에게 질문 (converse, converse_stream)</code></pre><p>boto3에서 <code>boto3.client(&quot;bedrock&quot;)</code>과 <code>boto3.client(&quot;bedrock-runtime&quot;)</code>은 서로 다른 Client입니다.
<code>bedrock</code> Client로 <code>converse</code>를 부르면 그런 메서드가 없다는 Error가 납니다.</p>
<hr>
<h2 id="0-사전-준비">0. 사전 준비</h2>
<h3 id="0-1-region-선택과-model-access">0-1. Region 선택과 Model Access</h3>
<p>Bedrock은 Region마다 쓸 수 있는 Model이 다릅니다. 저는 <code>us-east-2</code>(오하이오)를 씁니다.
서울(<code>ap-northeast-2</code>)도 되지만 새 Model이 미국 Region에 먼저 나오는 경우가 많아서, 개인 Project라면 미국 Region을 추천합니다.</p>
<p>먼저 Console에서 Model Access를 켜줍니다.</p>
<pre><code>Bedrock 콘솔 → 좌측 메뉴 맨 아래 Model access → Modify model access
→ 쓸 모델(Anthropic Claude ...) 체크 → Submit</code></pre><p>처음 쓰는 계정이면 몇 분 안에 <code>Access granted</code>로 바뀝니다.
이걸 안 켜고 호출하면 <code>AccessDeniedException</code>이 나는데, IAM 권한이 없을 때와 Message가 같아서 처음엔 구분이 잘 안 됩니다.
구분하는 방법은 글 마지막 Error 정리에 적어 두었습니다.</p>
<h3 id="0-2-자격증명-설정">0-2. 자격증명 설정</h3>
<p>방법은 두 가지가 있습니다.</p>
<table>
<thead>
<tr>
<th>방법</th>
<th>언제 쓰나</th>
<th>설정</th>
</tr>
</thead>
<tbody><tr>
<td>IAM Identity Center(SSO) 프로필</td>
<td>내 개발 머신에서 Console과 CLI를 같이 쓸 때</td>
<td><code>aws sso login --profile &lt;프로필&gt;</code></td>
</tr>
<tr>
<td>Bedrock API key</td>
<td>Server나 Container에 두고 계속 띄워둘 때</td>
<td>환경변수 하나로 끝</td>
</tr>
</tbody></table>
<p>저는 처음엔 SSO 프로필로 하다가 Backend를 EC2에 올리면서 두 번째 방법으로 바꿨습니다.
SSO Token은 몇 시간마다 만료돼서 계속 떠 있어야 하는 Server에는 맞지 않았습니다.</p>
<p>Bedrock은 Service 전용 자격증명(service-specific credential)을 지원합니다.
<code>AWS_BEARER_TOKEN_BEDROCK</code> 환경변수 하나만 있으면 boto3가 알아서 사용합니다.</p>
<pre><code class="language-bash"># 발급 (만료일이 있습니다. 상시 구동 서버라면 만료일을 캘린더에 걸어두세요)
aws iam create-service-specific-credential \
  --user-name &lt;Bedrock 전용 IAM 사용자&gt; \
  --service-name bedrock.amazonaws.com

# 사용
echo &#39;export AWS_BEARER_TOKEN_BEDROCK=&lt;발급된 키&gt;&#39; &gt; ~/.bedrock.env
chmod 600 ~/.bedrock.env &amp;&amp; source ~/.bedrock.env</code></pre>
<p>이 IAM 사용자에게는 아래 정도의 정책이면 충분합니다.</p>
<pre><code class="language-json">{
  &quot;Version&quot;: &quot;2012-10-17&quot;,
  &quot;Statement&quot;: [{
    &quot;Effect&quot;: &quot;Allow&quot;,
    &quot;Action&quot;: [
      &quot;bedrock:InvokeModel&quot;,
      &quot;bedrock:InvokeModelWithResponseStream&quot;,
      &quot;bedrock:Converse&quot;,
      &quot;bedrock:ConverseStream&quot;,
      &quot;bedrock:ListFoundationModels&quot;,
      &quot;bedrock:ListInferenceProfiles&quot;,
      &quot;bedrock:GetFoundationModelAvailability&quot;
    ],
    &quot;Resource&quot;: &quot;*&quot;
  }]
}</code></pre>
<p>자격증명이 잘 잡혔는지 보는 제일 빠른 방법은 그냥 한 번 호출해 보는 것입니다.
안 잡혀 있으면 이렇게 나옵니다.</p>
<pre><code>NoCredentialsError: Unable to locate credentials</code></pre><p>권한이 모자라면 아래처럼 나옵니다. 어떤 Action이 거부됐는지 Message에 그대로 적혀 있으니 <code>is not authorized to perform:</code> 뒤를 읽으면 됩니다.</p>
<pre><code>AccessDeniedException: User: arn:aws:iam::123456789012:user/bedrock-user is not authorized
to perform: bedrock:CountTokens on resource: arn:aws:bedrock:us-east-2::foundation-model/anthropic.claude-haiku-4-5-20251001-v1:0
because no identity-based policy allows the bedrock:CountTokens action</code></pre><p>이 Error는 글을 쓰다가 실제로 만났습니다. 4장에서 <code>count_tokens</code>를 써보려고 했는데 위 정책에 그 Action이 없었습니다.
Message에 적힌 대로 정책 <code>Action</code>에 <code>bedrock:CountTokens</code>를 추가하면 해결됩니다.
Bedrock Error는 Message가 친절한 편이라 끝까지 읽기만 해도 절반은 풀립니다.</p>
<h3 id="0-3-파이썬-환경">0-3. 파이썬 환경</h3>
<pre><code class="language-bash">mkdir bedrock-lab &amp;&amp; cd bedrock-lab
python3 -m venv .venv &amp;&amp; source .venv/bin/activate
pip install boto3 fastapi &quot;uvicorn[standard]&quot;</code></pre>
<p>boto3는 최신 버전으로 설치해 줍니다. Bedrock은 기능이 자주 추가돼서 오래된 boto3에는 Parameter 자체가 없는 경우가 있습니다.</p>
<hr>
<h2 id="1-호출할-수-있는-model-확인하기">1. 호출할 수 있는 Model 확인하기</h2>
<p>제일 먼저 이 Region에 어떤 Model이 있는지 조회했습니다.</p>
<pre><code class="language-bash">aws bedrock list-foundation-models --region us-east-2 \
  --query &quot;modelSummaries[?contains(modelId,&#39;claude&#39;)].modelId&quot; --output table</code></pre>
<pre><code>-----------------------------------------------
|            ListFoundationModels             |
+---------------------------------------------+
|  anthropic.claude-sonnet-4-20250514-v1:0    |
|  anthropic.claude-haiku-4-5-20251001-v1:0   |
|  anthropic.claude-sonnet-4-5-20250929-v1:0  |
|  anthropic.claude-opus-4-5-20251101-v1:0    |
|  anthropic.claude-sonnet-4-6                |
|  anthropic.claude-opus-4-6-v1               |
|  ...                                        |
+---------------------------------------------+</code></pre><p>목록에 나온 <code>anthropic.claude-haiku-4-5-20251001-v1:0</code>을 그대로 코드에 넣었더니 바로 Error가 났습니다.</p>
<pre><code>ValidationException: Invocation of model ID anthropic.claude-haiku-4-5-20251001-v1:0
with on-demand throughput isn&#39;t supported. Retry your request with the ID or ARN of
an inference profile that contains this model.</code></pre><p>목록에 있는데 왜 못 부르는지 처음엔 이해가 안 됐는데, Message를 읽어 보면 inference profile ID를 쓰라고 적혀 있습니다.
최신 Model은 한 Region에서만 처리하는 on-demand 호출을 막고 Cross-Region Inference Profile로만 열어 둔 경우가 많습니다.
Profile 목록은 따로 조회합니다.</p>
<pre><code class="language-bash">aws bedrock list-inference-profiles --region us-east-2 \
  --query &quot;inferenceProfileSummaries[?contains(inferenceProfileId,&#39;claude&#39;)].[inferenceProfileId,status]&quot; \
  --output table</code></pre>
<pre><code>----------------------------------------------------------------
|                     ListInferenceProfiles                    |
+----------------------------------------------------+---------+
|  us.anthropic.claude-haiku-4-5-20251001-v1:0       |  ACTIVE |
|  global.anthropic.claude-haiku-4-5-20251001-v1:0   |  ACTIVE |
|  us.anthropic.claude-sonnet-4-5-20250929-v1:0      |  ACTIVE |
|  global.anthropic.claude-sonnet-4-5-20250929-v1:0  |  ACTIVE |
|  us.anthropic.claude-sonnet-4-6                    |  ACTIVE |
|  ...                                               |         |
+----------------------------------------------------+---------+</code></pre><p>같은 Model에 접두어가 다른 ID가 두 개씩 있습니다.</p>
<table>
<thead>
<tr>
<th>접두어</th>
<th>의미</th>
<th>선택 기준</th>
</tr>
</thead>
<tbody><tr>
<td>(없음)</td>
<td>이 Region에서만 처리</td>
<td>최신 Model은 on-demand 미지원인 경우가 많음 -&gt; 위 Error</td>
</tr>
<tr>
<td><code>us.</code></td>
<td>미국 Region들 사이에서 Routing</td>
<td>기본으로 이걸 씀. Data가 미국 밖으로 안 나감</td>
</tr>
<tr>
<td><code>global.</code></td>
<td>전 세계 Region으로 Routing</td>
<td>가용성은 제일 좋지만 Data 처리 위치가 넓어짐. 규제가 있는 환경이면 확인 필요</td>
</tr>
</tbody></table>
<p>이 글에서는 전부 <code>us.anthropic.claude-haiku-4-5-20251001-v1:0</code>을 씁니다.
Haiku가 Claude 중에서 제일 빠르고 저렴해서 실험용으로 적당합니다.</p>
<p>Model ID는 코드 여기저기에 쓰지 말고 한 곳에 별칭으로 모아 두는 게 좋습니다.
저는 <code>{&quot;haiku&quot;: &quot;us.anthropic.claude-haiku-4-5-...&quot;, &quot;sonnet&quot;: &quot;us.anthropic.claude-sonnet-4-5-...&quot;}</code> 같은 딕셔너리 하나에 두고 설정에서는 별칭만 바꿉니다. 위 목록만 봐도 Model이 몇 달마다 바뀝니다.</p>
<p>참고로 위 두 명령(<code>list-foundation-models</code>, <code>list-inference-profiles</code>) 결과를 매일 자동으로 모아서 <a href="https://hub.seanson.com/bedrock/">hub.seanson.com/bedrock</a>에 정리해 두고 있습니다. 서울 Region에서 지금 호출 가능한 Model, on-demand/CRIS 구분, 버지니아엔 있는데 서울엔 없는 Model, 변경 이력 RSS가 있으니 글 작성 이후에 나온 Model은 여기서 확인하시면 됩니다.</p>
<hr>
<h2 id="2-첫-호출-converse-api와-응답-구조">2. 첫 호출: Converse API와 응답 구조</h2>
<p>Bedrock에서 Model을 부르는 방법은 두 가지입니다.</p>
<table>
<thead>
<tr>
<th>API</th>
<th>특징</th>
<th>언제</th>
</tr>
</thead>
<tbody><tr>
<td><code>InvokeModel</code></td>
<td>Model 제공사마다 body 형식이 다름 (Anthropic은 <code>anthropic_version</code>, Nova는 또 다른 형식)</td>
<td>특정 Model 전용 기능이 필요할 때</td>
</tr>
<tr>
<td><code>Converse</code></td>
<td>모든 Model에 같은 요청/응답 형식</td>
<td>보통은 이걸 씀</td>
</tr>
</tbody></table>
<p>특별한 이유가 없으면 <code>Converse</code>를 쓰면 됩니다. 나중에 Haiku에서 Sonnet으로, 또 Nova로 바꿔도 코드를 고칠 필요가 없습니다.</p>
<p><code>step2_converse.py</code>로 첫 호출을 해봅니다. 응답을 통째로 찍어서 구조를 확인합니다.</p>
<pre><code class="language-python">&quot;&quot;&quot;응답 전체를 그대로 찍어보기: 구조를 눈으로 익히는 게 먼저다&quot;&quot;&quot;
import boto3, json

runtime = boto3.client(&quot;bedrock-runtime&quot;, region_name=&quot;us-east-2&quot;)   # ← bedrock 아님, bedrock-runtime

resp = runtime.converse(
    modelId=&quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;,
    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;안녕! 한 문장으로 인사해줘.&quot;}]}],
    inferenceConfig={&quot;maxTokens&quot;: 100},
)
resp.pop(&quot;ResponseMetadata&quot;, None)              # HTTP 메타는 지우고 본문만
print(json.dumps(resp, ensure_ascii=False, indent=2))</code></pre>
<pre><code>$ python step2_converse.py
{
  &quot;output&quot;: {
    &quot;message&quot;: {
      &quot;role&quot;: &quot;assistant&quot;,
      &quot;content&quot;: [
        {
          &quot;text&quot;: &quot;안녕하세요, 반갑습니다! 😊&quot;
        }
      ]
    }
  },
  &quot;stopReason&quot;: &quot;end_turn&quot;,
  &quot;usage&quot;: {
    &quot;inputTokens&quot;: 26,
    &quot;outputTokens&quot;: 22,
    &quot;totalTokens&quot;: 48,
    &quot;cacheReadInputTokens&quot;: 0,
    &quot;cacheWriteInputTokens&quot;: 0
  },
  &quot;metrics&quot;: {
    &quot;latencyMs&quot;: 650
  }
}</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/19d8e1f9-aede-4e85-9a09-0d4c1e5d3ae8/image.png" alt="첫 호출 결과"></p>
<p>처음 성공했을 때 이 JSON을 한참 봤는데, 결국 이 시리즈 전체가 이 구조를 응용하는 것입니다.
요청과 응답 구조만 한 번 제대로 봐두면 됩니다.</p>
<h3 id="요청-구조">요청 구조</h3>
<pre><code class="language-python">messages=[
  {&quot;role&quot;: &quot;user&quot;,                     # user 또는 assistant, 반드시 번갈아
   &quot;content&quot;: [                        # ← 배열! 문자열이 아님
     {&quot;text&quot;: &quot;안녕! ...&quot;}             # 텍스트 블록. 이미지·문서 블록도 여기 들어감
   ]}
]</code></pre>
<p><code>content</code>가 문자열이 아니라 Block 배열이라 처음엔 번거로운데, 나중에 이미지나 문서, 도구 결과를 같은 자리에 넣어 보면 왜 이렇게 했는지 알게 됩니다.</p>
<h3 id="응답-구조">응답 구조</h3>
<table>
<thead>
<tr>
<th>경로</th>
<th>내용</th>
<th>어디에 쓰나</th>
</tr>
</thead>
<tbody><tr>
<td><code>output.message</code></td>
<td>요청과 같은 형식의 assistant Message</td>
<td>그대로 대화 기록에 append (2편)</td>
</tr>
<tr>
<td><code>output.message.content[]</code></td>
<td>응답 Block 배열 (<code>text</code>, <code>toolUse</code>, <code>reasoningContent</code>)</td>
<td>화면 출력</td>
</tr>
<tr>
<td><code>stopReason</code></td>
<td>왜 멈췄나: <code>end_turn</code> / <code>max_tokens</code> / <code>tool_use</code> / <code>stop_sequence</code></td>
<td>Loop 제어 (3장, 2편)</td>
</tr>
<tr>
<td><code>usage.inputTokens</code> / <code>outputTokens</code></td>
<td>과금 단위</td>
<td>비용 집계 (4장)</td>
</tr>
<tr>
<td><code>usage.cacheRead/WriteInputTokens</code></td>
<td>Cache 적중량</td>
<td>2편</td>
</tr>
<tr>
<td><code>metrics.latencyMs</code></td>
<td>Server 쪽 처리 시간</td>
<td>Model 고를 때 참고</td>
</tr>
</tbody></table>
<p>텍스트를 꺼낼 때 <code>content[0][&quot;text&quot;]</code>처럼 쓰면 나중에 꼭 문제가 생깁니다.
<code>content</code>는 배열이고 첫 Block이 Text라는 보장이 없습니다. 도구를 붙이면 첫 Block이 <code>toolUse</code>인 경우가 많아서 <code>KeyError: &#39;text&#39;</code>가 납니다.
처음부터 아래처럼 순회해서 꺼내는 걸 추천합니다.</p>
<pre><code class="language-python">text = &quot;&quot;.join(b.get(&quot;text&quot;, &quot;&quot;) for b in resp[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;])</code></pre>
<p>그리고 응답의 <code>output.message</code>가 요청의 <code>messages[i]</code>와 형식이 완전히 같다는 점도 기억해 두면 좋습니다.
2편에서 응답을 그대로 대화 기록에 append할 수 있는 게 이 덕분입니다.</p>
<hr>
<h2 id="3-inferenceconfig-parameter-바꿔-보기">3. inferenceConfig Parameter 바꿔 보기</h2>
<p><code>inferenceConfig</code>에 들어가는 값은 네 개입니다. 문서로 보면 뻔한데 직접 돌려 보면 차이가 확실히 보입니다.</p>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>뜻</th>
<th>기본값</th>
</tr>
</thead>
<tbody><tr>
<td><code>maxTokens</code></td>
<td>출력 Token 상한. 넘으면 잘림</td>
<td>Model마다 다름 -&gt; 항상 직접 지정</td>
</tr>
<tr>
<td><code>temperature</code></td>
<td>0 = 매번 같은 답, 1 = 다양한 답</td>
<td>1.0</td>
</tr>
<tr>
<td><code>topP</code></td>
<td>확률 상위 P% 안에서만 고르기 (temperature와 둘 중 하나만 조절)</td>
<td>Model마다 다름</td>
</tr>
<tr>
<td><code>stopSequences</code></td>
<td>이 문자열이 나오면 바로 멈춤</td>
<td>없음</td>
</tr>
</tbody></table>
<p><code>step3_params.py</code>로 세 가지를 바꿔 봤습니다.</p>
<pre><code class="language-python">def ask(label, q, **cfg):
    resp = runtime.converse(modelId=MODEL, inferenceConfig=cfg,
                            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: q}]}])
    txt = &quot;&quot;.join(b.get(&quot;text&quot;, &quot;&quot;) for b in resp[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;])
    print(f&quot;[{label}] stopReason={resp[&#39;stopReason&#39;]}  out={resp[&#39;usage&#39;][&#39;outputTokens&#39;]}토큰&quot;)
    print(f&quot;   → {txt!r}\n&quot;)

ask(&quot;maxTokens=20&quot;, &quot;클라우드 컴퓨팅을 자세히 설명해줘.&quot;, maxTokens=20)
ask(&quot;stopSequences&quot;, &quot;1, 2, 3, 4, 5까지 세어줘.&quot;, maxTokens=100, stopSequences=[&quot;3&quot;])

for t in (0.0, 1.0):                                   # 같은 질문을 3번씩
    outs = []
    for _ in range(3):
        resp = runtime.converse(modelId=MODEL, inferenceConfig={&quot;maxTokens&quot;: 40, &quot;temperature&quot;: t},
            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;귀여운 강아지 이름 하나만 지어줘. 이름만.&quot;}]}])
        outs.append(&quot;&quot;.join(b.get(&quot;text&quot;, &quot;&quot;) for b in resp[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;]).strip())
    print(f&quot;temperature={t} → {outs}&quot;)</code></pre>
<pre><code>$ python step3_params.py
[maxTokens=20] stopReason=max_tokens  out=20토큰
   → &#39;# 클라우드 컴퓨팅 상세 설명&#39;

[stopSequences] stopReason=stop_sequence  out=8토큰
   → &#39;1, 2, &#39;

temperature=0.0 → [&#39;뭉치&#39;, &#39;뭉치&#39;, &#39;뭉치&#39;]
temperature=1.0 → [&#39;뽀삐&#39;, &#39;뽀삐&#39;, &#39;뭉치&#39;]</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/ede8a230-8b46-4641-8e94-23562dc719cb/image.png" alt="Parameter 비교"></p>
<p>결과를 보면 이렇습니다.</p>
<p>1) <code>maxTokens</code>는 잘라내기입니다. 자세히 설명해 달라고 했는데 20 Token에서 제목만 쓰고 끊겼습니다.
이때 <code>stopReason</code>이 <code>max_tokens</code>로 옵니다. 답변이 중간에 끊겼는데 이유를 모르겠다면 이 값부터 확인해 보면 됩니다.
저는 <code>stopReason == &quot;max_tokens&quot;</code>이면 화면에 &quot;출력 상한에 걸려 잘렸습니다&quot;라고 표시하게 해뒀습니다.</p>
<p>2) <code>stopSequences</code>는 그 문자열을 만나면 바로 멈춥니다. <code>&quot;3&quot;</code>을 만나자마자 멈춰서 <code>&#39;1, 2, &#39;</code>까지만 왔고 <code>stopReason</code>은 <code>stop_sequence</code>입니다.
정해진 형식으로만 답을 받을 때(예: <code>###END###</code> 마커) 씁니다.</p>
<p>3) <code>temperature</code>는 같은 질문에 같은 답이 나오게 할지 정하는 값입니다.
0이면 세 번 다 <code>뭉치</code>가 나왔고 1.0이면 답이 갈렸습니다.
분류나 정형 데이터 추출은 0 근처로, 아이디어나 글쓰기는 높게 둡니다. 저는 범용 어시스턴트라 기본값을 0.7로 두고 있습니다.</p>
<p>여기서 <code>stopReason</code>을 꼭 봐야 하는 이유가 나옵니다.
똑같이 200 OK로 와도 <code>end_turn</code>(다 말함)과 <code>max_tokens</code>(잘림)는 전혀 다른 상황입니다. HTTP 상태코드보다 <code>stopReason</code>을 결과로 보는 게 맞습니다.</p>
<hr>
<h2 id="4-token과-요금">4. Token과 요금</h2>
<p>Bedrock 요금은 Token 단위로 계산됩니다. 그런데 Token은 글자도 아니고 단어도 아닙니다. 얼마나 다른지 직접 재봤습니다.</p>
<p>Token을 세는 정식 방법은 <code>count_tokens</code> API인데, 0장에서 권한 Error가 났던 그 API라 권한을 추가하기 전에는 우회했습니다.
<code>maxTokens=1</code>로 호출해서 <code>usage.inputTokens</code>만 읽는 방법입니다. 출력 Token 1개 값만 내면 입력 Token 수를 정확히 알 수 있습니다.</p>
<p><code>step4_tokens.py</code></p>
<pre><code class="language-python">def input_tokens(text):
    resp = runtime.converse(modelId=MODEL, inferenceConfig={&quot;maxTokens&quot;: 1},
                            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: text}]}])
    return resp[&quot;usage&quot;][&quot;inputTokens&quot;]

BASE = input_tokens(&quot;a&quot;) - 1        # 한 글자 요청의 토큰 − 1 = 메시지 래핑 오버헤드
print(f&quot;기본 오버헤드: {BASE} 토큰\n&quot;)

for label, text in [
    (&quot;영어 10단어&quot;, &quot;The quick brown fox jumps over the lazy dog today&quot;),
    (&quot;한글 같은 뜻&quot;, &quot;빠른 갈색 여우가 오늘 게으른 개를 뛰어넘는다&quot;),
    (&quot;숫자·기호&quot;,   &#39;2026-09-20T22:07:59+09:00 {&quot;a&quot;:1}&#39;),
]:
    n = input_tokens(text) - BASE
    print(f&quot;{label:&lt;12}{len(text):&gt;6}자 {n:&gt;6}토큰  {len(text)/n:&gt;5.2f}자/토큰&quot;)</code></pre>
<pre><code>$ python step4_tokens.py
기본 오버헤드: 7 토큰

영어 10단어      49자     11토큰   4.45자/토큰
한글 같은 뜻     25자     32토큰   0.78자/토큰
숫자·기호        33자     23토큰   1.43자/토큰</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/02528996-fc41-4940-a80a-bc5c84c2bfb7/image.png" alt="Token 실측"></p>
<p>처음 이 결과를 보고 좀 놀랐습니다.</p>
<table>
<thead>
<tr>
<th>결과</th>
<th>의미</th>
</tr>
</thead>
<tbody><tr>
<td>영어는 1 Token에 약 4.5글자 (단어 하나 정도)</td>
<td>문서에 나오는 &quot;1 Token은 약 4자&quot;는 영어 기준</td>
</tr>
<tr>
<td>한글은 1글자에 1 Token 이상</td>
<td>같은 뜻인데 글자 수는 절반, Token은 3배</td>
</tr>
<tr>
<td>날짜, JSON은 그 중간</td>
<td>도구 결과로 JSON을 넣으면 생각보다 비쌈</td>
</tr>
<tr>
<td>빈 요청도 7 Token</td>
<td>Message 형식 자체에 드는 몫</td>
</tr>
</tbody></table>
<p>한국어로 쓰는 어시스턴트는 영어보다 입력 요금이 3배쯤 나온다는 얘기입니다.
System Prompt를 한국어로 길게 쓰고 있다면 한 번 세어 보는 걸 추천합니다.
매 요청마다 들어가는 규칙 부분만 영어로 바꿔도 입력 Token이 꽤 줄어듭니다. Model은 영어로 된 지시도 한국어 답변에 잘 적용합니다.</p>
<h3 id="요금-계산">요금 계산</h3>
<pre><code>비용 = 입력토큰 × 입력단가 + 출력토큰 × 출력단가      (단가는 &quot;백만 토큰당 $&quot;)</code></pre><p>예를 들어 2장의 첫 호출(입력 26 + 출력 22 Token)은 어떤 단가를 넣어도 $0.0001이 안 됩니다.
개인 어시스턴트에서 비용이 커지는 건 호출 한 번이 아니라 대화가 길어지면서 입력 Token이 계속 쌓이는 부분인데, 이건 2편에서 숫자로 확인합니다.</p>
<p><code>usage</code>는 모든 응답에 들어 있습니다. 처음부터 이 값을 Log로 남겨 두는 걸 추천합니다.
저는 호출할 때마다 <code>inputTokens/outputTokens/model</code>을 SQLite에 쌓아 두는데, 나중에 &quot;이번 달은 왜 이렇게 많이 나왔지?&quot; 싶을 때 이것 말고는 확인할 방법이 없었습니다.</p>
<hr>
<h2 id="5-system-prompt로-역할-주기">5. System Prompt로 역할 주기</h2>
<p>지금까지는 질문만 던졌습니다. 어시스턴트처럼 동작하게 하려면 먼저 역할과 규칙을 줘야 하는데, 그게 <code>system</code> Parameter입니다.
<code>messages</code>와 따로 들어가고 대화 내내 유지됩니다.</p>
<p><code>step5_system.py</code></p>
<pre><code class="language-python">resp = runtime.converse(
    modelId=MODEL,
    system=[{&quot;text&quot;: &quot;너는 한국어로 짧고 정확하게 답하는 조수다.&quot;}],     # ← 역할·규칙
    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;Bedrock Converse API를 한 문장으로 설명해줘.&quot;}]}],
    inferenceConfig={&quot;maxTokens&quot;: 300, &quot;temperature&quot;: 0.2},
)
print(&quot;답변:&quot;, &quot;&quot;.join(b.get(&quot;text&quot;, &quot;&quot;) for b in resp[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;]))
print(&quot;토큰:&quot;, resp[&quot;usage&quot;])
print(&quot;지연(ms):&quot;, resp[&quot;metrics&quot;][&quot;latencyMs&quot;])</code></pre>
<pre><code>$ python step5_system.py
답변: Bedrock Converse API는 AWS에서 제공하는 통일된 인터페이스로, 다양한 기초 모델과의 멀티턴 대화를 간편하게 처리할 수 있는 API입니다.
토큰: {&#39;inputTokens&#39;: 54, &#39;outputTokens&#39;: 74, &#39;totalTokens&#39;: 128, &#39;cacheReadInputTokens&#39;: 0, &#39;cacheWriteInputTokens&#39;: 0}
지연(ms): 1071</code></pre><p>System Prompt에 대해 처음부터 알았으면 좋았을 것들입니다.</p>
<table>
<thead>
<tr>
<th>알아둘 것</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>system</code>도 배열</td>
<td>Block을 여러 개 넣을 수 있고, 2편의 Cache 포인트도 여기 들어감</td>
</tr>
<tr>
<td>매 요청 입력 Token으로 과금</td>
<td>위 예시도 System Prompt 때문에 입력이 2장(26 Token)의 두 배(54 Token)</td>
</tr>
<tr>
<td><code>system</code>을 지원하지 않는 Model도 있음</td>
<td>그때는 <code>ValidationException</code>. 첫 user Message에 합쳐 넣어서 우회</td>
</tr>
<tr>
<td>매번 바뀌는 값은 끝에</td>
<td>현재 시각처럼 바뀌는 값을 앞에 넣으면 2편의 Cache가 매번 깨짐</td>
</tr>
</tbody></table>
<p>System Prompt는 &quot;누구인지 -&gt; 무엇을 하는지 -&gt; 하지 말 것 -&gt; 출력 형식&quot; 순서로 썼을 때 잘 먹혔습니다.
그리고 Prompt는 코드보다 훨씬 자주 바뀌니까 코드 여기저기에 문자열로 두지 말고 한 곳(상수 하나나 파일 하나)에 모아 두는 게 좋습니다. SeanChat도 System Prompt를 설정 모듈 한 곳에서 관리합니다.</p>
<hr>
<h2 id="6-streaming-event-구조-보기">6. Streaming Event 구조 보기</h2>
<p><code>converse</code>는 답변이 다 만들어질 때까지 기다렸다가 한 번에 돌려줍니다. 답변이 길면 5~10초 동안 화면이 그대로 멈춰 있습니다.
채팅처럼 글자가 흘러나오게 하려면 <code>converse_stream</code>을 씁니다.
처음엔 글자가 하나씩 올 거라고 생각했는데, 실제로 오는 Event를 그대로 찍어 보니 달랐습니다.</p>
<p><code>step6_stream.py</code></p>
<pre><code class="language-python">resp = runtime.converse_stream(
    modelId=MODEL,
    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;1부터 5까지 세어줘. 숫자만.&quot;}]}],
    inferenceConfig={&quot;maxTokens&quot;: 200},
)

for ev in resp[&quot;stream&quot;]:                  # ← 응답이 아니라 이벤트 제너레이터
    kind = next(iter(ev))                  # 이벤트 이름이 곧 딕셔너리 키다
    if kind == &quot;contentBlockDelta&quot;:
        print(f&quot;  [delta] {ev[kind][&#39;delta&#39;].get(&#39;text&#39;, &#39;&#39;)!r}&quot;)
    else:
        print(f&quot;[{kind}] {json.dumps(ev[kind], ensure_ascii=False)[:120]}&quot;)</code></pre>
<pre><code>$ python step6_stream.py
[messageStart] {&quot;role&quot;: &quot;assistant&quot;}
  [delta] &#39;1&#39;
  [delta] &#39;\n2\n3\n4\n5&#39;
[contentBlockStop] {&quot;contentBlockIndex&quot;: 0}
[messageStop] {&quot;stopReason&quot;: &quot;end_turn&quot;}
[metadata] {&quot;usage&quot;: {&quot;inputTokens&quot;: 27, &quot;outputTokens&quot;: 13, &quot;totalTokens&quot;: 40}, &quot;metrics&quot;: {&quot;latencyMs&quot;: 664}}</code></pre><table>
<thead>
<tr>
<th>Event</th>
<th>하는 일</th>
<th>주의</th>
</tr>
</thead>
<tbody><tr>
<td><code>messageStart</code></td>
<td>역할 알림</td>
<td>-</td>
</tr>
<tr>
<td><code>contentBlockStart</code></td>
<td>Block 시작 (도구 호출이면 여기에 이름과 ID)</td>
<td>Text만 오면 생략될 수 있음 (위 출력에도 없음)</td>
</tr>
<tr>
<td><code>contentBlockDelta</code></td>
<td>실제 내용 조각</td>
<td>글자 단위가 아니라 덩어리로 옴</td>
</tr>
<tr>
<td><code>contentBlockStop</code> / <code>messageStop</code></td>
<td>Block, Message 끝</td>
<td><code>stopReason</code>은 <code>messageStop</code>에 있음</td>
</tr>
<tr>
<td><code>metadata</code></td>
<td>usage와 지연 시간</td>
<td>Token 집계는 여기서만 가능. 맨 마지막에 옴</td>
</tr>
</tbody></table>
<p><code>delta</code>가 <code>&#39;1&#39;</code> 다음에 <code>&#39;\n2\n3\n4\n5&#39;</code>로 한꺼번에 온 게 보입니다. Chunk 크기는 정해져 있지 않습니다. 한 글자일 때도 있고 문단 하나가 통째로 올 때도 있습니다.</p>
<p>이게 왜 중요하냐면, Markdown을 실시간으로 렌더링하면 Chunk 경계에서 문법이 잘립니다.
<code>**굵게</code>까지 온 상태에서 렌더링하면 별표가 그대로 보이고, 다음 Chunk에서 <code>**</code>가 와야 닫힙니다.
저는 iOS App에서 이것 때문에 한 번 크게 고생했고, 결국 Chunk를 모아서 문단이나 코드블록 단위로 Parsing하는 쪽으로 바꿨습니다. Markdown 표시 문제는 4편에서 조금 더 이야기합니다.</p>
<p><code>converse</code> 응답 하나가 <code>converse_stream</code>에서는 Event 5~6종으로 나뉘어 올 뿐입니다. Stream Event를 다시 모으면 <code>converse</code> 응답과 같은 Message가 됩니다.
그래서 저는 Stream을 받으면서 완성된 assistant Message를 같이 조립해 두고, 그걸 대화 기록에 넣습니다. 이 부분은 2편에서 이어집니다.</p>
<hr>
<h2 id="이번-편에서-만난-error">이번 편에서 만난 Error</h2>
<p>글을 쓰면서 실제로 만난 Error입니다. Bedrock Error는 예외 Class 이름만 봐도 어디를 봐야 할지 대략 정해집니다.</p>
<table>
<thead>
<tr>
<th>예외 Class</th>
<th>누가 거부했나</th>
<th>봐야 할 곳</th>
</tr>
</thead>
<tbody><tr>
<td><code>NoCredentialsError</code></td>
<td>boto3 (요청 전)</td>
<td>환경변수, 프로필</td>
</tr>
<tr>
<td><code>ParamValidationError</code></td>
<td>boto3 (요청 전)</td>
<td>내 코드의 Parameter 형식</td>
</tr>
<tr>
<td><code>ValidationException</code></td>
<td>Bedrock 또는 Model</td>
<td>Model ID, 요청 내용, Model별 제약</td>
</tr>
<tr>
<td><code>AccessDeniedException</code></td>
<td>Bedrock (권한)</td>
<td>IAM 정책 -&gt; Model Access -&gt; 기능 지원 여부 순서로</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>#</th>
<th>Error Message(일부)</th>
<th>원인</th>
<th>해결</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td><code>NoCredentialsError: Unable to locate credentials</code></td>
<td>자격증명 없음</td>
<td><code>AWS_BEARER_TOKEN_BEDROCK</code> 또는 <code>AWS_PROFILE</code> 확인</td>
</tr>
<tr>
<td>2</td>
<td><code>AccessDeniedException: ... is not authorized to perform: bedrock:CountTokens</code></td>
<td>IAM에 그 Action이 없음</td>
<td>Message에 나온 Action을 정책에 추가</td>
</tr>
<tr>
<td>3</td>
<td><code>ValidationException: Invocation of model ID ... with on-demand throughput isn&#39;t supported</code></td>
<td>Inference Profile 없이 호출</td>
<td><code>us.</code> 접두어 ID 사용 (1장)</td>
</tr>
<tr>
<td>4</td>
<td><code>ValidationException: The text field in the ContentBlock object at messages.0.content.0 is blank</code></td>
<td>빈 문자열을 보냄</td>
<td>빈 입력은 호출 전에 걸러냄</td>
</tr>
</tbody></table>
<p>4번은 4장에서 빈 문자열의 Token 수를 재보려다가 만났습니다. 실제로 쓰다 보면 엔터만 치고 보내는 경우가 꽤 있어서 Server 입구에서 걸러 두는 게 좋습니다.</p>
<h3 id="accessdeniedexception-원인-구분하기">AccessDeniedException 원인 구분하기</h3>
<p><code>AccessDeniedException</code>은 1) IAM 권한 없음 2) Model Access(구독)를 안 켬 3) 그 Model이 그 기능을 지원하지 않음, 이 세 경우에 똑같이 납니다.
위 2번처럼 Message에 Action이 적혀 있으면 1)이고, 그렇지 않으면 Control Plane에 물어보면 구분됩니다. 조회는 무료입니다.</p>
<pre><code class="language-bash">aws bedrock get-foundation-model-availability \
  --model-id anthropic.claude-haiku-4-5-20251001-v1:0 --region us-east-2</code></pre>
<pre><code class="language-json">{
    &quot;modelId&quot;: &quot;anthropic.claude-haiku-4-5-20251001-v1&quot;,
    &quot;agreementAvailability&quot;: { &quot;status&quot;: &quot;AVAILABLE&quot; },
    &quot;authorizationStatus&quot;: &quot;AUTHORIZED&quot;,
    &quot;entitlementAvailability&quot;: &quot;AVAILABLE&quot;,
    &quot;regionAvailability&quot;: &quot;AVAILABLE&quot;
}</code></pre>
<table>
<thead>
<tr>
<th>Field</th>
<th>뜻</th>
<th>여기가 문제면</th>
</tr>
</thead>
<tbody><tr>
<td><code>agreementAvailability</code></td>
<td>Model 사용 약관(구독) 상태</td>
<td>Console Model access에서 활성화 (0-1)</td>
</tr>
<tr>
<td><code>authorizationStatus</code></td>
<td>내 자격증명의 권한</td>
<td>IAM 정책 수정 (0-2)</td>
</tr>
<tr>
<td><code>regionAvailability</code></td>
<td>이 Region에 Model이 있나</td>
<td>Region 변경 또는 Inference Profile (1장)</td>
</tr>
</tbody></table>
<p>넷 다 <code>AVAILABLE</code>/<code>AUTHORIZED</code>인데도 <code>AccessDenied</code>가 나면 그 Model이 그 기능을 지원하지 않는 경우입니다. 2편 Prompt Caching에서 이 경우가 나옵니다.</p>
<hr>
<h2 id="정리">정리</h2>
<pre><code>step2_converse.py     첫 호출 + 응답 구조 (26 in / 22 out / 650ms)
step3_params.py       maxTokens, stopSequences, temperature (stopReason 3종)
step4_tokens.py       Token 실측: 영어 4.45자/Token, 한글 0.78자/Token
step5_system.py       System Prompt
step6_stream.py       converse_stream Event 5종</code></pre><p>이번 편에서 기억해 두면 좋은 것들입니다.</p>
<ol>
<li>Model ID는 <code>us.</code> 접두어(Inference Profile)로 부릅니다. 목록에 있어도 그대로는 안 됩니다.</li>
<li><code>content</code>는 Block 배열이고, 결과는 <code>stopReason</code>으로 판단합니다.</li>
<li>한글은 영어보다 Token이 3배쯤 나옵니다. System Prompt 길이를 한 번 재보는 게 좋습니다.</li>
<li>Streaming은 글자 단위가 아니라 덩어리로 옵니다. Token 수는 맨 마지막 <code>metadata</code>에서 받습니다.</li>
</ol>
<h2 id="다음-편-예고">다음 편 예고</h2>
<p>2편에서는 여기서 만든 호출 코드에 대화 기억과 도구 호출을 붙입니다. <code>messages</code> 배열 하나로 대화를 이어가는 방법과 그때 비용이 어떻게 늘어나는지, 도구 호출 while Loop, Prompt Caching, Extended Thinking을 차례로 해보고 마지막에 FastAPI + SSE Server로 묶습니다.</p>
<p>다음 편: <a href="https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-Amazon-Bedrock%EC%9C%BC%EB%A1%9C-%EB%82%98%EB%A7%8C%EC%9D%98-AI-%EC%96%B4%EC%8B%9C%EC%8A%A4%ED%84%B4%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-2-%EB%8C%80%ED%99%94-%EA%B8%B0%EC%96%B5-%EB%8F%84%EA%B5%AC-%ED%98%B8%EC%B6%9C-SSE-Server">2편 - 대화 기억, 도구 호출, SSE Server</a></p>
<hr>
<p><em>이 글은 개인 AWS 계정에서 실험한 결과입니다.
요금과 Model 지원 사항은 작성 시점(2026년 9월, us-east-2) 기준입니다.</em></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[쉽게 따라하는 LZA를 활용한 AWS Control Tower 구축 - Stack / CodePipeline 배포]]></title>
            <link>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95</link>
            <guid>https://velog.io/@seanson2709/%EC%89%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%ED%95%98%EB%8A%94-LZA%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-AWS-Control-Tower-%EA%B5%AC%EC%B6%95</guid>
            <pubDate>Mon, 30 Jun 2025 01:16:50 GMT</pubDate>
            <description><![CDATA[<h2 id="개요">개요</h2>
<p>이 글에서는 AWS에서 제공하는 <strong>Landing Zone Accelerator (LZA)</strong>를 활용하여 <strong>Control Tower 및 AWS Organizations를 구축하는 방법</strong>을 다룹니다.<br>LZA를 사용하면 조직 전체의 Network, 보안, 계정, 로깅 설정을 코드로 한 곳에서 관리할 수 있어서, 계정이 많아질수록 관리가 편해집니다.</p>
<hr>
<h2 id="사전-준비-사항">사전 준비 사항</h2>
<ul>
<li>AWS Organizations Root 계정 접근 권한</li>
<li>AWS CLI + CDK 환경 구성 (추가 설명)</li>
</ul>
<hr>
<h2 id="구성-요소-요약">구성 요소 요약</h2>
<table>
<thead>
<tr>
<th>구성 요소</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><strong>AWS Control Tower</strong></td>
<td>계정 프로비저닝, 기본 보안 OU 생성</td>
</tr>
<tr>
<td><strong>Landing Zone Accelerator (LZA)</strong></td>
<td>Network, 로깅, 보안 규칙 코드 기반 자동화</td>
</tr>
<tr>
<td><strong>S3</strong></td>
<td>구성 파일 저장소</td>
</tr>
<tr>
<td><strong>CodePipeline</strong></td>
<td>구성 변경 자동 반영</td>
</tr>
</tbody></table>
<hr>
<h2 id="실제-구축-순서">실제 구축 순서</h2>
<h3 id="1-aws-root-account로-login-및-control-tower-enable">1. AWS Root Account로 Login 및 Control Tower Enable</h3>
<p>먼저 Landing Zone Accelerator Code를 사용하여 Control Tower를 배포하기 위해서는 AWS Control Tower가 Enable 되어 있어야 합니다.</p>
<p>1) AWS Console에서 Home Region으로 사용하실 Region을 선택하고 Landing Zone을 Set up합니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/3112d385-146a-4e14-862c-87afd080f96f/image.png" alt=""></p>
<p>Region 등을 설정하고 OU 명칭을 입력해줍니다.
이때 OU명칭은 나중에 변경하기 쉽지 않으니 신중히 선택해주세요.
<img src="https://velog.velcdn.com/images/seanson2709/post/dad8be79-beae-4720-ae37-0f42f01100a9/image.png" alt=""></p>
<p>Log Archive 및 Audit Log의 Email의 경우 LZA 코드에서 활용됩니다. 기록하여 나중에 활용되도록 합시다.
<img src="https://velog.velcdn.com/images/seanson2709/post/e97616cd-3a31-43a2-ba51-936535e6526c/image.png" alt=""></p>
<p>나머지 설정의 경우 Default로 하여 Control Tower를 설정합니다.
초기 설정의 경우 약 한시간의 시간이 소요됩니다.</p>
<h3 id="2-lza-github-repository-복제">2. LZA GitHub Repository 복제</h3>
<p>Landing Zone Accelerator 코드 실행을 위해서는 먼저 LZA Sample Code를 Clone합니다.</p>
<pre><code class="language-bash">git clone https://github.com/awslabs/landing-zone-accelerator-on-aws.git
cd landing-zone-accelerator-on-aws/source
yarn install # 만약 yarn install 실패 시 yarn.lock 파일 지우고 재 실행
cd packages/@aws-accelerator/installer
yarn build &amp;&amp; yarn cdk synth</code></pre>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/07a013cc-d78e-4d26-b689-cdfe6b53fcfe/image.png" alt=""></p>
<p>그후 yarn을 이용해 template 생성을 진행합니다.
NPM 및 Yarn Install은 환경에 따라 다르므로 개인적으로 설치 및 환경변수 등록 하시면 됩니다.</p>
<p>맥북 기준</p>
<pre><code class="language-bash">brew install node
npm install -g aws-cdk
npm install -g yarn</code></pre>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/a98936b8-98c5-45e6-9519-1ad4c62cda2d/image.png" alt=""></p>
<p>여기까지 잘 따라오셨다면, 아래와 같이 json파일이 생성된 것을 확인할 수 있습니다.
해당 파일의 경로는 아래와 같습니다.</p>
<pre><code class="language-bash">landing-zone-accelerator-on-aws/source/packages/@aws-accelerator/installer/cdk.out/</code></pre>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/4ba6fdd3-2f16-4b6c-8a92-8daab5fb1435/image.png" alt=""></p>
<h3 id="3-lza-template-배포secret-생성">3. LZA template 배포(Secret 생성)</h3>
<p>먼저 CodePipeline 수행을 위한 github personal key를 만들어줍니다.</p>
<p>개인 github에 Login 후
Settings -&gt; Developer Settings -&gt; Personal access Token으로 이동합니다.</p>
<p>이후 Generate New token을 클릭하여 Token을 발행해줍니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/4e2ae2ad-ac1a-4a32-947e-788268898cc8/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/d3544ab5-be3e-4634-b552-1b27c533829c/image.png" alt=""></p>
<p>이후 생성된 Personal token은 AWS환경에서 사용될 예정이므로 잘 저장해두도록 합니다.</p>
<p>다시 AWS Console로 돌아가 AWS Secret Manager를 생성해줍니다.</p>
<pre><code>AWS Secret Manager -&gt; Secrets -&gt; Store a new secret -&gt; Other type of secret -&gt; Plaintext 선택 후 token 붙여넣기</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/11c4a9ff-16c2-4c93-9611-b205ba5225bc/image.png" alt=""></p>
<p>Encryption key의 경우 그대로 두고 다음으로 넘어갑니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/3875aec0-94da-40f4-80be-f57c070d7a7d/image.png" alt=""></p>
<p>Secret Name의 경우 아래 명칭을 그대로 입력합니다.</p>
<pre><code>accelerator/github-token</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/5d30aadb-2175-4cf1-817f-450b6c28d7e8/image.png" alt=""></p>
<p>나머지 설정의 경우 default로 하여 설정하면 secret이 설정됩니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/90c92901-5481-4c56-a462-21e4e070fed4/image.png" alt=""></p>
<h3 id="4-lza-template-배포s3-생성-및-stack-배포">4. LZA template 배포(S3 생성 및 stack 배포)</h3>
<p>위에 생성된 template 파일의 경우 stack생성 및 배포를 위해 활용될 예정입니다.
이 template 파일의 저장을 위해 S3를 생성합니다.</p>
<pre><code>Bucket 명칭 예시 : seungwoo-lza-template
(나머지는 default로 설정합니다)</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/e978d5ba-371f-478e-8de7-ea3c963041e7/image.png" alt=""></p>
<hr>
<p>S3에 Template 파일을 Upload 하기 위해 aws cli를 설정합니다.
(profile 설정을 하는 것을 추천드리나 이 블로그에서는 Profile 설정 없이 진행하도록 하겠습니다)</p>
<p>AWS Cli access-key를 IAM으로 설정하거나 아니면 아래와 같은 방법으로 설정합니다.</p>
<pre><code>IAM Identity Center 접속
Access URL 확인</code></pre><p><img src="https://velog.velcdn.com/images/seanson2709/post/d4f67526-cb1d-44b6-a1df-883724db1bed/image.png" alt=""></p>
<p>해당 URL로 접속 시 Login Page 확인 가능하며 기존 설정해둔 Email로 Login합니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/96a81930-abdb-4862-a83a-1b51a9048f94/image.png" alt=""></p>
<p>이후 Access Key를 눌러 임시 Token을 가이드에 따라 배포합니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/d437b5eb-42d3-46ed-9ac0-e23e641165d7/image.png" alt=""></p>
<p>Token 배포
<img src="https://velog.velcdn.com/images/seanson2709/post/4225265d-2db1-484f-b13d-e630238641d6/image.png" alt=""></p>
<hr>
<p>AWS CLI 설정이 완료되었다면 아까 만들었던 S3에 Template 파일을 Upload합니다.
Bucket 이름(<code>seungwoo-lza-template</code>)은 전역에서 유일해야 하니 본인 이름으로 바꿔서 실행하세요.</p>
<pre><code class="language-bash"># 2번에서 이미 installer 디렉터리로 이동했다면 cd는 생략
cd landing-zone-accelerator-on-aws/source/packages/@aws-accelerator/installer
# 콘솔에서 버킷을 이미 만들었다면 mb는 생략
aws s3 mb s3://seungwoo-lza-template
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
aws s3api head-bucket --bucket seungwoo-lza-template --expected-bucket-owner $ACCOUNT_ID
aws s3 cp ./cdk.out/AWSAccelerator-InstallerStack.template.json s3://seungwoo-lza-template</code></pre>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/657f66ee-4583-4073-88b5-67bdef4f23e8/image.png" alt=""></p>
<p>아래와 같이 생성된 S3 Bucket에서 Template 파일 확인이 가능해야 합니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/ee62c933-11e7-4566-8928-f9a6785ea5b7/image.png" alt=""></p>
<p>이제 거의 완료되었습니다. Stack을 배포해봅시다.
아래 값 중 Bucket URL·Email은 본인 환경 값으로 바꿔 넣으세요(대괄호 없이 값만 넣습니다). Email 3개(관리·Log Archive·Audit)는 Control Tower 설정 때 쓴 것과 같아야 합니다.</p>
<pre><code class="language-bash">aws cloudformation create-stack \
--stack-name AWSAccelerator-InstallerStack \
--template-url https://seungwoo-lza-template.s3.us-west-2.amazonaws.com/AWSAccelerator-InstallerStack.template.json \
--parameters \
ParameterKey=RepositoryName,ParameterValue=landing-zone-accelerator-on-aws \
ParameterKey=RepositoryBranchName,ParameterValue=main \
ParameterKey=ConfigurationRepositoryLocation,ParameterValue=s3 \
ParameterKey=ManagementAccountEmail,ParameterValue=management@example.com \
ParameterKey=LogArchiveAccountEmail,ParameterValue=logarchive@example.com \
ParameterKey=AuditAccountEmail,ParameterValue=audit@example.com \
ParameterKey=ApprovalStageNotifyEmailList,ParameterValue=approval@example.com \
ParameterKey=EnableApprovalStage,ParameterValue=Yes \
ParameterKey=ControlTowerEnabled,ParameterValue=Yes \
--capabilities CAPABILITY_IAM</code></pre>
<p><img src="https://velog.velcdn.com/images/seanson2709/post/2eb631f5-5954-42ae-b8ab-1fdbdb4756cc/image.png" alt=""></p>
<p>아래와 같이 Stack이 생성되면 정상적으로 수행된 것입니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/f4e57206-fa34-44b7-b647-fd1c35d8a339/image.png" alt=""></p>
<p>자동적으로 Code Pipeline이 수행되며, Control 타워를 구성하게 됩니다.
<img src="https://velog.velcdn.com/images/seanson2709/post/10edd048-1b4b-4a0d-95da-4f02e0440256/image.png" alt=""></p>
<h2 id="정리">정리</h2>
<p>여기까지 오면 LZA로 AWS Control Tower를 구성할 수 있는 기본 조건이 갖춰집니다.
이후 OU, 계정, Network 같은 설정은 전부 LZA 설정 파일을 고쳐서 배포하게 됩니다.
다음 포스트에서는 LZA 코드를 활용해 기본적인 OU / Accounts 구성 및 Network 구성에 대해 알아봅시다.</p>
<blockquote>
<p>2026-09-24 수정: 명령어 경로·Parameter 표기(대괄호)를 실제 실행 가능한 형태로 고치고, Screenshot 속 Email·계정 ID·임시 자격 증명을 가렸습니다.</p>
</blockquote>
]]></description>
        </item>
    </channel>
</rss>