<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ansible &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/category/tech/ansible/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>AI 자동화를 직접 굴려 본 개발자의 실무 교훈</description>
	<lastBuildDate>Fri, 21 Aug 2026 15:45:06 +0000</lastBuildDate>
	<language>ko-KR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.2</generator>

<image>
	<url>https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/08/wz-siteicon-512.png?fit=32%2C32&#038;ssl=1</url>
	<title>ansible &#8211; WONIZZ.LOG</title>
	<link>https://blog.wonizz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">152411368</site>	<item>
		<title>[DevOps] ansible nginx config 배포 구성</title>
		<link>https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/</link>
					<comments>https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 11 Jul 2022 07:59:14 +0000</pubDate>
				<category><![CDATA[ansible]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1936</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 ansible을 이용한 nginx config 파일의 배포에 대해서 정리해보도록 하겠습니다. 필자가 속한 프로젝트에서는 nginx를 Front-end의 export된 html 소스를 서빙하기 위한 용도로 사용하고 있습니다. nginx config의 설정 변경을 수행하고 배포시에는 별도의 사내 시스템을 사용하고 있었지만, 이는 scp를 통해서 직접 파일을 카피하고 전송하는 부분이였습니다. 이러한 부분을 좀더 수월하게 개선하기 위해서 필자는 ansible을 통하여&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 <code>ansible</code>을 이용한 <code>nginx config</code> 파일의 배포에 대해서 정리해보도록 하겠습니다. 필자가 속한 프로젝트에서는 nginx를 Front-end의 export된 html 소스를 서빙하기 위한 용도로 사용하고 있습니다. nginx config의 설정 변경을 수행하고 배포시에는 <code>별도의 사내 시스템</code>을 사용하고 있었지만, 이는 scp를 통해서 직접 파일을 카피하고 전송하는 부분이였습니다.</p>
<p>이러한 부분을 좀더 수월하게 개선하기 위해서 필자는 <code>ansible</code>을 통하여 파일을 배포하고 배포된 파일이 정상인지 검증(validation)을 수행하고, 이후에 기동한 뒤 프로세스체크까지 하는 파이프라인구조로 변경을 하기로 했습니다.</p>
<p>Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/17/devops-nginx-geoip-module/">[DevOps] Nginx GeoIP 모듈 적용</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/10/19/devops-nginx-log-aggregation-dashboard/">[DevOps] Nginx Log Aggregation &#038; Dashboard</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a>
  </li>
</ul>
<h2>1. nginx deploy with ansible</h2>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2022/07/ansible_deploy_1.png?w=1200" alt="ansible_deploy_1" /></p>
<p>nginx의 config 파일 관리는 github에서 우선적으로 합니다. ansible은 별도 ansible server에서 설치하여 사용하며 ansible을 위한 별도의 git repository도 존재합니다. 흐름은 다음 플로우를 통해서 진행이 되며, ansible을 통해서 nginx config 파일을 배포하고 nginx를 기동합니다.</p>
<ul>
<li>ansible에서 target되는 nginx config파일을 다운로드 받습니다.</li>
<li>nginx.conf 파일을 nginx의 binary를 통해서 검증(-t)를 수행합니다.</li>
<li>Nginx.conf 파일을 기반으로 restart를 수행합니다. (nginx config 파일을 갖고 기동합니다.)</li>
<li>Nginx의 프로세스(systemctl status)를 통해서 정상 기동되었는지 체크를 합니다.</li>
<li>위의 과정을 serial하게 1대씩 진행을 합니다.</li>
</ul>
<p>위와 같은 과정을 거쳐서 타겟팅 되는 nginx를 1대씩 배포를 수행하고(Rolling Update) 배포 완료시 알람을 발송합니다.</p>
<h2>2. ansible folder 구조</h2>
<p>Ansible의 git repository 구성에 대해서 정리를 해보도록 하겠습니다.</p>
<pre><code class="language-bash line-numbers">├── group_vars
│    └── test-web-nginx-prod.yml
├── nginx_deploy.yml
├── test-web-nginx-prod
└── roles
    ├── common
    │   ├── meta
    │   │   └── main.yml
    │   └── tasks
    │       └── main.yml
    └── nginx
        ├── meta
        │    └── main.yml
        ├── tasks
        │     └── main.yml
        └── templates
            └── index.html.j2
</code></pre>
<ul>
<li>ansible inventory 작성은 배포그룹(ex. test-web-nginx-prod) 에 작성</li>
</ul>
<h3>inventory / test-web-nginx-prod</h3>
<pre><code class="language-bash line-numbers">[test-web-nginx-prod]
test1501
test1502
test1503

[webservers:children]
test-web-nginx-prod
</code></pre>
<h3>inventory / group_vars / test-web-nginx-prod.yml</h3>
<pre><code class="language-yaml line-numbers">phase: "prod"
application: "test-web-nginx"
index: true
maintenence: true
members: false
vosdomain: "test-objects.com"
vosbucket: "test-nft"
</code></pre>
<p>inventory에는 서버에 대한 정보 설정을 기입합니다. 그리고 관련하여 참조할 변수들을 <strong>group_vars</strong> 하위에 기입을 합니다.</p>
<h2>3. ssh 접속을 위한 사전설정</h2>
<p>ansible 서버에서 target 서버로 접속을 하기 위해서는 ssh 설정이 필요합니다. 별도의 비밀번호 없이 public key와 private key를 통해서 접근을 하기 위한 설정입니다.</p>
<h3>키생성</h3>
<pre><code class="language-bash line-numbers">$ ssh-keygen -t rsa
</code></pre>
<ol>
<li>키를 저장할 경로( 기본값 : $HOME/.ssh/id_rsa)</li>
<li>passphrase (추가로 사용할 암호, 기본값 없음)</li>
<li>passphrase 확인</li>
</ol>
<h3>ssh key 등록하기</h3>
<p>.pub이 공개키 인데 해당 공개키를 서버에 등록하면 다음부턴 비밀번호를 입력할 필요가 없어집니다.</p>
<pre><code class="line-numbers">$ mkdir ~/.ssh
$ touch ~/.ssh/authorized_keys
$ chmod 755 ~/.ssh/authorized_keys
</code></pre>
<p>Host의 ~/.ssh/id_rsa.pub 에 있는 모든 내용을 복사해서, <strong>접속한 서버의 .ssh 폴더 내에 있는 authorized_keys 파일을 수정해 해당 내용을 모두 붙여 넣고 저장합니다.</strong></p>
<p>이렇게 되면, ansible서버에서 target 서버로 접속이 비밀번호 없이 바로 할 수 있습니다.</p>
<h2>4. jenkins 연계</h2>
<p>Jenkins를 통해서 ansible playbook 명령어를 호출하여 target 서버에 nginx config를 배포하고 restart를 해주는 내용을 연계하려고 합니다.</p>
<p>jenkins의 파라미터로는 2가지로 선정을 했습니다. nginx가 FE의 서빙 역할을 하기 때문에 application 별로 있습니다.</p>
<p>따라서 application이라는 파라미터를 설정했고, 각 phase(alpha, beta, real) 순서로 파라미터를 설정했습니다.</p>
<ul>
<li>applicatoin</li>
<li>phase</li>
</ul>
<p>설정한 값에 맞춰서 ansible playbook 실행시, nginx-config 와 target 서버 목록을 셋팅합니다.</p>
<h3>ansible 명령어</h3>
<pre><code class="language-bash line-numbers">$ ansible-playbook -i ${WORKSPACE}/devops-nginx-deploy/inventory/${APPLICATION}-${PHASE} ${WORKSPACE}/devops-nginx-deploy/playbook/nginx_deploy.yml -u irteamsu
</code></pre>
<h3>ansible roles</h3>
<pre><code class="language-yaml line-numbers"># roles/nginx/tasks/main.yml

---
# tasks file for nginx
#- name: install nginx
#  yum: name=nginx state=installed

- name: git clone
  git:
    repo: https://test:xxxxx@github.com/dongwonlee/test-web-nginx.git
    dest: /home1/test/apps/test-web-nginx/
    update: yes
    version: master

- name: copy nginx.config
  copy:
    src: /home1/test/apps/test-web-nginx/config/{{ application }}/nginx-{{ phase }}.conf
    dest: /etc/nginx/nginx.conf
    remote_src: yes

- name: Verify Nginx config
  command: nginx -t
  changed_when: false

- name: Download Index html
  get_url:
    url: https://{{ vosdomain }}/{{ vosbucket }}-{{ phase }}/index.html
    dest: /etc/nginx/index.html
    force: true
  when: index | bool

- name: Reload nginx config
  service: name=nginx state=reloaded enabled=yes

- name: check nginx status
  command: systemctl status nginx
  register: process
  failed_when: "'running' not in process.stdout"

</code></pre>
<p>ansible yaml 파일을 보면, 기존의 수동으로 하던 작업들을 일련의 작업으로 순서화를 시킨내용입니다.</p>
<ul>
<li>git clone</li>
<li>verify nginx</li>
<li>download resource ( index.html )</li>
<li>reload nginx cofig</li>
<li>check nginx status</li>
</ul>
<h2>5. 테스트</h2>
<p>기본적으로 ansible은 병렬 수행을 하는데, serial 수행으로 옵션을 줄 수 있습니다.</p>
<h3>Playbook / nginx_deploy.yml</h3>
<pre><code class="language-yaml line-numbers">---
- hosts: webservers
  become: yes
  serial: 1
  roles:
    - nginx
</code></pre>
<p>위와 같이 <strong>serial: 1</strong>을 주게 되면, 1대씩 실행을 합니다. 아래 결과에서 보듯이 2대의 서버를 1대씩 진행하고 결과를 출력해주고 있습니다.</p>
<pre><code class="line-numbers">PLAY [webservers] **************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test-web-nginx001-dev]

TASK [nginx : git clone] *******************************************************
ok: [test-web-nginx001-jp2v-dev]

TASK [copy nginx.config] *******************************************************
ok: [test-web-nginx001-dev]

TASK [nginx : Verify Nginx config] *********************************************
ok: [test-web-nginx001-dev]

TASK [nginx : Download Index html] *********************************************
changed: [test-web-nginx001-dev]

TASK [Reload nginx config] *****************************************************
changed: [test-web-nginx001-dev]

TASK [check nginx status] ******************************************************
changed: [test-web-nginx001-dev]

PLAY [webservers] **************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test-web-nginx002-dev]

TASK [nginx : git clone] *******************************************************
ok: [test-web-nginx002-dev]

TASK [copy nginx.config] *******************************************************
ok: [test-web-nginx002-dev]

TASK [nginx : Verify Nginx config] *********************************************
ok: [test-web-nginx002-dev]

TASK [nginx : Download Index html] *********************************************
changed: [test-web-nginx002-dev]

TASK [Reload nginx config] *****************************************************
changed: [test-web-nginx002-dev]

TASK [check nginx status] ******************************************************
changed: [test-web-nginx002-dev]

PLAY RECAP *********************************************************************
test-web-nginx001-dev : ok=8    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
test-web-nginx002-dev : ok=8    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
</code></pre>
<h2>6. 마치며</h2>
<p>ansible은 여러대의 config 설정과 같이 다양한 환경에서 반복적이고 여러대의 작업에서 수행되는 작업을 할 때 굉장히 유용한것 같습니다. 본 포스팅은 사내의 시스템이 있었는데 설정도 배포도 상당히 어려움이 있어서 ansible을 통해서 간단하게 jenkins 연계를 통하여 nginx 설정 배포를 할 수 있도록 구성했습니다.</p>
<p>다음 시간에는 ansible을 실행하고 job들을 관리할 수 있는 ansible tower(AWX)에 대해서 정리해보고 적용해보는 시간을 갖도록 하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1936</post-id>	</item>
		<item>
		<title>[kubernetes] kubespray를 통한 클러스터 구축</title>
		<link>https://blog.wonizz.com/2021/05/17/kubernetes-kubespray/</link>
					<comments>https://blog.wonizz.com/2021/05/17/kubernetes-kubespray/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 17 May 2021 08:26:46 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[ansible]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1778</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 쿠버네티스 클러스터 구축을해주는 툴인 kubespray에 대해서 알아보는 시간을 갖도록 하겠습니다. 이전 포스팅을 보면, 직접 마스터 노드/워커 노드에 접속을 해서 수동 설치를 진행하고 마지막에는 join을 해주는 개념으로 클러스터를 구축했었습니다. 하지만, kubespray를 통해서 한번에 진행하는 방식을 도입하고 그부분에 대해서 정리를 진행하고자 합니다. 필자는 초기 클러스터를 구축할 당시에 kubeadm 을 통해서 클러스터를 구축해보았습니다.&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/05/17/kubernetes-kubespray/">[kubernetes] kubespray를 통한 클러스터 구축</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 쿠버네티스 클러스터 구축을해주는 툴인 kubespray에 대해서 알아보는 시간을 갖도록 하겠습니다. 이전 포스팅을 보면, 직접 마스터 노드/워커 노드에 접속을 해서 수동 설치를 진행하고 마지막에는 join을 해주는 개념으로 클러스터를 구축했었습니다. 하지만, kubespray를 통해서 한번에 진행하는 방식을 도입하고 그부분에 대해서 정리를 진행하고자 합니다.

필자는 초기 클러스터를 구축할 당시에 <code>kubeadm</code> 을 통해서 클러스터를 구축해보았습니다.  kubeadm을 통해서 구축하는 내용은 쿠버네티스 공식 블로그에 순서대로 잘 정리가 되어있습니다.

<a class="wp-editor-md-post-content-link" href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/" title="kubeadm을 사용하여 클러스터 만들기" target="_blank" rel="noopener">kubeadm을 사용하여 클러스터 만들기</a>

쿠버네티스를 구성하는 내용은 공식 블로그에는 3가지를 통해서 정리가 되어있습니다.

<ol>
<li>kubeadm을 통한 클러스터 구축</li>
<li>kops를 통한 클러스터 구축</li>
<li>kubespray를 통한 클러스터 구축</li>
</ol>

위의 내용중에서 이번 포스팅은 kubespray를 통한 클러스터 구축에 대해서 정리를 하고자 합니다.

<h2>1. kubespray란 무엇인가요?</h2>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2021/05/kubespray_1.png?w=1200&#038;ssl=1" />

<code>kubespray</code> 는 쿠버네티스를 쉽게 설치하는 자동화 도구 입니다. github을 클론받게 되면, ansible yaml파일들이 정리가 되어있습니다. Ansible의 playbook과 inventory설정을 통해서 kubernetes 클러스터를 설정하게 됩니다.

kubespray는 Ansible Playbook, Inventory, Provisioning Tool과 일반적인 운영체제, 쿠버네티스 클러스터의 설정 관리 작업에 대한 도메인 지식의 결합으로 만들어졌습니다. 
kubespray는 다음과 같은 기능을 제공합니다.

<ul>
<li>고가용성을 지닌 클러스터의 생성</li>
<li>대부분의 리눅스 배포판 지원</li>
<li>지속적인 통합(CI) 테스트</li>
</ul>

<h2>2. Kubespray 사전 작업</h2>

kubespray를 활용하여 클러스터 구축을 하기 위해서는 다음과 같은 환경이 구성되어있어야 합니다.

<h3>2-1. 서버 구성</h3>

<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />kubespray 서버 : kubespray를 실행할 서버</li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />kubernetes master 서버 : kubernetes 마스터 서버</li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />kubernetes worker 서버 : kuberentes 워커 서버</li>
</ul>

<h3>2-2. 사전 준비</h3>

kubespray서버에 접속한 뒤, 다음을 설치 합니다. 
kubespray를 사용하기 위해서는 다음의 요구사항이 필요합니다.

<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />Jinja 2.9 이상 필요</li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />서버가 인터넷에 액세스 가능</li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />서보 상호간의 ssh 키 복사</li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />방화벽 비활성화</p></li>
<li>Python3 설치(kubespray 서버)</p></li>
</ul>

<pre><code class="language-bash line-numbers">$ yum install python3
</code></pre>

<ul>
<li>Ansible, netaddr, jinja2 설치(kubespray 서버)</li>
</ul>

<pre><code class="language-bash line-numbers">$ python3 -m pip install -u pip
$ pip3.6 uninstall ansible ansible-base
$ pip3.6 install ansible==2.9.14 netaddr jinja2
</code></pre>

<ul>
<li>ssh key 생성(kubespray 서버)</li>
</ul>

<pre><code class="language-bash line-numbers">$ ssh-keygen -t rsa
$ cat ~/.ssh/id_rsa.pub // 해당 내용의 키값을 복사해둡니다.
</code></pre>

<ul>
<li>ssh key 복사(master, worker 서버)</li>
</ul>

<pre><code class="language-bash line-numbers">$ vi ~/.ssh/authorized_keys2 // 위의 복사된 키값을 append로 붙여넣습니다.
</code></pre>

<h3>2-3. master, worker 서버 기본 셋팅</h3>

kubernetes master 서버를 포함한 worker 서버에서 아래의 명령어를 동일하게 수행합니다. 주요 내용은 패킷 포워딩이 가능하도록 설정하고, 방화벽 및 selinux를 해제하며, 메모리 swapping을 비활성화 하는 것입니다.

<ul>
<li>ip_forward 활성화</li>
</ul>

<pre><code class="language-bash line-numbers">$ echo 1 > /proc/sys/net/ipv4/ip_forward
</code></pre>

<ul>
<li>firewalld 비활성화</li>
</ul>

<pre><code class="language-bash line-numbers">$ systemctl stop firewalld & systemctl disable firewalld
</code></pre>

<ul>
<li>selinux 해제</li>
</ul>

<pre><code class="language-bash line-numbers">$ sed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/sysconfig/selinux && cat /etc/sysconfig/selinux
$ setenforce 0
</code></pre>

<ul>
<li>swap memory 중지</li>
</ul>

<pre><code class="language-bash line-numbers">$ swapoff -a 
</code></pre>

<h2>3. kubespray 실행</h2>

kubespray를 사용하기 위해서는 공식 깃헙의 내용을 클론하여 내용 변경 후 사용합니다. 아래의 내용은 kubespray 서버에서 진행합니다.

<ul>
<li>git clone을 통해 소스를 가져옵니다.</li>
</ul>

<pre><code class="language-bash line-numbers">$ git clone https://github.com/kubernetes-sigs/kubespray.git
</code></pre>

<ul>
<li>requirements.txt 파일을 통해 종속파일들을 설치합니다.</li>
</ul>

<pre><code class="language-bash line-numbers">$ sudo pip3 install -r requirements.txt
</code></pre>

<ul>
<li>sample 파일을 <code>custom cluster</code> 폴더에 복사합니다 .</li>
</ul>

<pre><code class="language-bash line-numbers">$ cp -rfp inventory/sample inventory/{custom cluster}
</code></pre>

<ul>
<li>Inventory.ini 파일을 수정합니다.</li>
</ul>

<pre><code class="language-bash line-numbers">$ vi inventory/{custom cluster}/inventory.ini

# inventory/mycluster/inventory.ini 
[all]
master ansible_host=192.168.122.10 ip=192.168.122.10 etcd_member_name=etcd1
node1 ansible_host=192.168.122.21  ip=192.168.122.21
node2 ansible_host=192.168.122.22  ip=192.168.122.22
node3 ansible_host=192.168.122.23  ip=192.168.122.23
# node4 ansible_host=95.54.0.15  # ip=10.3.0.4 etcd_member_name=etcd4
# node5 ansible_host=95.54.0.16  # ip=10.3.0.5 etcd_member_name=etcd5
# node6 ansible_host=95.54.0.17  # ip=10.3.0.6 etcd_member_name=etcd6

# ## configure a bastion host if your nodes are not directly reachable
# bastion ansible_host=x.x.x.x ansible_user=some_user

[kube-master]
master

[etcd]
master

[kube-node]
node1
node2
node3

[calico-rr]

[k8s-cluster:children]
kube-master
kube-node
calico-rr
</code></pre>

<ul>
<li>Ping 모듈을 통해서 노드간 통신이 이루어지는지 확인합니다.</li>
</ul>

<pre><code class="language-bash line-numbers">$ ansible kube-node -i ./{custom cluster}/inventory.ini -m ping -u irteamsu -vvv
</code></pre>

<ul>
<li>cluster.yaml 파일을 통해서 배포</li>
</ul>

<pre><code class="language-bash line-numbers">$ ansible-playbook --flush-cache -u irteamsu -b -i inventory/{custom cluster}/inventory.ini cluster.yml -vvv
</code></pre>

<h2>4. 클러스터 생성 확인</h2>

kubespray 서버를 통해서 스프레이를 뿌려주게 되면(?) master, worker간에 클러스터 구축이 완료되고, 마스터 서버를 통해서 클러스터가 정상적으로 생성이 되었는지 확인할 수 있습니다.

<pre><code class="language-bash line-numbers">kube[root@dev-k8s-master001-kubespray-dev:~]# kubectl get nodes
NAME                               STATUS   ROLES    AGE     VERSION
dev-k8s-master001-kubespray-dev   Ready    master   2d17h   v1.18.8
dev-k8s-worker001-kubespray-dev   Ready    <none>   2d17h   v1.18.8
dev-k8s-worker002-kubespray-dev   Ready    <none>   2d17h   v1.18.8
dev-k8s-worker003-kubespray-dev   Ready    <none>   2d17h   v1.18.8
</code></pre>

<h2> </h2>

<h2>5. 마치며&#8230;</h2>

클러스터 생성을 도와주는 툴인 kubespray를 사용하는 방법에 대해서 정리를 해보았습니다. 정확하게 말하면 ansible 을 통한 클러스터 구축이라고 해도 상관이 없을 듯 합니다. ansible yaml 파일들이 각각 작성이 되어있고, 아마 내부적으로는 kubeadm을 설치하고 각 worker로 접속해서 join하는 작업이 명시되어 있지 않을까 하는 생각이 듭니다. 다음시간에는 kubespray의 yaml 파일들을 분석해보는 포스팅을 작성해 보도록 하겠습니다.

<h2>6. 참고자료</h2>

<a class="wp-editor-md-post-content-link" href="https://github.com/kubernetes-sigs/kubespray" target="_blank" rel="noopener">kubespray GitHub</a>
<a class="wp-editor-md-post-content-link" href="https://memory-hub.tistory.com/8" target="_blank" rel="noopener">kubespray로 Kubernetes 설치하기</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/09/01/kubeadm-pod-cidr-change/">[DevOps] kubeadm upgrade를 통한 pod cidr 변경</a></li><li><a href="https://blog.wonizz.com/2019/11/27/kubernetes-cluster-terraform/">[Kubernetes] 테라폼을 통한 Cluster 구성 자동화</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li><li><a href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/05/17/kubernetes-kubespray/">[kubernetes] kubespray를 통한 클러스터 구축</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2021/05/17/kubernetes-kubespray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1778</post-id>	</item>
	</channel>
</rss>
