<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 김도영 on Medium]]></title>
        <description><![CDATA[Stories by 김도영 on Medium]]></description>
        <link>https://medium.com/@mzc_kdyoung?source=rss-256a1395a4d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IbKZWc8wqyceVwK3</url>
            <title>Stories by 김도영 on Medium</title>
            <link>https://medium.com/@mzc_kdyoung?source=rss-256a1395a4d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:10:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mzc_kdyoung/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GKE에서 Calico CNI 사용하기]]></title>
            <link>https://medium.com/cloudvillains/gke%EC%97%90%EC%84%9C-calico-cni-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-b3fa505e6f38?source=rss-256a1395a4d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3fa505e6f38</guid>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[calico]]></category>
            <category><![CDATA[cni]]></category>
            <dc:creator><![CDATA[김도영]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 06:28:48 GMT</pubDate>
            <atom:updated>2022-07-06T07:06:45.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why?</h3><p>Project Calico는 Kubernetes에서 사용하는 네트워크 정책 엔진입니다.</p><p>최근 Kubernetes 네트워크를 정책 기반으로 사용할 필요가 생겨 다양한 NPP(Network Policy Provider)중에서 대표적인 CNI인 Calico에 대해서 조사하게 되었습니다.</p><h3>목표</h3><p>GKE Calico CNI는 어떻게 사용하는지, GKE에서 이용 가능한 Calico CNI와 Default CNI는 어떤 차이가 있는지 알아보겠습니다.</p><p>먼저 Calico를 알아보기 전에 GKE Cluster 종류에 대해서 알아볼 필요가 있습니다. GKE Cluster는 트래픽을 전달하는 방법에 따라서 2가지 Cluster로 구분이 됩니다.</p><p>Alias IP Range를 사용해 트래픽을 전달하는 방법인 <strong>VPC Native Cluster</strong>가 있고 VPC Network Custom Static 경로를 사용하는 <strong>Route Based Cluster</strong>가 있습니다.</p><h3>VPC Native Cluster</h3><p>VPC Native Cluster로 GKE를 생성하면 아래와 같이 VPC-native traffic routing 부분이 Enabled이 되며</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*ITWE6nQCrCIZg5lJ" /></figure><p>​</p><p>Cluster 생성 시 설정한 podCIDR와 serviceCIDR에 대해서 아래와 같이 Routing이 생성됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*bZSO3wIf0X8kK-q6" /></figure><h4>하지만 여기서 의문!</h4><p>Destination이 특정 Node위에 있는 Pod IP인 트래픽인 경우. 위 Routing대로 Next hop인 custom-vpc로 향하게 될 것입니다. 하지만 custom-vpc로 도착한 트래픽은 해당 Pod IP가 어떤 Node에 위치하는지 알 수 없음으로 길을 잃게 될 것입니다.</p><p>그렇다면 특정 Pod에게 트래픽을 보냈을 때, 어떻게 Routing 정보만 가지고 Pod 위치를 알 수 있을까? 더 정확하게 말하면 Pod가 위치해 있는 Node를 어떻게 알고 찾아갈 수 있까? 라고 의문이 들 수도 있습니다.</p><p>​</p><p>여기서<strong> VPC Native Cluster의 장점</strong>이 나타납니다. 앞에서 언급을 했지만 VPC Native Cluster는 Alias IP Range를 사용합니다.</p><p>아래와 같이 GKE의 Node는 Alias IP Range가 붙게 되며 이 Alias IP Range는 자신이 가지고 있는 Pod IP 대역을 나타냅니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*JA4rKGDt2NzyNlYv" /></figure><p>즉, custom-vpc로 도착한 트래픽은 Node의 Alias IP Range를 보고 Destination Pod가 위치하고 있는 Node를 알 수 있으며 트래픽은 Pod가 위치한 Node에게 갈 수 있게 되고 통신이 이루어지는 것입니다. 동일한 VPC 내에 위치하기만 하면 VM 일지라도 Pod와 통신이 가능한 구성입니다.</p><h3>Route based Cluster</h3><p>Route based Cluster로 생성하게 되면 아래와 같이 VPC-native traffic routing이 Disabled가 되며</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*4f5m3SVKz7btJET8" /></figure><p>​</p><p>podCIDR에 대해서는 아래와 같이 Node 별로 Routing이 생성됩니다. <br>Node마다 Routing이 생성되는 이유는 간단합니다. Alias IP를 사용하지 않기 때문에 VPC가 아닌 바로 Node로 트래픽을 보내야 하기 때문입니다. 또한 Route based Cluster는 Service 대역대 관련해서는 GCP Route에 Routing이 따로 생성하지 않습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*vCBiX-Q0oUE9Uy88" /></figure><h3>GKE에서 Calico CNI를 사용</h3><p>이번에는 GKE Calico CNI를 사용하는 방법에 대해서 알아보겠습니다.</p><p>사용 방법은 매우 간단합니다. 아래 이미지와 같이 Networking &gt; Enable Kubernetes Network Policy를 Check만 해주면 알아서 설치해 주므로 매우 쉽게 Calico CNI를 사용할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*cnF4_R0yLMIbQ-E0" /></figure><p>​</p><p>이렇게 설치된 GKE의 Calico CNI와 일반적인 Calico CNI와 어떤 차이점이 있을까요? 이 차이점에 대해서 알아보겠습니다.<br>(기본적인 Calico에 대해서 알아보고 싶으면 <a href="https://blog.naver.com/pukasun011">링크</a>를 참조해 주세요.)</p><h4>첫 번째, GKE Calico는 Calico의 IPAM을 사용하지 않는다</h4><p>GKE Node에 직접 들어가 cni 설정 파일을 확인해 보면 Calico ipam이 아닌 local-host ipam을 사용한다는 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*dpFJT4SJryAhJrV_" /></figure><p>​</p><h4>두 번째, GKE는 Overlay Network를 사용하지 않는다.</h4><p>IPAM을 사용하지 않음으로 calicoctl get ippool -o wide라는 명령어로는 확인이 불가하며 또한 각 Node에는 Overlay 네트워크 통신을 가능하게 해주는 Tunnel이라는 인터페이스도 존재하지 않습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*1ZQdWoDRprSOOjD0" /></figure><p>​</p><h4>세 번째, BGP를 사용하지 않는다.</h4><p>일반적인 kubernetes 환경에서 Calico CNI는 각 Node끼리 BGP를 통해서 Pod IP 대역을 공유하지만 GKE는 각 Node끼리 Pod 대역대 공유를 BGP를 통해서 하지 않습니다.</p><p>​직접 Node에 들어가 Process를 확인해 보면 BGP 프로토콜을 이용해 대역대를 광고하는 bird라는 Process가돌고 있지 않음을 확인할 수 있으며, 자연스럽게 confd도 사용할 필요가 없게 돼 confd Process도 없는 것을 알 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*2glF476Ooo-UHjjX" /></figure><h3>통신 흐름</h3><p>그렇다면 BGP를 사용하지 않고 GKE Calico는 어떠한 방식으로 Pod끼리 통신을 하게 되는 것일까요? 이해를 돕기 위해 Calico CNI를 사용하고 있는 GKE 아키텍처를 그려보았습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*rEhZBum60Bop_cl-" /></figure><p>설명을 하자면 Node1은 pod 10.84.1.0/24 대역대를 지니고 있고, Node2는 pod 10.84.2.0/24 대역대를 지니고 있습니다. 그리고 각 Route에는 각 Pod IP로 들어오면 가상 인터페이스인 cali로 들어가라는Routing이 잡혀있습니다. 여기서 포인트는 Node의 GCP NI에 Pod의 IP 대역대가 Alias IP로 추가가 되어있다는 것입니다.</p><h4>Node마다 Alias IP가 없는 상태라면</h4><p>이해를 돕기 위해 Alias IP가 없는 상태에 대해서 먼저 알아보겠습니다.<br>아래 이미지처럼 Node마다 Alias IP가 없는 상태에서 「pod4 → pod2」로 트래픽을 보낸다고 하면</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*13_cKqHUQqNMZw87" /></figure><p>​</p><p>pod2의 IP는 자신 Pod 대역이 아님으로 eth0으로 보내 것이며, GCP Route에 따라 해당 트래픽은 다시 calico-cluster-vpc로 이동을 할 것입니다. 하지만 Destination이 10.84.1.0/24 대역대를 가진 트래픽은 어떠한 정보도 없기 때문에 어떤 Node로 가야 할지 알 수가 없게 됩니다. 그럼으로써 해당 Packet은 Drop 처리가 될 것입니다.</p><h4>Node마다 Alias IP가 있다면</h4><p>이번에는 Alias IP로 Pod IP 대역을 가지고 있는 Node인 경우를 살펴보겠습니다. 먼저 아래 이미지를 보면 pod4번에서 보낸 트래픽이 pod2번까지 문제 없이 도달하고 있는 것을 알 수 있습니다. 왜 도달할 수 있을까요?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*QJGZjRJOlMUY3BdP" /></figure><p>흐름을 따라가 보면 먼저 pod4에서 10.84.1.13으로 트래픽을 보내는 경우, 자신의 IP 대역대가 아님으로 eth0으로 보낼 것이고, eth0으로 나온 트래픽은 GCP Routes를 통해서 calilco-cluster-vpc로 가고 calilco-cluster-vpc 갔더니 10.84.1.13 IP가 포함되는 대역대인 10.84.1.0/24 대역대를 Alias IP로 가지고 있는 Node1이 있으므로 해당 패킷은 Node1로 들어가게 되고 Node1에서는 10.84.1.13으로 가려면 cali2로 가라는 Routing이 존재함으로 결국엔 pod2까지 패킷이 도달할 수 있는 것입니다.</p><p>​즉, GKE는 Alias IP를 사용하는 native VPC인 경우에만 GKE에서 제공하는 Calico CNI를 사용할 수 있으며, 이로 인해 BGP로 각 Node가 IP를 주고받지 않아도 되고 overlay 네트워크 또한 필요 없게 되는 것입니다.</p><h4>Pod와 GCE 통신은 어떻게</h4><p>다른 VPC에 존재하는 GCE(VM)와 Pod 간 통신도 크게 다르지 않게 아래와 같이 이루어집니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*nLxll4dMJLoUW4qz" /></figure><h3>BGP 연동</h3><p>그렇다면 GKE Calico 사용 중에 온프렘의 서버와 BGP를 통해서 IP 대역대를 연계하고 싶은 경우엔 어떻게 해야 할까요? 기존 Calico CNI처럼 BGPPeer Object를 생성해서 BPG Session을 맺어야 하는 것일까요?</p><p>하지만 이 방법은 GKE Calico는 BGP를 지원하지 않아 불가능합니다. 그렇다면 어떻게 해야 할까요?</p><p>답은 간단합니다. 이러한 경우에는 그냥 GCP VPN을 사용해서 온프레미스(또는 타 Provider)와 BGP 연결을 맺으면 됩니다. 온프레미스와 VPN을 통해 BGP 세션을 맺음으로써 GCP Route에는 온프레미스 대역대 Routing 정보가 추가될 것이며 Pod는 GCP Routes를 통해 온프레미스의 특정 서버까지 트래픽을 보낼 수 있게 될 것입니다.</p><h3>GKE Calico CNI와 GKE Default CNI와 차이점</h3><p>이번에는 Network Policy Enable을 안 했을 경우(GKE Calico가 아닌 경우) 사용되는 Default CNI Cluster와는 어떤 차이점이 있는지 알아보겠습니다. 일단 Document를 확인해 보면 Default CNI도 Calico와 동일하게 Virtual Route Table에 의해서 통신이 이루어지며, Calico와 다르게 Bridge가 생성이 되고 Bridge를 통해서 내부 Pod들이 통신이 된다고 기술되어 있습니다. 하지만 실제로 구성을 해보면 crb0의 Bridge는 존재하지 않습니다.</p><p>​또한 각 Node에 들어가 CNI 설정 정보를 보면 ptp로 통신한다는 것까지 알 수 있습니다. 개인적인 생각으론 GKE Calico와 GKE Default CNI의 차이점은 Proxy arp 기능 활성화 여부와 Label을 이용한 트래픽 제한하는 Network Policy 가능 사용 여부인 것 같습니다.</p><h4>Proxy arp</h4><p>Proxy arp를 간단하게 설명하자면 ARP 프로토콜을 이용해서 대신 MAC 주소를 알아와 주는 기능입니다. GKE Calico는 이 기능이 활성화되어있고 Default CNI는 비활성화로 Proxy arp가 아닌 직접 ARP를 Request를 해서 MAC 주소를 알아옵니다.</p><p>​Proxy arp는 가상 인터페이스에 설정하며, 확인은 아래 명령어로 확인이 가능합니다.</p><p>$ cat /proc/sys/net/ipv4/conf/[pod의 가상 인터페이스 ID]/proxy_arp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*aEjI1SOOTevNG0Dt" /></figure><p>이처럼 GKE Default CNI는 0이며, GKE Calico CNI는 1로 되어있다는 것을 알 수 있습니다. Proxy arp를 사용 중인 Calico는 Pod 내부 route에 169.254.1.1로 가도록 Routing이 추가되어있고</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*JaaNaKhw0KSB5taf" /></figure><p>​TcpDump를 통해 확인해 보면 Ping 통신을 했을 시 169.254.1.1로 ARP Request, Reply를 받는 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*UqFuSKy3lmVUioaQ" /></figure><p>​그에 반해 Default CNI에서 Pod의 Route는 아래와 같으며</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*mAjPhOa0dgD_OkyK" /></figure><p>​TcpDump로 확인했을 때, 직접 ARP Request를 보내고 상대 Pod에게 직접 Mac 주소를 Reply를 받습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*JtD4fGP6L-dcBqIE" /></figure><h4>Network Policy</h4><p>Network Policy란 간단하게 Pod마다 Firewall이 있다고 생각하면 될 것 같습니다. 아키텍처는 아래와 같은 형태입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*nvGUQgKYrnGcraSV" /></figure><p>간단하게 Network Policy의 기능인 Ingress Network Policy와 Egress Network Policy에 대해서 알아보겠습니다.</p><h4>Ingress Network Policy</h4><p>먼저 Network policy가 설정이 안 되어있는 상황에서 아래 명령어로 Pod와 Service를 생성합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1b151f55423a6fce232799c81326ec3/href">https://medium.com/media/d1b151f55423a6fce232799c81326ec3/href</a></iframe><p>그리고 아래와 같이 NetworkPolicy를 생성한 다음</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d630da3af6bcaedaa936f609c0ba54c9/href">https://medium.com/media/d630da3af6bcaedaa936f609c0ba54c9/href</a></iframe><p>​</p><p>Test pod로 접근을 해보면 아래와 같이 Timeout이 발생합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*TR2jYjwwAELWyfEr" /></figure><p>​그렇다면 방금 전에 생성한 NetworkPolicy에 대해 어떤 설정이 들어가 있는지 자세히 살펴보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*bEdMbkMQJ8OPEZjE" /></figure><p>Ingress에 대해서 Label 「app: foo」를 가진 Pod만 허용한다고 기술되어 있고 대상은 「app: hello」 label을 가진 pod 라는 것을 짐작할 수 있습니다.<br>Test Pod가 접근했을 시 Timeout이 발생한 이유는 Test Pod에 「app: foo」 label이 없었기 때문입니다.「app: foo」 label 추가 후 다시 통신을 해보면 문제 없이 통신이 통신이 가능한 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*RRSL2xTkO12GgxS9" /></figure><h4>Egress Network Policy</h4><p>Egress Network Policy는 특정 Pod에서 나가는 트래픽을 제한할 수 있습니다.Ingress와 생성 방법은 크게 다른 점은 없습니다.<br>먼저 아래 명령어로 pod와 service를 배포 후</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2ff0b1e3cd5a4fc816af7d9ea6cb12a/href">https://medium.com/media/a2ff0b1e3cd5a4fc816af7d9ea6cb12a/href</a></iframe><p>아래와 같이 Egress를 제한하는 NetworkPolicy를 생성하면</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd5ffdad3bd9cb070cd11058bcad68a6/href">https://medium.com/media/cd5ffdad3bd9cb070cd11058bcad68a6/href</a></iframe><p>​아래와 같이 통신이 안 되는 것을 알 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*XMja81_GVvThK7vR" /></figure><p>​</p><p>Networkpolicy를 자세히 살펴보면「app: foo」 label을 지닌 pod가 「app: hello」 label을 지닌 pod로 가는 트래픽을 제한하겠다는 의미인 것을 유추 할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*CGgoKIKKsMuXBYUZ" /></figure><h3>정리</h3><p>VPC Native Cluster의 GKE 생성을 하면 Node에 Pod 대역이 Alias IP로 붙게 되며, 이 Alias IP가 붙음으로써 Pod와 Pod 통신 또는 Pod와 VM 통신 시 문제 없이 통신이 된다는 것을 알아보았습니다. 또한 기존 Calico와 다르게 BGP와 Network Overlay를 사용하지 않는데 그 이유는 Alias IP가 있으므로 굳이 사용할 필요가 없어서 였습니다. 그리고 GKE Calico 와 GKE Default CNI와 차이는 Proxy ARP와 Network Policy 기능의 유무였습니다.</p><h3>메가존클라우드 GCP Team</h3><p>메가존클라우드 GCP Team이 궁금하다면 다음 링크를 확인해 주세요!</p><p><a href="https://ctc.oopy.io/gcp_sa_group_info">https://ctc.oopy.io/gcp_sa_group_info</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3fa505e6f38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/gke%EC%97%90%EC%84%9C-calico-cni-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-b3fa505e6f38">GKE에서 Calico CNI 사용하기</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Citadel 과 GCGS의 관계]]></title>
            <link>https://medium.com/cloudvillains/citadel-%EA%B3%BC-gcgs%EC%9D%98-%EA%B4%80%EA%B3%84-c416b9ecea2b?source=rss-256a1395a4d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c416b9ecea2b</guid>
            <category><![CDATA[agones]]></category>
            <category><![CDATA[citadel]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[tlm]]></category>
            <category><![CDATA[gcg]]></category>
            <dc:creator><![CDATA[김도영]]></dc:creator>
            <pubDate>Wed, 11 May 2022 08:37:33 GMT</pubDate>
            <atom:updated>2022-05-20T06:25:18.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why?</h3><p><a href="https://medium.com/ctc-mzc/gcgs%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EA%B2%8C%EC%9E%84-%EC%84%9C%EB%B2%84-%EB%B0%B0%ED%8F%AC-4df8cb22dc7">이전 포스트 GCGS를 이용한 게임서버 배포 </a>에서 GCGS Multi-Cluster Allocation 이용해 GameServer Allocation을 진행해 보았습니다. GCGS Multi-Cluster Allocation을 진행하면서 Citadel이라는 모듈을 설치하였는데 여기서 Citadel은 무엇이며, 왜 설치를 해야 하는지, 그리고 Citadel의 역할이 무엇인지에 대한 궁금증으로 Citadel을 찾아보게 되었습니다.</p><p>​Citadel을 찾아보기 전에 먼저 풀어야할 과제들이 있었습니다. 우선 TLS가 무엇인지, mTLS란 무엇인지에 대해 알아야 했으며 Server의 인증서는 어떤 흐름으로 인증이 되는지, Client 인증서란 무엇인지에 대해서도 알아야 했습니다. 대충만 알고 있던 TLS 와 mTLS 그리고 Server인증서와 Client 인증서에 대해서 이번에 제대로 알아보자! 라는 마음가짐으로 해당 내용들을 조사해 보았습니다.</p><p>​조사한 내용 토대로 TLS와 mTLS의 개념 그리고 Client와 Server가 어떤 식으로 서로 간 인증하는지에 대해 알아볼 것이며, 이러한 인증 과정에 쓰이는 인증서를 조금 더 쉽게 발급이 가능한 Citadel 그리고 GCGS에서 Multi-Cluster Allocation을 하기 위해서는 왜 Citadel이 필요한지에 대해서 알아보겠습니다.</p><h3>TLS 통신이란​</h3><p><strong>TLS 의미<br></strong>먼저 TLS에 대해서 알아보겠습니다. TLS란 SSL과 동일한 의미입니다. SSL 이란 Secure Sockets Layer의 약자로 암호화를 기반으로 한 인터넷 보안 프로토콜이며 현재는 TLS라는 이름으로 변경이 되었습니다. 이름은 변경되었지만 SSL, TLS 두 용어 모두 사용되고 있습니다.​</p><p><strong>SSL HandShake 과정<br></strong>그렇다면 어떠한 방식으로 보안 통신이 되는지 알아보겠습니다.<br>(대칭키와 공개키에 대해서는 <a href="https://www.uname.in/129#:~:text=%ED%81%B0%ED%8B%80%EC%97%90%EC%84%9C%EC%9D%98%20%EC%B0%A8%EC%9D%B4%EB%A5%BC,%EB%B9%84%EB%8C%80%EC%B9%AD%ED%82%A4%20%EC%95%94%ED%98%B8%ED%99%94%EB%9D%BC%EA%B3%A0%EB%8F%84%20%ED%95%9C%EB%8B%A4.">링크</a>를 참고 부탁드립니다)​</p><p><strong>1. Client Hello 「Client → Server」<br></strong>먼저 Client가 Server에게 접속을 하면서 시작되는 단계입니다.<br>Client는 <strong>랜덤 숫자</strong>를 생성을 하고, 그 값과 자신이 지원하는 <strong>암호화 방식 List(Cipher Suite 목록)</strong>를 Server 측에 보냅니다.​</p><p><strong>2–1. Server Hello 「Server → Client」<br></strong>Client Hello에 대해 응답하는 단계로 Client와 마찬가지로 <strong>랜덤 숫자</strong>를 생성하고, 그 값과 Client가 보낸 암호화 List 중에서 한 가지 <strong>암호화 방식을 택</strong>해 Client에게 보냅니다.​</p><p><strong>2–2. Certificate<br></strong>그리고 <strong>자신(Server)의 인증서</strong>와 <strong>Root CA 인증서</strong>​를 Client에게 보냅니다.</p><p><strong>2–3. ServerKeyExchange<br></strong>Server는 자신의 인증서에 공개키가 포함이 되어있지 않으면 이 메시지를 통해서 공개키를 전달합니다. 인증서에 공개키가 포함되어 있는 경우에는 해당 메시지를 생략합니다.​</p><p><strong>2–4. ServerHelloDone<br></strong>Server는 초기 협상이 끝났다는 메시지를 Client에게 알립니다.​</p><p><strong>3–1. ClientKeyExchange 「Client → Server」<br></strong>Client는 자신이 가지고 있는 Root CA List에서 Server로부터 받은 Root CA가 존재하는지 확인합니다. (브라우저 같은 경우에는 아래와 같이 기본적으로 공용 CA 를 지니고 있습니다)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*Gwy1hj-Q0f-VP6le.png" /></figure><p>List에 Server로부터 받은 Root CA가 존재하지 않으면 경고 메시지를 보내고​</p><p>List에 Server로부터 받은 Root CA가 존재하면 그 인증서의 공개키를 가지고 Server 인증서의 Hash 부분을 복호화 합니다. 복호화에 성공을 했다면 이는 Root CA에 의해 발급 된 인증서임이 증명된 것이므로 정상으로 판단합니다.​</p><p>그러고 나서 1번 과정(Client Hello)에서 Client가 생성한 <strong>랜덤</strong> <strong>수</strong>와 2번 과정(Server Hello)에서 Server로부터 받은 <strong>랜덤 수</strong>를 이용해 <strong>Pre Master Secret(PMS)</strong>이라는 난수값을 생성하고, Server 인증서에서 <strong>공개키</strong>를 획득해 <strong>암호화</strong>한 후 Server에게 보냅니다.​</p><p>Server는 자신의 공개키로 암호화된 <strong>PMS Key</strong>를 받아 자신의 <strong>개인키로 복호화</strong>를 통해 안전하게 PMS Key를 획득합니다. 그리고 Server와 Client는 각자에게 받은 랜덤 수 + PMS를 가지고 일련의 과정을 걸쳐서 MS(Master Secret) &gt; <strong>Session Key</strong>를 생성합니다.</p><p><strong>3–2. ChangeCipherSpec<br></strong>위 협상에서 정해진 암호화 알고리즘, 개인키를 실제로 적용을 하고 Server 측에게 보냄으로써 정말로 사용하겠다는 의미를 지닌 메시지를 보냅니다.</p><p><strong>3–3. Finished<br></strong>Client는 Server에게 협상 종료하겠다는 메시지를 보냅니다.<br>​</p><p><strong>4–1. ChangeCipherSpec 「Server → Client」<br></strong>위에서 정한 알고리즘 및 개인키를 사용하겠다고 Server 측에서 확답의 메시지를 보냅니다.</p><p><strong>4–2. Finished<br></strong>Server는 Client에게 협상 종료하겠다는 메시지를 보냅니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*VXXFRFXIzylj9Mvd.png" /></figure><p><strong>5. Session<br></strong>Client와 Server는 안전한 방식으로 <strong>대칭키</strong>를 서로 가지게 되었으며 이제 이 <strong>대칭키</strong>인 <strong>Session Key</strong>를 이용한 <strong>암호화 통신​</strong>을 진행합니다.<br>​</p><p><strong>6. Session 종료<br></strong>데이터의 전송이 끝나면 SSL 통신이 끝났음을 서로에게 알려줍니다. 이때 통신에서 사용한 <strong>대칭키</strong>인 <strong>​Session Key</strong>를 <strong>폐기</strong>합니다.</p><p>위 과정을 통해 SSL 통신은 처음에는 <strong>공개키</strong>를 이용해 안전하게 PMS Key를 잔달하며, 안전하게 전달받은 <strong>PMS Key</strong>를 이용해 각자 <strong>Session Key</strong>를 만들어 안전하게 서로가 <strong>대칭키</strong>를 이용해해 암호화된 통신하는 것을 확인할 수 있었습니다.</p><h3>mTLS 통신이란</h3><p>​<strong>mTLS 의미<br></strong>위에서 암호화를 기반으로 한 인터넷 보안 프로토콜인 TLS에 대해서 알아보았습니다. 그렇다면 mTLS란 무엇일까요?</p><p>m 은 Mutual의 약자로 서로의 라는 의미를 가지고 있습니다. 즉, Server만 인증하는 것이 아닌 Server도 Client를 인증하는 통신방법을 의미합니다.</p><p>​</p><p><strong>Client-authenticated SSL HandShake 과정<br></strong>mTLS HandShake 과정은 TLS HandShake 과정에서 Server가 Client의 인증서를 요청하는 과정과 인증하는 과정이 추가됩니다.​</p><p><strong>1. Client Hello 「Client → Server」<br></strong>먼저 Client가 Server에게 접속을 하므로 시작되는 단계입니다. Client는 랜덤 숫자를 생성을 하고 그 값과 자신이 지원하는 암호화 방식 List(Cipher Suite 목록)를 Server 측에 보냅니다.​</p><p><strong>2–1. Server Hello 「Server → Client」<br></strong>Client Hello에 대해 응답하는 단계로 Client와 마찬가지로 랜덤 숫자를 생성하고, 그 값과 Client가 보낸 암호화 List 중에서 한 가지 암호화 방식을 택해 Client에게 보냅니다.​</p><p><strong>2–2. Certificate<br></strong>그리고 자신(Server)의 인증서와 Root CA 인증서​를 Client에게 보냅니다.​</p><p><strong>2–3. ServerKeyExchange<br></strong>Server는 자신의 인증서에 공개키가 포함이 되어있지 않으면 이 메시지를 통해서 공개키를 전달합니다. 인증서에 공개키가 포함되어 있는 경우에는 해당 메시지를 생략합니다.​</p><p><strong>※2–4. CertificateRequest (추가된 부분)<br>Server는 Client에게 인증서를 요구</strong>합니다.​</p><p><strong>2–5. ServerHelloDone<br></strong>Server는 초기 협상이 끝났다는 메시지를 Client에게 알립니다.​</p><p><strong>※3–0. Certificate (추가된 부분)<br></strong>Client가 자신의 인증서를 담아서 Certificate 메시지에 응답합니다<br><strong>여기서 개인키(Private Key)는 보내지 않습니다.<br></strong>​</p><p><strong>3–1. ClientKeyExchange 「Client → Server」<br></strong>Client는 자신이 가지고 있는 Root CA List에서 Server로부터 받은 Root CA가 존재하는지 확인합니다. List에 Server로부터 받은 Root CA가 존재하지 않으면 경고 메시지를 보내고</p><p>​List에 Server로부터 받은 Root CA가 존재하면 그 인증서의 공개키를 가지고 Server 인증서의 Hash 부분을 복호화 합니다. 복호화에 성공을 했다면 이는 Root CA에 의해 발급 된 인증서임이 증명된 것이므로 정상으로 판단합니다.</p><p>​그러고 나서 1번 과정(Client Hello)에서 Client가 생성한 랜덤 수와 2번 과정(Server Hello)에서 Server로부터 받은 랜덤 수를 이용해 Pre Master Secret이라는 난수값을 생성하고, Server 인증서에서 획득한 공개키를 이용해 암호화한 후 Server에게 보냅니다.​</p><p><strong>※3–2. CertificateVerify (추가된 부분)<br></strong>위 3–1의 메시지를<strong> Client 개인키</strong>로 암호화해 다시 Server에게 보냅니다. Server는 Client의 인증서를 받았으므로</p><p>공개키를 가지고 있으며, 그 공개키를 이용해서 해당 메시지 복호화를 성공하면, Server는 해당 Client가 개인키를 가지고 있음을 확신할 수 있습니다.</p><p>​그러고 나서 Server는 자신의 공개키로 암호화된 PMS Key를 자신의 개인키로 복호화를 통해 안전하게 PMS Key를 획득합니다. 그리고 Server와 Client는 각자에게 받은 랜덤 수 + PMS를 가지고 일련의 과정을 걸쳐서 MS(Master Secret) &gt; Session Key를 생성합니다.</p><p>​<br><strong>3–3. ChangeCipherSpec<br></strong>위 협상에서 정해진 암호화 알고리즘, 개인키를 실제로 적용을 하고 Server 측에게 보냄으로써 정말로 사용하겠다는 의미를 지닌 메시지를 보냅니다.</p><p>​<br>그 이후 과정은 TLS와 동일합니다. <br>(추가된 부분은 보라색 CertificateRequest / Certificate/ Certificate Verify)</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*SCnVRhJrGLqHGhgk.png" /></figure><p><strong>Citadel 이란 무엇인가?<br></strong>TLS와 mTLS에 의미 및 인증과정에 대해서 알아보았습니다. 이제부터 Citadel에 대해서 본격적으로 알아보겠습니다.<br>​</p><p><strong>Citadel 이란 무엇일까요?</strong><br>Citadel 이란 Istio에서 Security 관련 기능을 담당을 하며 Client 인증서를 관리하는 하는 모듈입니다.</p><h3>GCGS에서 Citadel은?</h3><p>그렇다면 GCGS에서는 왜 Istio의 Citadel을 필수로 설치해 사용하는 걸까요?</p><p>​답을 찾기 전에 먼저 Agones에서 Multi-Cluster Allocation을 사용하기 위해서는 무엇이 필요한지 살펴봐야 합니다.<br>​</p><ol><li><strong>Server 인증서<br></strong>Allocate 또는 Multi-cluster Allocation을 진행하기 위해서는 agones-allocator의 External IP로 Server 인증서 발급이 필요합니다. External IP로 인증서 발급은 아래 명령어를 통해서 할 수 있습니다.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7b122707d03227790073318929d42c/href">https://medium.com/media/fe7b122707d03227790073318929d42c/href</a></iframe><p>조금더 정확하게 말하면 초기 helm을 통해 agones를 설치하면 agones-allocator pod가 생성되면서 아래와 같이 인증서가 발급됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*o9dhuLVBE__uj4SL.png" /></figure><p>============================</p><p>allocator-client-ca는 클라이언트 인증서로 Server 측에서 사용하는 Client Whitelist.</p><p>allocator-tls는 agones-allocator의 Server 인증서와 개인키.</p><p>allocator-tls-ca는 Server Root CA 인증서.</p><p>============================</p><p>하지만 agones-allocator Service의 External IP 가 발행 전에 발급된 인증서이므로 External IP로 다시 인증서 갱신하는 작업이 필요한데, 그 작업을 위 명령어를 통해서 진행이 필요합니다.</p><p><strong>2. Client 인증서<br></strong>mTLS 통신이므로 Server뿐만 아니라 Client도 인증서가 필요합니다.<br>(Self Sign Client 인증서 생성하는 방법은 <a href="https://mcilis.medium.com/how-to-create-a-self-signed-client-certificate-with-openssl-c4af9ac03e99">링크</a> 참고)</p><p>​위 링크와 같이 Openssl을 이용해 Client 인증서, Client 개인키, Client Root CA를 생성하고 해당 정보를 담고있는 Secret이 필요합니다.</p><p>​</p><p><strong>3. GameServerAllocationPolicy라는 CRD Object 생성이 필요</strong>GameServerAllocationPolicy란 Multi-Cluster Allocation을 진행시 Allocate할 Cluster의 정보를 담고 있는Object로써 agones-allocator의 External IP 정보, GameServer의 NameSpace 이름, Client 인증서 정보가 담긴 Secret (2번에서 생성한 Secret) 그리고 Multi-Cluster Allocation 진행시 다수의 GameServer<br>Allocation Policy 중 선택의 기준이 되는 Priority와 Weight 값을 지니고 있는 Object입니다.</p><p>이 정보들을 포함하고 있는 GameServerAllocationPolicy를 Cluster 별로 생성이 필요합니다.<br>​​</p><p><strong>4. allocator-client-ca에 Client 인증서 추가<br></strong>Server 측에서 Client 인증서에 대한 WhileList를 담당하는 Secret으로써 2번에서 생성한 Client 인증서를 allocator-client-ca Secret에 추가가 필요합니다.</p><p>이렇게 4개의 작업인 Server인증서 생성, Client 인증서 생성, Cluster마다 GameServerAllocationPolicy 생성, Client 인증서 WhiteList 처리 작업들을 Cluster가 추가될때마다 수동으로 해야 한다면 매우 번거로운 일이 될 것입니다. 하지만 <strong>Citadel</strong>과 <strong>GCGS</strong>를 사용하게 되면 쉽게 생성 및 관리를 할 수 있습니다.</p><h3>Citadel</h3><p>OpenSSl 명령어로 생성해야 했던 Client 인증서를 Citadel이 대체 가능합니다.</p><p>아래 명령어를 통해서 Citadel을 생성을 하면 Citadel은 현재 존재하고 있는 각각의 Service Account마다 Client 인증서를 발급해 주게 됩니다. 또한 Citadel을 설치 후에 생성하는 Service Account에 대해서도 Client 인증서를 발급해줍니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8ae66cc0aafbaa46791ff5940c4af13/href">https://medium.com/media/f8ae66cc0aafbaa46791ff5940c4af13/href</a></iframe><p>생성된 Secret 중 대표적으로 default 네임스페이스에 위치한 istio.default secret을 확인해 보면 아래와 같습니다.</p><p>「cert-chain.pem」 은 Client 인증서이고 「key.pem」 은 Client 개인키 , <br>그리고 마지막 「root-cert.pem」 은 Self Signed Client Root CA입니다.</p><p>Citadel이 생성한 어떠한 Secret 내용을 살펴보아도 default 형태와 동일하게 Client 인증서, Client 개인키, Client Root CA를 가지고 있는 것을 확인 할 수 있습니다. 그리고 istio.default, istio.agones-sdk secret 두 개의 Secret만 비교해 봐도 알 수 있지만 Client Root CA는 동일한 걸 알 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*qwN5OvF4G2Ho9_J8.png" /><figcaption>istio.default secret 내용</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/0*irKlxBS89CtEczta.png" /><figcaption>istio.agones-sdk secret 내용</figcaption></figure><h3>GCGS</h3><p>GCGS는 아래와 같이 간단하게 Realm에 Cluster1과 Cluster2를 추가만 해주면 Cluster 마다 생성이 필요한 GameServerAllocationPolicy 생성 작업 및 allocator-client-ca에 Client 인증서 추가를 자동으로 해줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HZgrYeQyRRDTlo19.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sgUDhiWc1OMIW-gr.png" /></figure><p>위와 같이 Realm에 Cluster를 추가 해주면, 먼저 Google API는 Citadel이 생성한 default 네임스페이스에 있는 istio.default 이름의 Secret의 값을 참조해서 또 다른 Secret을 생성합니다. (Secret 이름은 Realm에 Cluster 포함할 때 사용자가 지정했던 이름이 포함되어 있습니다)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/0*GptdtSP58fAs5fFC.png" /><figcaption>kubectl get secret</figcaption></figure><p>생성된 Secret을 확인해 보면 istio.default의 Client 인증서와 개인키 값을 가지며 Server Root CA를 가지고 있습니다. 여기서 왜 Client Root CA가 아닌 Server Root CA를 담고 있을까요?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EDl2PPZqn2uvC_uo.png" /><figcaption>kubectl get secret allocator-secret-cluster1-… -o yaml</figcaption></figure><p>그 이유는 Citadel은 Self Signed 인증서이기 때문입니다. 즉 공인 CA가 아니면 Client가 Request를 보낼 때 자신(Server)의 CA를 같이 보내야만 합니다. 그래서 Client Root CA가 아닌 Server Root CA의 정보를 담고 있는 것입니다.</p><p>​​그리고 Google API는 Cluster1에는 Cluster1과 Cluster2의 GameServer<br>AllocationPolicy생성해주고 Cluster2도 마찬가지로 Cluster1과 Cluster2의 GameServerAllocationPolicy를 생성해줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*hkEFi8d48KOpbN2w.png" /><figcaption>kubectl get gameserverallocationpolicy</figcaption></figure><p>그리고 GameServerAllocationPolicy정보를 확인해보면 위에서 생성한 Google API가 따로 생성한 Secret을 지니고 있음을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/0*5CrlU3yAJqiyMaU9.png" /><figcaption>kubectl get gameserverallocationpolicy allocation-cluster1-… -o yaml</figcaption></figure><p>마지막으로 allocator-client-ca에 허용해 줄 Client 인증서를 추가해 줍니다. 여기서 allocator-client-ca Secret의 정보를 확인해 보면</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NAnitlsZK4iqKb1K.png" /><figcaption>kubectl get secret allocator-client-ca -n agones-system -o yaml</figcaption></figure><p>Client 인증서 값이 아닌 Client Root CA 값이 추가되어 있는 것을 확인할 수 있습니다. 당연히 특정 Client 인증서만 추가해 특정 Client 만 허용할 수도 있습니다. 하지만 Client Root CA를 추가하게 되면 Citadel이 Service Account마다 생성한 Client 인증서를 모두 허용 되게 됩니다. 즉 Google API는 특정 Client 인증서뿐만 아니라 Citadel이 생성한 모든 Client 인증서로 접속이 가능하게 하기 위해 Client Root CA를 추가해 줍니다.​</p><p>그럼으로써 위에서 만든 Client 인증서로 Server에 Multi-cluster Request를 보낼 수 있는 환경이 갖춰졌습니다.</p><h3>​Multi-cluster Allocation 흐름</h3><p>이제 Multi-cluster Allocation이 되는 흐름을 살펴보도록 하겠습니다.</p><p>매치메이커가 Cluster1에게 Multi-Cluster Allocation Request를 보내게 보내면 우선 Priority가 낮게 설정된 GameServerAllocationPolicy를 선택하게 될 것입니다. ( Priority와 Weigh이 동일한 값이면 랜덤으로 GameServerAllocation<br>Policy가 선택이 될 것입니다) 여기서는 여러 가지 요인으로 인해서 Cluster2의 Game ServerAllocationPolicy가 선택이 되었다고 가정하겠습니다.</p><p>​<br>그렇다면 매치메이커로 부터 Multi-ClusterAllocation Request를 받은Cluster1의 aognes-allocator는 Cluster2의 GameServerAllocationPolicy를 확인해 Cluster2의 agones-allocator External IP를 획득 후 해당 IP로 Allocate Request를 보낼 것입니다. Request를 받은 Cluster2는 여러가지 과정을 걸친 후(HandShake) Client 인증서를 요구할 것입니다. 그러면 Cluster1은 Game<br>ServerAllocationPolicy에 포함되어 있는 Secret의 Client 인증서를(Client 개인키를 제외한) Cluster2에게 보낼 것이며 그리고 PMS Key를 생성해 Cluster2의 공개키로 암호화해 보낼 것입니다.</p><p>그리고 이 메시지를 Client 개인키로 암호화해서 한 번 더 보내고 Server의 Root CA도 보낼 것입니다. (위 mTLS 통신과정 3–0에서 3–2까지)</p><p>​그러면 Cluster2 측은 allocator-client-ca에 해당 Client 인증서가 있는지 확인을 해 볼 것이고 Client 개인키로 암호화된 메시지는 Client 인증서에 있는 공개키로 복호화를 진행할 것입니다. 만약 복호화가 성공하였다면 이는 Cluster1이 해당 Client 인증서의 개인키를 지니고 있다고 증명된 것이기에 정상으로 판단합니다. 그리고 Client인증서는 공용 CA 사용이 아님으로 Cluster1이 보낸 CA가 자신(server)의 Root CA 인지도 확인할 것입니다. 이 모든 것이 정상적이면 해당 Client의 Allocate Request는 받아들여지게 될 것입니다.</p><p>​이런 식으로 Client와 Server 간에 서로를 인증하는 mTLS 통신이 이루어집니다.</p><h3>GCGS에서 꼭 Citadel을 사용하는 이유가 있는가?</h3><p>그렇다면 왜 하필 Citadel을 사용하는 것일까요?</p><p>정확한 이유는 알 수가 없었습니다. 하지만 Realm에 Cluster를 추가하게 되면 Google API는 istio.default 이름의 secret을 참조해 사용한다는 것은 확인할 수 있었습니다.</p><p>​이를 확인하기 위해 Citadel 설치 없이 수동으로 Self signed 인증서를 발급 하고 인증서, 개인키, Root CA 값을 지닌 istio.default secret 생성후에 Realm에 Cluster를 추가해보았습니다</p><p>​Google API는 istio.default란 <strong>이름</strong>만 보고 istio.default안의 값을 참조해 자동으로 Secret 생성했고 , GameServer AllocationPolicy 생성했으며 allocator-client-ca에 인증서 추가해 주는 것을 확인할 수가 있었습니다.</p><p>​Google API가 장확하게 어떻게 동작하는지에 대해서는 Code Open이 안되어있기 때문에 확인할 수 없었지만 테스트를 통해서 istio.default라는 이름의 Secret을 참조해 자동으로 GameServerAllocationPolicy등의 작업을 수행한다는 것을 알 수 있었습니다.</p><h3>정리</h3><p>GCGS에서의 Citadel은 Service Account마다 인증서를 발급해 주는 것이 전부입니다. 나머지는 Citadel이 생성한 istio.default의 이름을 지닌 Secret를 이용해 Google API에서 새로운 Secret을 생성하고 이를 포함하는 GameServer<br>AllocationPolicy를 생성하며 allocator-client-ca에 Citidel이 생성한 Client Root-CA를 추가 해줍니다.​</p><p>그리고 allocator-client-ca에 Client 인증서가 아닌 Client Root-CA를 추가해주는데 그 이유는 istio.default가 지닌 인증서 뿐만 아니라 Citadel이 생성한 모든 ServiceAccount의 Client 인증서를 Allow 하기 위함이였습니다.</p><p>또한 Multi Cluster Allocation 요청을 보낼 때에는 Client 인증서, Client 개인키, 공용 CA로 Client 인증서가 서명되지 않은 경우에는 Server Root CA가 필요합니다.</p><p>그리고 allocator-tls Secret에 Root CA가 포함되어 있지 않은 이유는 Client에서 Server Root CA 사용 시 Server의 개인키를 노출하지 않기 위함입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c416b9ecea2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/citadel-%EA%B3%BC-gcgs%EC%9D%98-%EA%B4%80%EA%B3%84-c416b9ecea2b">Citadel 과 GCGS의 관계</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCGS를 이용한 게임 서버 배포]]></title>
            <link>https://medium.com/cloudvillains/gcgs%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EA%B2%8C%EC%9E%84-%EC%84%9C%EB%B2%84-%EB%B0%B0%ED%8F%AC-4df8cb22dc7?source=rss-256a1395a4d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df8cb22dc7</guid>
            <category><![CDATA[agones]]></category>
            <category><![CDATA[multi-cluster]]></category>
            <category><![CDATA[gcg]]></category>
            <dc:creator><![CDATA[김도영]]></dc:creator>
            <pubDate>Thu, 14 Apr 2022 03:01:56 GMT</pubDate>
            <atom:updated>2022-04-19T00:34:15.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*-wulJtuUbXxUit0M.png" /></figure><p>Agones라는 OSS를 이용해 Kubernetes에 Dedicated GameServer를 쉽게 배포 및 관리를 할 수 있도록 하는 GCGS에 대해서 알아보겠습니다.​</p><h4>Agones란 무엇일까?</h4><p>Agones 또한 Google에서 개발한 OSS이며, Dedicate Gameserver를 Host, Run, Scale 하기 위한 라이브러리입니다.​</p><h4>GCGS를 사용해야하는 이유?</h4><p>Agones를 사용해 Gameserver를 관리하기 위해서는 Kubernetes 위에 Agones Install이 필요합니다. 하지만 Kubernetes를 VM 위에 직접 설치하고 설정하기에 너무 많은 번거로움이 따르기에 Public Cloud에서 제공하는 Full Managed Kubernetes Service를(예를 들어 GKE) 사용하곤 합니다.<br>동일한 이유로 Kubernetes에 Agones를 설치하였지만, Agones에서 정의한 CRD Object생성, 연동 및 Gameserver 배포 등을 일일이 진행하려고 하면, 매우 번거로운 일이 될 것입니다. 이러한 번거로움을 줄이기 위해 쉽게 연동되고 Realm 단위로 Gameserver를 쉽게 한번에 배포할 수 있도록 제공하는 제품이 GCGS입니다.</p><p>또한 GCGS는 비용적으로도 매우 적은 비용이 발생하므로(거의 GKE 비용만 발생한다고 생각하면 됩니다)GCGS를 사용하지 않을 이유가 없다고 생각합니다.</p><h4>용어 정리</h4><p>먼저 간단하게 용어 정리를 하고 넘어가겠습니다.</p><h4>Realm</h4><p>GCGS는 Realm이라는 단위로 여러 cluster를 묶어 관리를 합니다. GameServer 배포시 Realm이라는 단위로 한번에 여러 Cluster에 Gameserver배포를 할 수 있습니다.</p><h4>Cluster</h4><p>Kubernetes Cluster를 의미합니다.</p><h4>GameServer Deployment</h4><p>게임 서버 배포를 관리합니다. GameServer Deployment 하위에는 GameServer를 구성하는 내용을 담고 있는 GameServer Config가 존재하며 Manage Rollout을 통해서 특정 GameServer Config를 선택해 배포할 수 있습니다.​</p><h4>GameServer Config (= Fleet)</h4><p>GameServer의 설정 내용을 지니고 있는 부분입니다. 한 번 생성하면 수정이 불가하며 여러 Config 생성이 가능합니다.</p><h4>GameServer 배포</h4><p>바로 GCGS를 이용해 GameServer를 배포해 보겠습니다.​</p><h4>1. GKE</h4><p>먼저 Agones를 설치하기 위해서는 Kubernetes 환경이 필요하기 때문에 GCP의 Full Managed Kubernetes Service인 GKE를 아래 명령어를 이용해 Seoul 리전 Cluster를 생성합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07198d60a0ebece9ab8080d75edc1701/href">https://medium.com/media/07198d60a0ebece9ab8080d75edc1701/href</a></iframe><h4>2. Agones</h4><p>Kubernetes 환경이 갖추어졌으면 Helm을 통해 Agones 설치를 합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5578a0eca76c86013da001a1fccddcc4/href">https://medium.com/media/5578a0eca76c86013da001a1fccddcc4/href</a></iframe><h4>3. Realm</h4><p>Agones 설치가 완료 되었으면 아래와 같이 Realm에 Cluster를 추가합니다.<br>Realm 생성은 「game servers &gt; realm &amp; clusters」로 이동해 「create realm」으로 생성해 주면 되며 Cluster 추가는 「add game server cluster」로 추가해 주면 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*8GBKvzqBpgK12ZMI" /></figure><h4>4. GameServer Deploy</h4><p>GameServer를 배포하기 위해서는 먼저 Deployment를 생성합니다.<br>「game server deployments」로 이동해서 「create deployment」로 Deployment 생성이 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*iHuL20xUVgBcQdGm" /></figure><p>​</p><p>그런 다음에 생성한 Deployment의 List configs로 이동해 「create config」를 통해 Gameserver config 생성을 합니다. <br>레이싱 게임인 「supertuxkart」 게임 서버를 배포할 것이므로 「gcr.io/agones-images/supertuxkart-example:0.3」 이미지를 사용한 config를 생성을 해줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*qvrvoPTT1Zar9iFz" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b82b8d14ce39f14919e690e08f92516c/href">https://medium.com/media/b82b8d14ce39f14919e690e08f92516c/href</a></iframe><p>이제 Manage Rollout을 통해서 GameServer를 배포해줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*2OX_TXeH1oeDWJjq" /></figure><p>​</p><p>배포를 하게 되면 「kubectl get gameserver」로 배포된 gameserver의 정보를 확인할 수 있으며</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*GVacwKgm0yghvWhC" /></figure><p>​</p><p>또한 배포된 게임 서버로 문제없이 접근 및 게임 플레이가 되는 것을 확인할 수 있습니다. 게임서버 접근은 「kubectl get gameserver」로 확인했을때 출력되는 IP와 Port를 이용해서 접근이 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*pEoKuLNcR7INEmQc" /><figcaption>GameServer 접근</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*XeDFVhc8E_TA8RMp" /><figcaption>문제없이 GameServer 접근 완료</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*rMaJbiZ3bw-RI8UM" /><figcaption>문제없이 게임 플레이 완료</figcaption></figure><h4>GameServer Ready 상태</h4><p>그렇다면 Gameserver는 어떻게 Ready 상태를 가지게 되는 것일까?<br>agones는 gameserver를 관리하는 game cycle이 존재합니다. 게임이 잘 올라갔는지, 사용자가 문제없이 access 했는지 등의 여러 상태를 관리를 해야 하는데 이러한 상태를 받는 서버가 gameserver pod가 올라갈 때 sidecar 형태로 같이 올라오게 됩니다.(kubectl get pod로 확인해 보면 container가 2/2로 2개인 것을 확인할 수 있습니다)​</p><p>sidecar로 올라온 container는 sdk server로써 game container에서 sdk server로 health()/ ready()를 보내면 sdk server는 gameserver의 상태를 agones-controller에게 보내 gameserver의 state를 업데이트하게 된다. 그럼으로써 gameserver의 state가 scheduled에서 ready 상태로 변경이 하게 됩니다.​</p><p>gameserver의 cycle을 control 하기 위해서 wrapper를 사용할 수도 있습니다. 예를 게임 이미지를 실행 후 client들의 access를 기다리는 시점이 아래와 같이 「listen 30000」 란 문구가 출력된 후라고 가정하겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*KctdjqRnqL7Iwksy" /></figure><p>이러한 경우 「listen 30000」문구가 출력이 되면 gameserver에서 sdk server에게 ready() 등의 상태를 보내야 하는데 이를 원하는 언어인 go 또는python 등을 이용해 wrapper를 생성하므로 control이 가능합니다. wrapper완료되었다면 다시 이미지화해서 GameServer Config로 배포를 하면 됩니다.</p><h4>GameServer Allcated 상태</h4><p>Gameserver를 배포하고 배포된 Gameserver로 Client 입장에서 접근까지 해보았습니다. 하지만 유저가 Gameserver에 접근을 했지만 어떤 서버에 접근을 했는지 표시를 할 수 있는 방법이 있을까요?</p><p>바로 Gameserver Allocate를 사용하면 됩니다. Gameserver Allocate를 간단하게 정의하면 Gamserver에 유저가 접근했을 시, “현재 이 Gameserver에는 유저가 접속해 있습니다” 를 마크를 해주는 기능입니다. 즉 Allocate를 생성을 해주게 되면 Gameserver의 stats를 Ready에서 Allocate로 변경해 줍니다.​</p><p>Allocate 상태를 지닌 Gameserver는 유저가 접속해서 Play 중이라는 의미를 가지고 있으며 Allocate 상태가 되면 강제로 Gameserver를 삭제 또는 SDK를 이용한 Shut down을 해주지 않는 이상 Pod는 삭제되지 않습니다.</p><h4>GameServer Allcated 흐름</h4><p>Allocate는 아래와 같은 프로세스로 진행됩니다. 먼저 MatchMaker는 kubernetes API를 통해서 GameserverAllocate를 생성합니다. 그러면 Agones는 Allocatable(Ready 상태인) Gameserver를 찾아서 Allocate 해주고 AllocateGameserver의 정보를 MatchMaker에게 Return을 합니다. 정보를 Return 받은 MatchMaker는 Gameserver IP 등의 정보를 이용해 Player가 Gameserver에 접근할 수 있도록 매칭하면 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*khZ8HJ7vfdRtedMw.png" /></figure><h4>GameServer Muticluster Allocate</h4><p>GameServer Allcated의 확장된 개념입니다. Realm 그룹 안에 속해있는 Cluster는 Multi-Cluster이며 GameServer Multi-cluster Allocation 생성을 하면 Realm 안에 속해있는 Cluster 중 한 Cluster가 선택되고 Fleet의 Scheduling 방식에 따라 GameServer Allocate가 진행이 됩니다.​</p><p>여기서 중요하게 생각해 봐야 할 점은 Realm으로 Clsuter들은 묶을 때 어떠한 기준으로 Cluster를 묶어야 할 것인지를 생각해봐야 합니다.</p><p>그에 대한 해답은 “latency가 비슷한 cluster들로 묶어야 한다” 입니다. <br>왜 latency가 비슷한 cluster들로 묶어야 할까요? 예를 통해 알아보겠습니다.</p><p>latency 차이가 많이 나는 서울 리전 cluster와 유럽 리전 cluster와 realm으로 묶여있다고 가정해보겠습니다.</p><p>서울 리전 Cluster에 갑작스럽게 많은 Client의 접속으로 인해서 Allocatable Gameserver가 모두 소진되었을 경우에 동일 Realm으로 묶여있는 유럽 리전의 Cluster에 Gameserver에 Allocate가 될 수도 있습니다. 이러한 상황에서 서울에서 Game 접속한 Client가 Latency가 낮은 서울리전에서 Game을 즐기기를 원했지만 Latency가 높은 유럽 Cluster에 위치한 게임 서버에 Allocate 될 수도 있습니다. 이러한 경우를 피하기 위해서 Realm은 비슷비슷한 Latency를 가지는 Cluster로 묶어야합니다.</p><h4>GameServer Muticluster Allocate 사용​</h4><p>이번에는 Multi-cluster Allocation가 어떤식으로 진행되는지에 대해 알아보겠습니다. 먼저 Multi-cluster를 구성하기 위해 cluster 1대를 추가로 생성합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/009b1e71bbd4a836b8a50b666e8b8c65/href">https://medium.com/media/009b1e71bbd4a836b8a50b666e8b8c65/href</a></iframe><p>그런 후 이전과 동이랗게 Helm으로 agones를 설치해 주고</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3807bbad3efb67c6d506571060bfd687/href">https://medium.com/media/3807bbad3efb67c6d506571060bfd687/href</a></iframe><p>Realm에 방금 전에 생성한 Cluster를 추가시켜줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*tfPn4BfPG_gCiv1Z" /></figure><p>추가시켜주면 바로 새 Cluster에서 Gameserver가 올라오는 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*gCB0A6i8PYTsJppB" /></figure><p>​​</p><p>「kubect get service -n agones-system」 명령어를 실행해 보면 agones-allocator라는 LoadBalancer Type의 service가 있는 것을 확인할 수 있는데</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*YLHL4tGFFn_kx21q" /></figure><p>​</p><p>agones-allocator의 External IP를 가지고 인증서를 갱신을 할 필요가 있으므로 아래 명령어를 통해서 인증서 갱신을 해줍니다.<br>(cluster 2대 모두에서 진행 필요)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81342605c0bcad5f30ed4fb46206a20/href">https://medium.com/media/d81342605c0bcad5f30ed4fb46206a20/href</a></iframe><p>그런 후 cluster 사이의 보안 연결을 용이하게 하는 멀티 클러스터 측 인증서 관리자로써 citadel을 사용하기 위해 아래 명령어를 통해 설치합니다.<br> (cluster 2대 모두에서 진행 필요)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41b938b8025e07bc90395cc44bc7dbe4/href">https://medium.com/media/41b938b8025e07bc90395cc44bc7dbe4/href</a></iframe><p>모두 완료가 되었으면 이제 multi cluster gameserver allocate 준비가 완료되었습니다. 아래 명령어를 통해 GameServerAllocation을 생성해 보겠습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37896e6cb353997e885386187d058aad/href">https://medium.com/media/37896e6cb353997e885386187d058aad/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*z5pKBvD5hU7EJ8GA" /><figcaption>생성 후 출력되는 yaml 파일</figcaption></figure><p>​</p><p>cluster1에서 확인해 보면 gameserver state가 ready에서 allocate로 변경된 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*bzAydTeKa52KmybM" /></figure><p>​</p><p>한 번 더 allocate를 생성해 주면 cluster2도 아래와 같이 allocate 된 것을 확인할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*cHmbEiuyLpb0Mxn-" /></figure><p>위에서 알아본 것과 같이 Allocate를 생성할 때마다 Cluster를 이동하면서 Allocate가 진행된 것을 확인 할 수 있었습니다. 그렇다면 왜 Cluster를 이동하면서 Allocate가 되는 것일까요? 어떠한 기준으로 Cluster가 선출이 되어 Gameserver를 Allocate 하게 되는 것일까요?</p><p>먼저 Gameserverallocationpolicy에 대해서 알아야 합니다. <br>Gameserverallocationpolicy는 Multi-cluster Allocation의 Rule을 정하기 위한<br>Agones에서 정의한 CRD 입니다. Gameserverallocationpolicy에는 priority와 weight라는 항목이 존재하며, Multi-cluster Allocation를 하게되면 priorty와 weight에 따라서 Cluster가 선택이 되게 됩니다. 기본으로는 동일한 priorty와 weight 값을 지님으로 균등하게 Allocate가 진행이 되게 됩니다</p><p>또한 Gameserver의 연결 정보인 Namespace, agones-allocator의 External IP(endpoint), K8S의 API key를 포함하고 있습니다.</p><p>그렇다면 Gameserverallocationpolicy는 언제 생성이 되는 것일까요?<br>Gameserverallocationpolicy는 Realm에 cluster를 추가하는 동시 아래와 같이GCGS에서 자동으로 Cluster마다 Realm에 포함되어있는 Cluster의 갯수만큼Gameserverallocationpolicy를 생성을 해주게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*YYfNNsfo_FQ6813sXhtCGg.png" /></figure><p>정리를 해보면 Multi-cluster Allocation 이 생성이 되면 Gameserverallocationpolicy Prioirty에 의해서 Allocate 될 Cluster가 정해지게 되며 Gameserverallocationpolicy의 endpoint로 Allocate를 진행하게 됩니다.</p><p>그리고 ​참고로 Allocate는 Performance 상 Create만 가능하며 저장되지 않습니다. Allocate가 된 Server를 확인하려면「kubect get gameserver」로 State를 확인하면 됩니다.</p><h4>agones-allocator service를 이용한 Muticluster Allocate</h4><p>이번에는 매치메이커 서버가 외부에 존재하는 경우에 agones-allocator service를 이용해 allocate 하는 방법에 대해 알아보겠습니다.​</p><p>매우 간단합니다. 아래 명령어를 통해서 client.key , client.crt, ca.crt 파일을 추출해 API Request를 보내면 됩니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ccb0e275488900b693bdba34be1ac7/href">https://medium.com/media/08ccb0e275488900b693bdba34be1ac7/href</a></iframe><h4>kubernetes api를 이용한 Muticluster Allocate</h4><p>이번에는 kubernetes api를 이용해 allocate를 해보겠습니다.</p><p>아래와 같이 먼저 kube porxy를 백그라운드에 실행시킨 후 kube-api에게 post로 API Request를 보내주면 됩니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5e4b573ef4cbc430f0b26a3c522789f/href">https://medium.com/media/b5e4b573ef4cbc430f0b26a3c522789f/href</a></iframe><h4>마무리</h4><p>GCGS를 이용해 게임 서버 배포를 진행해 보았습니다. 게임 서버라고 해서 어렵게만 생각했었지만 GCGS를 활용하면 매우 쉽게 배포 및 관리를 할 수 있을 것 같다는 생각이 들었습니다. 그리고 Allocate와 Multi-cluster Allocation에 관해서도 알아보았습니다. Allocate는 내가 원하는 Cluster의 Gameserver를 지정할 수 있다는 장점이 존재했습니다. Agones를 설치하면 Load balancer type의 agones-ping-http-service 과 agones-ping-udp-service들이 생성되는데 MatchMaker서버에서 Gameserver Allocate을 할 때 이들을 이용해 제일 낮은 Latency를 지닌 Cluster를 선별 후 Allocate 하는 방식으로 사용한다면 매우 유용할 것 같다고 생각했습니다. <br>반면에 Multi-cluster Allocation는 Realm으로 묶여있는 Cluster 들에게 Allocate 해준다는 큰 장점을 가지고 있지만, Latency에 따른 Cluster 선별은 어떤 식으로 구현해야 할지는 그려지지 않았습니다. GameServerAllocationPolicy의 priorty를 사용해 원하는 Cluster의 우선순위를 지정할 수 있다. 하지만 Latency에 따른 Cluster를 선별하기 위해서는 Latency를 비교하고 낮은 Latency인 Cluster의 GameServerAllocationPolicy의Priorty를 낮춰 Allocate를 진행해야 할 것으로 보이는데 이러한 방식이라면 오히려 Multi-cluster Allocation 보다는 일반적인 agones-allocate 서비스를 이용한 Allocate 방식을 이용하는 방법이 더 좋은 방법이 될 것 같다고 생각했습니다. 반대로 Zone마다 Cluster를 생성해 Realm으로 묶어 Multi-cluster Allocation를 한다고 하면 Latency에 민감하지 않으므로 Multi-cluster Allocation이 더 좋은 방법이라고 생각이 듭니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4df8cb22dc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/gcgs%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EA%B2%8C%EC%9E%84-%EC%84%9C%EB%B2%84-%EB%B0%B0%ED%8F%AC-4df8cb22dc7">GCGS를 이용한 게임 서버 배포</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP IAM by Terraform]]></title>
            <link>https://medium.com/cloudvillains/gcp-iam-by-terraform-f33228da7efb?source=rss-256a1395a4d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f33228da7efb</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[ami]]></category>
            <category><![CDATA[메가존클라우드]]></category>
            <dc:creator><![CDATA[김도영]]></dc:creator>
            <pubDate>Tue, 26 Oct 2021 08:34:39 GMT</pubDate>
            <atom:updated>2021-10-27T16:26:18.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>1. IAM Create ServiceAccount</h4><h3>시작</h3><p>최근에 IAM을 Terraform통해 관리 하고 싶다는 요구사항을 받았습니다.</p><p>Terraform은 항상 Infra관련 내용만 다뤄보았기 때문에 IAM 관련 부분은 조금 어설프고 낯설었습니다. 하나 하나씩 준비해가면서 느낀 점은 IAM Terraform Code는 Infra를 다루는 것에 비해 매우 간단하다는 것 입니다.​</p><p>그렇지만 권한을 다루는 작업이기 때문에 코드 작성과 적용 할 때 주의해야 할 점들이 몇 가지 있었습니다. 그 중 하나는 “Authoritative”라는 특성이었습니다. IAM Terraform 관련해서 검색하다 보면 Authoritative 또는 Non-Authoritative라는 단어가 꽤 자주 등장하는데, 이 Authoritative라는 특성이 무엇인지 파악하는 것은 중요합니다.</p><p><a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam">https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam</a></p><p>처음에 Authoritative에 대한 개념이 없는 상태로 Authoritative한 로직을 이용해 코드 작성 후 Role 부여하고 Apply를 실행하더니, 예상과는 달리 내가 정의한 Role이 추가로 붙는 형태가 아니라 이전에 지니고 있던 Role들을 삭제 후, 내가 정의한 Role만 부여되어있는 형태가 되었습니다.</p><p>즉, Owner 권한을 포함해 이전에 부여한 모든 Role이 삭제가 되었고, 내가 정의한 viewer Role만 남게 되는 상황이 되었습니다. 결국엔 스스로 Role추가가 불가한 View 역할만 가지게 되어 아무것도 할 수 없는 상태가 되었고, Organization을 관리하시는 담당자에게 다시 Owner Role 부여를 요청하는 일이 발생했습니다.</p><p>즉, 코드는 간단하지만 이러한 주의점이 있으니 코드 작성 시 참고하길 바랍니다.</p><h3>개요</h3><p>IAM 관련한 시나리오를 아래와 같이 세웠고, 해당 시나리오를 Terraform 코드로 작성했습니다. 첫번째는 service account 생성 및 Role Binding하는 코드를 살펴 보겠습니다.</p><p><strong>1. service account 생성 및 Role Binding</strong></p><p>2. service account Key 생성 및 Terraform Cloud에서 확인 방법</p><p>3. custom role 생성 및 부여</p><p>4. organization Policy 컨트롤</p><p>5. dataset access 권한 설정</p><h3>사용 가능 CASE</h3><p>A. 단일 및 복수개의 service account 생성 및 Role 부여</p><h3>코드 구조</h3><p>코드는 아래와 같은 구조로 작성했습니다.​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*r254z3nG0hi0ZvkFfRBDzg.png" /><figcaption>코드 구조</figcaption></figure><h3>코드 리뷰</h3><h4>1. ./modules/iam/var.tf</h4><p>변수들을 받기 위한 파일이며, 해당 파일에서는 변수들의 type 및 default 값을 지정했습니다.</p><p>선언하지 않는 (사용하지 않을) 변수에는 default 값을 지정해 줌으로써 terraform plan 또는 apply를 실행 했을 시, 값이 선언되어 있지 않았다는 오류가 발생하지 않도록 하였습니다. (project_id, region은 제외)</p><pre>######################################<br>## Default <br>######################################</pre><pre>## Project <br>variable &quot;project_id&quot; {<br>    type = string<br>}</pre><pre>## Region<br>variable &quot;region&quot; {<br>    type = string<br>}</pre><pre>######################################<br>## Service Account<br>######################################</pre><pre>## Service Account ID<br>variable &quot;names&quot; {<br>    type = set(string)<br>    default = []<br>}</pre><pre>## Service Account Name<br>variable &quot;display_name&quot; {<br>    type = string<br>    default = &quot;&quot;<br>}</pre><pre>## Service Account Description<br>variable &quot;description&quot; {<br>    type = string<br>    default = &quot;&quot;<br>}</pre><pre>## Service Account Role<br>variable &quot;roles&quot; {<br>    type = set(string)<br>    default = []<br>}</pre><p>project_id : 리소스를 생성할 Project를 정하는 변수입니다.​</p><p>region : region을 정하는 변수입니다.​</p><p>names : 생성할 service account의 고유 이름을 생성하는 변수입니다.​</p><p>display_name : service account의 보여지는 이름을 생성하는 변수이며 고유하지 않아도 됩니다.​</p><p>description : 생성 할 service account에 대해 설명을 기술하는 변수입니다.​</p><p>roles : service account에 부여하고 싶은 role을 기술하는 부분입니다. 롤은 단일 및 복수로 설정이 가능하며 role을 부여하고 싶지 않은 경우 선언을 하지 않으면 됩니다.</p><h4>2. main.tf</h4><p>사용 모듈을 정의하고, ./modules/iam/var.tf 에 값을 매칭 하기 위한 파일입니다.</p><p>아래 코드의 ★★★ 부분을 확인해보면 <br>복수개의 service account에 복수개의 role을 바인딩 하려고 변수값을 지정해둔 것을 확인 할 수 있습니다. 반대로 service account에 role부여를 원하지 않는 경우에는 roles 변수를 생략해주면 됩니다.</p><pre>## Define Modules<br>#create service accounts<br>module &quot;create_serviceaccounts&quot; {  <br>  source = &quot;./modules/iam&quot;<br>  project_id= &quot;kdyoung-int-210504&quot;<br>  region = &quot;asia-northeast3&quot;<br>  names = [&quot;test1-serviceaccount&quot; , &quot;test2-serviceaccount&quot;, &quot;test3-serviceaccount&quot;] ★★★</pre><pre>  display_name  = &quot;Test Service Accounts&quot;<br>  description = &quot;Test Service Accounts&quot;<br>  roles = [&quot;roles/bigtable.viewer&quot;,&quot;roles/bigquery.resourceViewer&quot;] ★★★<br>}</pre><h4>3. ./modules/iam/main.tf</h4><p>실질적으로 동작하는 iam 모듈파일입니다. <br>아래 코드는 setproduct와 zipmap 함수를 이용해 복수개의 service account에 복수개의 role을 부여 할 수 있도록 작성한 코드입니다.</p><pre>locals {<br>## setproduct 함수를 이용<br>names_roles_combination=setproduct(var.names, var.roles)</pre><pre>## zipmap 함수를 이용<br>names_roles_combination_map = zipmap(<br>    [for names_roles in local.names_roles_combination : &quot;${names_roles[0]}-${names_roles[1]}&quot;],<br>    [for names_roles in local.names_roles_combination : {<br>      name = names_roles[0]<br>      role = names_roles[1]<br>    }]<br>  )<br>}</pre><pre>resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>    for_each = var.names<br>    account_id   = each.value<br>    display_name = var.display_name<br>}</pre><pre>resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>  for_each = local.names_roles_combination_map<br>  role = each.value.role<br>  member = &quot;serviceAccount:${google_service_account.service_account[each.value.name].email}&quot;<br>}</pre><p>코드에 대해서 리뷰해보면</p><pre>setproduct(var.names, var.roles)</pre><p>일단 위 함수 내용을 풀어서 적어보면 아래와 같은 형태가 됩니다.<br>그렇다면 setproduct 함수란 어떤 역할을 하는 함수일까?</p><pre>setproduct([&quot;test1-serviceaccount&quot; , &quot;test2-serviceaccount&quot;, &quot;test3-serviceaccount&quot;], [&quot;roles/bigtable.viewer&quot;,&quot;roles/bigquery.resourceViewer&quot;])</pre><p>setproduct란 집합 요소의 가능한 <strong>모든 조합</strong>을 찾게 해주는 함수입니다.</p><p>( ( x , y ) * (1 , 2 ) = x1 , x2 , y1 , y2 와 같이 모든 조합을 찾게 해주는 함수)</p><p>​</p><p>즉, 위 명시된 setproduct를 실행 하게 되면 집합 요소의 가능한 모든 조합을 찾게 해줌으로 아래와 같은 결과를 가질 수 있게 됩니다.</p><pre>[&quot;test1-serviceaccount&quot; , &quot;roles/bigtable.viewer&quot; ] <br>[&quot;test1-serviceaccount&quot; , &quot;roles/bigquery.resourceViewer&quot; ] <br>[&quot;test2-serviceaccount&quot; , &quot;roles/bigtable.viewer&quot; ] <br>[&quot;test2-serviceaccount&quot; , &quot;roles/bigquery.resourceViewer&quot; ] <br>[&quot;test3-serviceaccount&quot; , &quot;roles/bigtable.viewer&quot; ] <br>[&quot;test3-serviceaccount&quot; , &quot;roles/bigquery.resourceViewer&quot; ]</pre><p>이렇게 모든 조합을 찾은 값들을 zipmap을 이용해 map 형태의 key, value로 나눠줍니다.</p><p>여기서 왜 map 형태로 변경하는 것일까?</p><p>for_each문은 set(string) 형태와 map 형태만을 받아들이도록 되어있습니다.즉, 한마디로 해당 조합들을 zipmap을 이용해 map 형태로 변경해 결론적으로는 for_each문을 사용하기 위함입니다. 그럼으로 아래와 같이 zipmap을 사용하였습니다.</p><pre>zipmap(<br>    [for names_roles in local.names_roles_combination : &quot;${names_roles[0]}-${names_roles[1]}&quot;],<br>    [for names_roles in local.names_roles_combination : {<br>      name = names_roles[0]<br>      role = names_roles[1]<br>    }]</pre><p>위 코드를 아래와 같이 풀어 써보았습니다.</p><pre>zipmap([<br>&quot;test1-serviceaccount-roles/bigtable.viewer&quot; ,<br>&quot;test1-serviceaccount-roles/bigquery.resourceViewer&quot; ,<br>&quot;test2-serviceaccount-roles/bigtable.viewer&quot; ,<br>&quot;test2-serviceaccount-roles/bigquery.resourceViewer&quot; ,<br>&quot;test3-serviceaccount-roles/bigtable.viewer&quot; ,<br>&quot;test3-serviceaccount-roles/bigquery.resourceViewer&quot; ,<br>] ,<br>[<br>&quot;name = roles/bigtable.viewer<br> role = roles/bigquery.resourceViewer&quot;,<br>&quot;name = roles/bigtable.viewer<br> role = roles/bigquery.resourceViewer&quot;,<br>&quot;name = roles/bigtable.viewer<br> role = roles/bigquery.resourceViewer&quot;,<br>&quot;name = roles/bigtable.viewer<br> role = roles/bigquery.resourceViewer&quot;,<br>&quot;name = roles/bigtable.viewer<br> role = roles/bigquery.resourceViewer&quot;,<br>&quot;name = roles/bigtable.viewer<br> role = roles/bigquery.resourceViewer&quot;<br>])</pre><p>그렇다면 zipmap이라는 함수는 어떤식으로 map형태로 변형해줄까?<br>zipmap 코드는 왼쪽의 리스트와 오른쪽 리스트가 pair로 map 형태로 묶일 수 있도록 해주는 함수입니다.</p><p>즉, 아래와 같은 Map 형태로<br>오른쪽 6개와 왼쪽 6개가 1:1 매칭 되게 해주는 함수입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*erkPLPHVxOTNLo12.png" /></figure><p>결과적으로 zipmap의 결과값은 총 6개 값이 나오며 for_each문을 사용하면 6번의 반복문을 실행 할 수 있게 됩니다.</p><p>또한 각 반복문 마다 name, role이라는 key, value 값이 매칭이 되어있어<br>한개의 service account에 role 부여가 2개 <br>총, 3개 유저가 있음으로 총 6번의 루프가 돌며 로직을 수행 하게 될 것입니다.</p><p>​&lt; 각 for문의 key 값을 가지고 해당 value 값을 얻을 수 있다는 것이 중요한 포인트 (each.value.name / each.value.role) &gt;</p><pre>resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>  for_each = local.names_roles_combination_map<br>  role = each.value.role<br>  member = &quot;serviceAccount:${google_service_account.service_account[each.value.name].email}&quot;<br>}</pre><p>정리하자면 service account 한 개 당 role을 2개 부여를 해야 되는 상황임으로<br>총 루프가 6번 돌아야 된다는 것을 알 수 있습니다. <br>그럼으로 setproduct이라는 함수를 이용해 6개의 조합을 만들고 <br>zipmap 사용해 해당 함수안에서 for 문을 이용해 왼쪽에는 Title , 오른쪽에는 실질적인 값인 key/value 형태로 나누어 왼쪽, 오른쪽 1:1 매칭해 map 형태로 변환해 줍니다. <br>최종적으로 map 형태로 변환한 값을 이용해 복수개의 service account에 복수개의 role을 부여 가능하게 for_each문을 통해 작성하였습니다.</p><h4>google_project_iam_policy VS google_project_iam_member</h4><p>위에 언급을 한 적이 있지만, 이 둘의 차이는 Authoritative한 로직인지 아닌지입니다.</p><p>즉, google_project_iam_policy라는 로직을 사용한다면 내가 정의한 Role들만을 가진 service account 또는 member, group이 될 것이고(이전에 정의되었던 Role은 삭제됨)<br>Non-authoritative한 google_project_iam_member를 사용하게 되면 내가 정의한 Role이 이전 Role에 추가가 되는 형식이 될 것입니다.</p><p>그렇다면 Authoritative한 google_project_iam_policy는 언제 사용하면 좋을까?</p><p>해당 로직은 관리자 입장에서 사용하면 좋을 것 같습니다. 예를 들면 우리 팀이 Security팀이라 가정을 해봅시다. 하위에 있는 수많은 project에서 Role들이 계속해서 추가가 될 것이며, 그 Role들 중에는 사용자가 필요한 Role보다 더 큰 Role이 부여가 되어 있는 Role이 있을 수도 있으며, 프로젝트가 끝난 후에도 삭제가 되지 않고 남아있는 Role이 있을 수도 있습니다.</p><p>이러한 Role들을 컨트롤 하기 위해 Security차원에서 Security팀에서는 Project마다 필수적으로 필요한 Role만을 남겨두고 이전 Role들을 삭제하고 싶은 경우가 있을 수 있다.</p><p>이러한 경우, Project에 꼭 필요한 Role들만 정의를 해두고 Authoritative한 google_project_iam_policy를 사용해 코드 작성 및 정기적으로 배포를 통해 이를 해결 할 수 있을 것이라고 생각합니다.</p><h3>코드 적용</h3><h4>Terraform Plan</h4><pre>$ terraform plan</pre><pre>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create</pre><pre>Terraform will perform the following actions:</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test1-serviceaccount-roles/bigquery.resourceViewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigquery.resourceViewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test1-serviceaccount-roles/bigtable.viewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigtable.viewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test2-serviceaccount-roles/bigquery.resourceViewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigquery.resourceViewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test2-serviceaccount-roles/bigtable.viewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigtable.viewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test3-serviceaccount-roles/bigquery.resourceViewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigquery.resourceViewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test3-serviceaccount-roles/bigtable.viewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigtable.viewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_service_account.service_account[&quot;test1-serviceaccount&quot;] will be created<br>  + resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>      + account_id   = &quot;test1-serviceaccount&quot;<br>      + disabled     = false<br>      + display_name = &quot;Test Service Accounts&quot;<br>      + email        = (known after apply)<br>      + id           = (known after apply)<br>      + name         = (known after apply)<br>      + project      = (known after apply)<br>      + unique_id    = (known after apply)<br>    }</pre><pre># module.create_serviceaccounts.google_service_account.service_account[&quot;test2-serviceaccount&quot;] will be created<br>  + resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>      + account_id   = &quot;test2-serviceaccount&quot;<br>      + disabled     = false<br>      + display_name = &quot;Test Service Accounts&quot;<br>      + email        = (known after apply)<br>      + id           = (known after apply)<br>      + name         = (known after apply)<br>      + project      = (known after apply)<br>      + unique_id    = (known after apply)<br>    }</pre><pre># module.create_serviceaccounts.google_service_account.service_account[&quot;test3-serviceaccount&quot;] will be created<br>  + resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>      + account_id   = &quot;test3-serviceaccount&quot;<br>      + disabled     = false<br>      + display_name = &quot;Test Service Accounts&quot;<br>      + email        = (known after apply)<br>      + id           = (known after apply)<br>      + name         = (known after apply)<br>      + project      = (known after apply)<br>      + unique_id    = (known after apply)<br>    }</pre><pre>Plan: 9 to add, 0 to change, 0 to destroy.</pre><h4>Terraform apply</h4><pre>$ terraform apply</pre><pre>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create</pre><pre>Terraform will perform the following actions:</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test1-serviceaccount-roles/bigquery.resourceViewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigquery.resourceViewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test1-serviceaccount-roles/bigtable.viewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigtable.viewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test2-serviceaccount-roles/bigquery.resourceViewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigquery.resourceViewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test2-serviceaccount-roles/bigtable.viewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigtable.viewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test3-serviceaccount-roles/bigquery.resourceViewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigquery.resourceViewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_project_iam_member.role_binding[&quot;test3-serviceaccount-roles/bigtable.viewer&quot;] will be created<br>  + resource &quot;google_project_iam_member&quot; &quot;role_binding&quot; {<br>      + etag    = (known after apply)<br>      + id      = (known after apply)<br>      + member  = (known after apply)<br>      + project = (known after apply)<br>      + role    = &quot;roles/bigtable.viewer&quot;<br>    }</pre><pre># module.create_serviceaccounts.google_service_account.service_account[&quot;test1-serviceaccount&quot;] will be created<br>  + resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>      + account_id   = &quot;test1-serviceaccount&quot;<br>      + disabled     = false<br>      + display_name = &quot;Test Service Accounts&quot;<br>      + email        = (known after apply)<br>      + id           = (known after apply)<br>      + name         = (known after apply)<br>      + project      = (known after apply)<br>      + unique_id    = (known after apply)<br>    }</pre><pre># module.create_serviceaccounts.google_service_account.service_account[&quot;test2-serviceaccount&quot;] will be created<br>  + resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>      + account_id   = &quot;test2-serviceaccount&quot;<br>      + disabled     = false<br>      + display_name = &quot;Test Service Accounts&quot;<br>      + email        = (known after apply)<br>      + id           = (known after apply)<br>      + name         = (known after apply)<br>      + project      = (known after apply)<br>      + unique_id    = (known after apply)<br>    }</pre><pre># module.create_serviceaccounts.google_service_account.service_account[&quot;test3-serviceaccount&quot;] will be created<br>  + resource &quot;google_service_account&quot; &quot;service_account&quot; {<br>      + account_id   = &quot;test3-serviceaccount&quot;<br>      + disabled     = false<br>      + display_name = &quot;Test Service Accounts&quot;<br>      + email        = (known after apply)<br>      + id           = (known after apply)<br>      + name         = (known after apply)<br>      + project      = (known after apply)<br>      + unique_id    = (known after apply)<br>    }</pre><pre>Plan: 9 to add, 0 to change, 0 to destroy.</pre><pre>Do you want to perform these actions?<br>  Terraform will perform the actions described above.<br>  Only &#39;yes&#39; will be accepted to approve.</pre><pre>Enter a value: yes</pre><pre>--- 생략 ---</pre><pre>Apply complete! Resources: 9 added, 0 changed, 0 destroyed.</pre><h4><strong>Console 확인</strong></h4><p>문제없이 3개의 service account에 2개의 롤들이 각각 부여가 되어있는 것을 확인 할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JxJyNpCM_4A29zW5.png" /></figure><p>참조 코드</p><p><a href="https://github.com/terraform-google-modules/terraform-google-service-accounts">https://github.com/terraform-google-modules/terraform-google-service-accounts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f33228da7efb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/gcp-iam-by-terraform-f33228da7efb">GCP IAM by Terraform</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP VPC Peering]]></title>
            <link>https://medium.com/cloudvillains/gcp-vpc-peering-a56b6c7bd50e?source=rss-256a1395a4d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56b6c7bd50e</guid>
            <category><![CDATA[exchange-custom-routes]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[vpc-peering]]></category>
            <category><![CDATA[exchange-subnet-routes]]></category>
            <category><![CDATA[메가존클라우드]]></category>
            <dc:creator><![CDATA[김도영]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 09:16:21 GMT</pubDate>
            <atom:updated>2021-06-04T07:59:14.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>VPC Peering란?</h3><p>프라이빗 IPv4 주소 또는 IPv6 주소를 사용하여 두 VPC 간에 트래픽을 라우팅할 수 있도록 하기 위한 두 VPC 사이의 네트워킹 연결하는 기능이다.<br><a href="https://jinho.dev/posts/vpc/">https://jinho.dev/posts/vpc/</a></p><h3>GCP에서 VPC Peering를 사용하는 경우</h3><p>GCP에서는 크게 3가지로 나눌 수 있다.</p><ul><li>동일한 Project에서 각각 다른 VPC간의 내부 통신을 하고 싶은 경우<br>→ 다른 MSP와 동일</li><li>하나의 Project의 VPC와 또다른 Project의 VPC간 내부 통신을 하고 싶은 경우<br>→ Project와 Project 간은 서로 내부IP로 통신이 불가능하므로 Project간 내부 통신을 하고 싶은 경우 VPC Peering을 사용한다.</li></ul><blockquote><strong>Project란 무엇일까?</strong></blockquote><blockquote>Project를 한마디로 표현하면 <br>일종의「상위폴더」라고 말할 수 있다. <br>GCP에서는 여러개의 Project를 생성 할 수 있으며, <br>하나의 Project에 속한 Google Cloud Resource는 <br>다른 Project의 Google Cloud Resource와는 독립적이며, <br>Project간의 내부 통신은 불가능하다. <br>그렇기 때문에 GCP에서는 목적에 따라 Project를 나눠서 관리를 한다.</blockquote><ul><li>온프레미스와 Project간 Interconnect가 맺어져 있는 상태에서 온프레미스가 추가로 생성된 Project와 통신하고 싶은 경우 <br>→ 온프레미스와 Interconnect를 맺은 Project를 Hub Project로 두고<br> 추가로 생성된 Project(Spoke Project)와 온프레미스간의 통신을 위해<br> Hub Project와 Spoke Project간의 VPC Peering 설정이 필요하다.</li></ul><h3><strong>목표</strong></h3><p>이번 글에서는 「하나의 Project의 VPC와 또다른 Project의 VPC간 내부 통신을 하고 싶은 경우」에 대해서 알아 볼 것이며, 아래 그림에 (빨간 BOX로 표시해둔)해당하는 VPC Peering 생성 시 선택 가능한 「Exchange subnet routes with public IP」기능에 대해 언제 사용되는 옵션인지 살펴볼 것이다.</p><p>(「Exchange custom routes」는 「온프레미스와 Project간의 Interconnect맺어있는 상태에서 온프레미스가 추가로 생성된 Project와 통신하고 싶은 경우 」에 필요한 기능임으로 다음 글에서 다룰 예정이다)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*U5pL7dOmjUsOHGjHQBpISQ.png" /></figure><h3><strong>참고(RFC1918 사설IP 대역)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*XXCkuLzV5kdcOMhKke5zEw.png" /></figure><h3>WorkFlow</h3><ol><li><strong>두개의 프로젝트를 준비</strong></li><li><strong>Project A VPC생성</strong></li></ol><ul><li>「private-public-ip-vpc1」 라는 이름으로 VPC 생성.</li><li>이름은 「private-public-ip-subnet1」, 대역대는 「172.168.1.0/24」로 subnet 생성.</li><li>「private-ip-vpc1」 라는 이름으로 VPC 생성.</li><li>이름은 「private-ip-subnet1」, 대역대는 「172.16.0.0/16」로 subnet 생 성. </li></ul><p><strong>3.</strong> <strong>Project B VPC생성</strong></p><ul><li>「private-public-ip-vpc2」 라는 이름으로 VPC 생성.</li><li>이름은 「private-public-ip-subnet2」, 대역대는 「172.168.2.0/24」로 subnet 생성.</li><li>「private-ip-vpc2」 라는 이름으로 VPC 생성.</li><li>이름은 「private-ip-subnet2」, 대역대는 「172.26.0.0/16」로 subnet 생 성 </li></ul><p><strong>4. Peering 구성</strong></p><ul><li>「private-public-ip-vpc1」 ⇔ 「private-public-ip-vpc2」</li><li>「private-public-ip-vpc1」 ⇔ 「private-ip-vpc2」</li><li>「private-ip-vpc1」 ⇔ 「private-ip-vpc2」</li></ul><p>================================</p><h4>1. 두개의 프로젝트를 준비</h4><p>Project A : kdyoung-int-210504 Project</p><p>B : gcp-team-210510</p><h4>2. Project A VPC생성</h4><p>Project A에서 VPC생성 및 subnet 생성</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0Gvj7qRPxs1p3f_JNVDYQ.png" /></figure><h4>3. Project A VPC생성</h4><p>Project B에서 VPC생성 및 subnet 생성</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXcUPKSdvTRUPt_xvLPosA.png" /></figure><h4>4. Peering 구성</h4><p><strong>A.「private-public-ip-vpc1」 ⇔ 「private-public-ip-vpc2」</strong></p><h4>ACTIVE확인</h4><p>private로 사용은 되었지만 RFC1918의해 정해진 사설 IP대역이 아닌 IP를 사용한 경우이다.</p><p>해당 경우에는 아래와 같이 각 프로젝트의 VPC Peering에서는 ACTIVE가 된 것 까지는 확인이 된다</p><p><strong>private-public-ip-vpc1 → private-public-ip-vpc2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6_6mmE4zL6oXI4oS7ykDQ.png" /></figure><p><strong>private-public-ip-vpc2 → private-public-ip-vpc1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipJG4ZSsrba7Mjli3ZameQ.png" /></figure><h4>Route확인</h4><p>하지만 각 Imported Routes와 Exported Routes를 확인해보면</p><p>아무것도 없는 것을 확인 할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*sSYnvDjG2YbPg3AcF92Now.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*2qLDBaBfs83y6izmPA8Vbg.png" /><figcaption><strong>ProjectA</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*ZGFbP7uHyFtBI9E9ysyLFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*1JFPOQnvyKuSlVmzcTQfBg.png" /><figcaption><strong>ProjectB</strong></figcaption></figure><p><strong>B.「private-public-ip-vpc1」 ⇔ 「private-ip-vpc2」</strong></p><h4>ACTIVE확인</h4><p><strong>private-public-ip-vpc1→ private-ip-vpc2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0CEIU3fr6FTJ1bXy3HQ8w.png" /></figure><p><strong>private-ip-vpc2 → private-public-ip-vpc1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5KeS6FrEsBv2Bi7DctA2g.png" /></figure><h4>Route확인</h4><p>VPC Peering 라우팅 확인을 해보니</p><p>RFC1918에 의해 정해져 있는 사설 IP대역인</p><p><strong>ProjectB</strong>의 <strong>private-ip-vpc2</strong> 의 「<strong>172.26.0.0/16</strong>」대역만 광고 한 것이 확인 되었다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*Q3bVwyXrdXvL1z5PJZdqiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*vFF8pBD63Rl6rmicYBML7Q.png" /><figcaption><strong>ProjectA</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*EhWymEBs5_JbwzoGUVyy2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*5FXKNWRLSNyjFnczQt3ZHw.png" /><figcaption><strong>ProjectB</strong></figcaption></figure><p><strong>c.「private-ip-vpc1」 ⇔ 「private-ip-vpc2」</strong></p><h4>ACTIVE 확인</h4><p><strong>private-ip-vpc1 → private-ip-vpc2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2711HTdbbmss0R0Z4OO0HQ.png" /></figure><p>private-ip-vpc2 → private-ip-vpc1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RC6D7FNJe51WbELsmUEJKg.png" /></figure><h3>Route확인</h3><p>아래와 같이 RFC1918에 따라 사설IP대역을 사용 중인 subnet은</p><p>서로 경로 정보를 주고받은 것을 확인 할 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*x0xKtnN6KA7Hxw2frbtYkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*1KEargCX7w5ZkeXVyF4WQA.png" /><figcaption><strong>ProjectA</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*yCFqm_nhHT0pfYnW49ynXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*CacFsMI4kDi1y5RRJQEHcw.png" /><figcaption><strong>ProjectB</strong></figcaption></figure><h3>결론</h3><p><strong>subnet을 생성 시 RFC1918 사설대역이 아닌 IP대역대를 사용하게 되면</strong></p><p><strong>public IP로 인식을 하기 때문에 자동으로 경로 정보를 Export를 하지 않는다.</strong></p><p><strong>그런 경우 사용하는 옵션이 「Exchange subnet routes with public IP」이다.</strong></p><p>즉, private IP로 사용하지만 public IP대역대를 사용함에 있어 public IP로 인식되며<strong>「Exchange subnet routes with public IP」옵션을 사용하지 않으면 경로정보를 Export하지 않는다.</strong></p><h4>B. 「<strong>private-public-ip-vpc1</strong>」 ⇔ 「<strong>private-ip-vpc2</strong>」</h4><p>위의 경우로 예를 들어 보면,</p><p>해당 경우는 「<strong>private-public-ip-vpc1</strong>」의 subnet「172.168.1.0/24」이 public IP로 인식이 됨으로 경로 정보를 광고하지 않는다. 즉, 경로 정보를 Export하지 않았음으로 「<strong>private-ip-vpc2</strong>」 의 <strong>Imported Routes</strong>에서는 emtpy로 표시가 되는 것까지 위에서 확인을 했었다.</p><p>이런 경우</p><p>「<strong>private-public-ip-vpc1</strong>」 쪽의 vpc peering에서 「Export subnet routes with public IP」선택</p><p>「<strong>private-ip-vpc2</strong>」 쪽의 vpc peering에서는 「Import subnet routes with public IP」선택</p><p>을하면 「172.168.1.0/24」에 대한 경로 정보 Export하게 되며, 통신이 가능한 상태가 된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ur9Af1FxmTVZTHP-pSTTig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ET1p_u0HsdZF6JJsT2Z2dA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56b6c7bd50e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloudvillains/gcp-vpc-peering-a56b6c7bd50e">GCP VPC Peering</a> was originally published in <a href="https://medium.com/cloudvillains">Cloud Villains</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>