Ansible Playbook 실습 - Ansible AWX - K3s 설치 자동화 - 구현 1 > Ansible 자료실

본문 바로가기
사이트 내 전체검색

Ansible 자료실

실습 Ansible Playbook 실습 - Ansible AWX - K3s 설치 자동화 - 구현 1

페이지 정보

profile_image
작성자 꿈꾸는여행자
댓글 0건 조회 3,196회 작성일 25-02-18 18:01

본문

안녕하세요.

 

꿈꾸는여행자입니다.

 

 

Ansible을 통한 Playbook을 활용에 대해서 Ansible AWX 구성 자동화 방안을 생각해 보았습니다.

 

해당 항목들을 설계 및 구현 해보는 과정을 진행하고자 합니다. 

 

이번 항목에서는 다음 내용을 기준으로 

구현 해 보겠습니다. 

 

 

1. K3s 오프라인 설치를 위한 Ansible 기반 자동화

    - 제어 노드 설정

    - K3s 오프라인 패키지 다운로드 

 

 

감사합니다. 

 

> 아래 

 

## ** Ansible을 활용한 K3s 오프라인 설치 및 정리 자동화**

### ** 1. 실행된 주요 작업**

1. **제어 노드 설정 (`setup_control_node`)**

   - 필수 패키지 설치 (`net-tools`, `curl`, `sshpass`, `tar`, `unzip`)

   - SSH 키 생성 및 표시


2. **K3s 오프라인 패키지 다운로드 (`prepare_k3s_offline`)**

   - K3s 바이너리 및 설치 스크립트 다운로드

   - K3s Air-Gap 이미지 다운로드

   - Helm 바이너리 다운로드

   - 다운로드한 파일을 압축(`tar.gz`)하여 저장


3. **K3s 오프라인 패키지 정리 (`clearup`)**

   - 다운로드된 K3s 오프라인 패키지 파일 및 디렉터리 삭제


---


### ** 2. 실행된 Ansible Playbook 및 역할**

#### ** `prepare.yml` (환경 설정 및 다운로드)**

```yaml

- name: Prepare environment and download offline packages

  hosts: localhost

  become: yes

  vars_files:

    - group_vars/all.yml

  roles:

    - setup_control_node

    - prepare_k3s_offline

```

> **설치 전 사전 준비 및 패키지 다운로드**


#### ** `clearup.yml` (다운로드된 파일 삭제)**

```yaml

- name: Cleanup K3s offline package from localhost

  hosts: localhost

  become: yes

  vars_files:

    - group_vars/all.yml

  roles:

    - clearup

```

> **설치 후 불필요한 파일을 삭제**


---


### ** 3. 실행된 Role 파일**

#### ** `roles/setup_control_node/tasks/main.yml`**

```yaml

---

# tasks file for roles/setup_control_node


- name: Update all packages

  dnf:

    name: "*"

    state: latest


- name: Install required packages for Ansible Control Node

  dnf:

    name:

      - net-tools

      - curl

      - sshpass

      - tar

      - unzip

    state: present


- name: Ensure SSH key exists for passwordless login

  user:

    name: "{{ ansible_user }}"

    generate_ssh_key: yes

    ssh_key_bits: 2048

    ssh_key_file: "{{ ansible_env.HOME }}/.ssh/id_rsa"


- name: Display SSH public key

  command: cat "{{ ansible_env.HOME }}/.ssh/id_rsa.pub"

  register: ssh_pub_key


- debug:

    msg: "Add the following SSH public key to your managed nodes:\n{{ ssh_pub_key.stdout }}"

```

> **제어 노드에서 필수 패키지를 설치하고 SSH 키를 생성하여 원격 노드와 통신 가능하도록 설정**


#### ** `roles/prepare_k3s_offline/tasks/main.yml`**

```yaml

---

# tasks file for roles/prepare_k3s_offline


- name: Create local directory for K3s package

  ansible.builtin.file:

    path: "{{ offline_package_dir }}"

    state: directory

    mode: '0755'


- name: Download K3s binary

  get_url:

    url: "{{ k3s_url }}"

    dest: "{{ offline_package_dir }}/k3s"

    mode: '0755'


- name: Download K3s install script

  get_url:

    url: "{{ k3s_install_script_url }}"

    dest: "{{ offline_package_dir }}/install.sh"

    mode: '0755'


- name: Download K3s Air-Gap Image Archive

  get_url:

    url: "{{ k3s_airgap_image_url }}"

    dest: "{{ offline_package_dir }}/k3s-airgap-images-amd64.tar.zst"


- name: Download Helm binary

  get_url:

    url: "{{ helm_url }}"

    dest: "{{ offline_package_dir }}/helm.tar.gz"


- name: Compress offline package

  archive:

    path: "{{ offline_package_dir }}/"

    dest: "{{ offline_package_archive }}"

    format: gz

```

> **K3s 및 Helm 관련 바이너리를 다운로드하고 압축하여 패키지를 생성**


#### ** `roles/clearup/tasks/main.yml`**

```yaml

---

# tasks file for roles/clearup


- name: Remove extracted K3s offline package directory

  ansible.builtin.file:

    path: "{{ offline_package_dir }}"

    state: absent


- name: Remove compressed K3s offline package tarball

  ansible.builtin.file:

    path: "{{ offline_package_archive }}"

    state: absent

```

> **K3s 오프라인 패키지를 다운로드한 후 필요 없는 파일을 삭제**


---


### ** 4. 실행 결과**

#### ** 준비 단계 실행 (`prepare.yml`)**

```bash

ansible-playbook -i inventory.ini prepare.yml --ask-become-pass

```

**출력 결과**

 `setup_control_node`에서 필수 패키지 설치 및 SSH 키 설정 완료  

 `prepare_k3s_offline`에서 K3s 오프라인 패키지 다운로드 및 압축 완료


#### ** 정리 단계 실행 (`clearup.yml`)**

```bash

ansible-playbook -i inventory.ini clearup.yml --ask-become-pass

```

**출력 결과**

 `clearup`에서 K3s 오프라인 패키지 삭제 완료


---


### ** 5. 프로젝트 디렉토리 구조**

```bash

.

├── clearup.yml              # 정리 Playbook

├── group_vars/

│   └── all.yml              # 변수 정의 파일

├── install-k3s.yml          # K3s 설치 Playbook (미포함, 필요 시 추가)

├── inventory.ini            # 인벤토리 파일

├── playbook.yml             # 전체 실행 Playbook

├── prepare.yml              # 준비 Playbook

├── roles/

│   ├── clearup/             # 다운로드된 파일 삭제 역할

│   │   ├── tasks/

│   │   │   ├── main.yml

│   ├── prepare_k3s_offline/  # K3s 오프라인 패키지 다운로드 역할

│   │   ├── tasks/

│   │   │   ├── main.yml

│   ├── setup_control_node/   # 제어 노드 설정 역할

│   │   ├── tasks/

│   │   │   ├── main.yml

```


---


### ** 6. 요약**

| 실행 단계 | 역할 | 주요 작업 |

|-----------|------|---------|

| **준비 단계 (`prepare.yml`)** | `setup_control_node` | 제어 노드 필수 패키지 설치, SSH 키 설정 |

| | `prepare_k3s_offline` | K3s 및 Helm 오프라인 패키지 다운로드 및 압축 |

| **정리 단계 (`clearup.yml`)** | `clearup` | 다운로드된 K3s 오프라인 패키지 삭제 |


---


## 작업 실행 내역 


---

 

```

[lds@ansible-host with-ansible]$ 

[lds@ansible-host with-ansible]$ cat /home/lds/Documents/with-ansible/roles/setup_control_node/tasks/main.yml

---

# tasks file for roles/setup_control_node


- name: Update all packages

  dnf:

    name: "*"

    state: latest


- name: Install required packages for Ansible Control Node

  dnf:

    name:

      - net-tools

      - curl

      - sshpass

      - tar

      - unzip

    state: present


- name: Ensure SSH key exists for passwordless login

  user:

    name: "{{ ansible_user }}"

    generate_ssh_key: yes

    ssh_key_bits: 2048

    ssh_key_file: "{{ ansible_env.HOME }}/.ssh/id_rsa"


- name: Display SSH public key

  command: cat "{{ ansible_env.HOME }}/.ssh/id_rsa.pub"

  register: ssh_pub_key


- debug:

    msg: "Add the following SSH public key to your managed nodes:\n{{ ssh_pub_key.stdout }}"


[lds@ansible-host with-ansible]$ cat /home/lds/Documents/with-ansible/roles/prepare_k3s_offline/tasks/main.yml 

---

# tasks file for roles/prepare_k3s_offline


- name: Create local directory for K3s package

  ansible.builtin.file:

    path: "{{ offline_package_dir }}"

    state: directory

    mode: '0755'


- name: Download K3s binary

  get_url:

    url: "{{ k3s_url }}"

    dest: "{{ offline_package_dir }}/k3s"

    mode: '0755'


- name: Download K3s install script

  get_url:

    url: "{{ k3s_install_script_url }}"

    dest: "{{ offline_package_dir }}/install.sh"

    mode: '0755'


- name: Download K3s Air-Gap Image Archive

  get_url:

    url: "{{ k3s_airgap_image_url }}"

    dest: "{{ offline_package_dir }}/k3s-airgap-images-amd64.tar.zst"


- name: Download Helm binary

  get_url:

    url: "{{ helm_url }}"

    dest: "{{ offline_package_dir }}/helm.tar.gz"


- name: Compress offline package

  archive:

    path: "{{ offline_package_dir }}/"

    dest: "{{ offline_package_archive }}"

    format: gz


[lds@ansible-host with-ansible]$ 

[lds@ansible-host with-ansible]$ cat prepare.yml 

- name: Prepare environment and download offline packages

  hosts: localhost

  become: yes

  vars_files:

    - group_vars/all.yml

  roles:

    - setup_control_node

    - prepare_k3s_offline


[lds@ansible-host with-ansible]$


lds@ansible-host with-ansible]$ ansible-playbook -i inventory.ini prepare.yml --ask-become-pass

BECOME password: 


PLAY [Prepare environment and download offline packages] **************************************************************************************************************************************************************************


TASK [Gathering Facts] ************************************************************************************************************************************************************************************************************

ok: [localhost]


TASK [setup_control_node : Update all packages] ***********************************************************************************************************************************************************************************

ok: [localhost]


TASK [setup_control_node : Install required packages for Ansible Control Node] ****************************************************************************************************************************************************

ok: [localhost]


TASK [setup_control_node : Ensure SSH key exists for passwordless login] **********************************************************************************************************************************************************

changed: [localhost]


TASK [setup_control_node : Display SSH public key] ********************************************************************************************************************************************************************************

changed: [localhost]


TASK [setup_control_node : debug] *************************************************************************************************************************************************************************************************

ok: [localhost] => {

    "msg": "Add the following SSH public key to your managed nodes:\nssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/+GpScW2NCmHaPCLsiW+e9U5q/rMM88lBvA9z7z3TZiYNKebT2P1kyRthSRX/RBmxfAjsXLkkRComt06sRPgj5QPuJZ2iGao1FpbWSGI5UhX+TYAyS4XjrT7ewrRC/FXMt1iBEwl+fPs6w4dLcduAniAXiDR6O08Jxg5wuSAjAVQxuK/qN2521QKdakglCziJMGf5L8G9WKGxnuZTzfWyDhbptGaYwr7C2jxcL07vwTMU3YoQ1t+G2T1TlUwecwelHL4SceSpiKiqktzJZB4NXsdRiFZMniD1sKHPNeUg0lKCh8ZXmQDQA0XnEwCYJSQCL2MEkhgp1Zi01v5XnCHz ansible-generated on ansible-host"

}


TASK [prepare_k3s_offline : Create local directory for K3s package] ***************************************************************************************************************************************************************

changed: [localhost]


TASK [prepare_k3s_offline : Download K3s binary] **********************************************************************************************************************************************************************************

changed: [localhost]


TASK [prepare_k3s_offline : Download K3s install script] **************************************************************************************************************************************************************************

changed: [localhost]


TASK [prepare_k3s_offline : Download K3s Air-Gap Image Archive] *******************************************************************************************************************************************************************

changed: [localhost]


TASK [prepare_k3s_offline : Download Helm binary] *********************************************************************************************************************************************************************************

changed: [localhost]


TASK [prepare_k3s_offline : Compress offline package] *****************************************************************************************************************************************************************************

changed: [localhost]


PLAY RECAP ************************************************************************************************************************************************************************************************************************

localhost                  : ok=12   changed=8    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[lds@ansible-host with-ansible]$ 



[lds@ansible-host with-ansible]$ ls

files  group_vars  install-k3s.yml  inventory.ini  k3s_offline_package  k3s_offline_package.tar.gz  playbook.yml  prepare.yml  README.md  roles

[lds@ansible-host with-ansible]$ vi group_vars/all.yml 

[lds@ansible-host with-ansible]$ vi clearup.yml

[lds@ansible-host with-ansible]$ cat clearup.yml 

- name: Cleanup K3s offline package from localhost

  hosts: localhost

  become: yes

  vars_files:

    - group_vars/all.yml

  roles:

    - clearup

[lds@ansible-host with-ansible]$ 

[lds@ansible-host with-ansible]$ 

[lds@ansible-host with-ansible]$ ansible-galaxy init roles/clearup

- Role roles/clearup was created successfully

[lds@ansible-host with-ansible]$ vi roles/clearup/tasks/main.yml

[lds@ansible-host with-ansible]$ cat roles/clearup/tasks/main.yml

---

# tasks file for roles/clearup


- name: Remove extracted K3s offline package directory

  ansible.builtin.file:

    path: "{{ offline_package_dir }}"

    state: absent


- name: Remove compressed K3s offline package tarball

  ansible.builtin.file:

    path: "{{ offline_package_archive }}"

    state: absent

[lds@ansible-host with-ansible]$ 

[lds@ansible-host with-ansible]$ ansible-playbook -i inventory.ini clearup.yml --ask-become-pass

BECOME password: 


PLAY [Cleanup K3s offline package from localhost] *********************************************************************************************************************************************************************************


TASK [Gathering Facts] ************************************************************************************************************************************************************************************************************

ok: [localhost]


TASK [clearup : Remove extracted K3s offline package directory] *******************************************************************************************************************************************************************

changed: [localhost]


TASK [clearup : Remove compressed K3s offline package tarball] ********************************************************************************************************************************************************************

changed: [localhost]


PLAY RECAP ************************************************************************************************************************************************************************************************************************

localhost                  : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[lds@ansible-host with-ansible]$ tree

.

├── clearup.yml

├── files

├── group_vars

│   └── all.yml

├── install-k3s.yml

├── inventory.ini

├── playbook.yml

├── prepare.yml

├── README.md

└── roles



[lds@ansible-host with-ansible]$ git add . -A

[lds@ansible-host with-ansible]$ git commit -m "Edit inventory and Add clear file process"

[main d5df566] Edit inventory and Add clear file process

 13 files changed, 181 insertions(+), 69 deletions(-)

 create mode 100644 clearup.yml

 create mode 100644 roles/clearup/README.md

 create mode 100644 roles/clearup/defaults/main.yml

 create mode 100644 roles/clearup/handlers/main.yml

 create mode 100644 roles/clearup/meta/main.yml

 create mode 100644 roles/clearup/tasks/main.yml

 create mode 100644 roles/clearup/tests/inventory

 create mode 100644 roles/clearup/tests/test.yml

 create mode 100644 roles/clearup/vars/main.yml

[lds@ansible-host with-ansible]$ git push origin main


(gnome-ssh-askpass:80482): Gtk-WARNING **: 17:32:43.106: cannot open display: 

error: unable to read askpass response from '/usr/libexec/openssh/gnome-ssh-askpass'

Username for 'https://gitlab.com': taeminKwon


(gnome-ssh-askpass:80483): Gtk-WARNING **: 17:32:46.953: cannot open display: 

error: unable to read askpass response from '/usr/libexec/openssh/gnome-ssh-askpass'

Password for 'https://taeminKwon@gitlab.com': 

warning: redirecting to https://gitlab.com/lds_solution/ezauto/install/with-ansible.git/

Enumerating objects: 32, done.

Counting objects: 100% (32/32), done.

Delta compression using up to 4 threads

Compressing objects: 100% (14/14), done.

Writing objects: 100% (24/24), 2.54 KiB | 1.27 MiB/s, done.

Total 24 (delta 5), reused 0 (delta 0), pack-reused 0

To https://gitlab.com/lds_solution/ezauto/install/with-ansible

   7bda580..d5df566  main -> main

[lds@ansible-host with-ansible]$ 

```

댓글목록

등록된 댓글이 없습니다.

회원로그인

회원가입

사이트 정보

회사명 : (주)리눅스데이타시스템
대표이사 : 정정모
본사 : 강남구 봉은사로 114길 40 홍선빌딩 2층
- tel : 02-6207-1160
대전지사 : 유성구 노은로174 도원프라자 5층
- tel : 042-331-1161

접속자집계

오늘
2,421
어제
2,585
최대
8,445
전체
2,034,631
Copyright © www.linuxdata.org All rights reserved.