paint-brush
Ansible 101: 팩트 및 템플릿 작업~에 의해@cloudkungfu
723 판독값
723 판독값

Ansible 101: 팩트 및 템플릿 작업

~에 의해 cloud-kung-fu4m2024/01/30
Read on Terminal Reader

너무 오래; 읽다

Ansible은 변수, 사실 및 템플릿을 활용하여 적응 가능한 자동화 워크플로우를 생성합니다. 변수는 동적 구성 관리를 가능하게 하고, 사실은 시스템별 정보를 제공하며, 템플릿은 사용자 정의 가능한 구성 파일을 생성합니다. 이 접근 방식을 사용하면 다양한 환경에서 플레이북을 재사용하고 유연하게 사용할 수 있습니다.
featured image - Ansible 101: 팩트 및 템플릿 작업
cloud-kung-fu HackerNoon profile picture
0-item

Ansible에서는 템플릿과 함께 변수와 팩트가 유연한 자동화 워크플로를 생성하기 위한 기본 도구입니다. 변수를 사용하면 구성을 동적으로 관리하고 변경할 수 있습니다. 사실은 Ansible이 원격 시스템에서 수집하여 상황별 정보를 제공하는 변수의 특수 하위 집합입니다.


템플릿을 사용하면 변수 기반 구성 파일을 생성할 수 있으므로 플레이북을 다양한 환경과 시나리오에 맞게 조정할 수 있습니다.


이러한 도구를 사용하면 플레이북을 재사용하고 적응할 수 있으므로 값을 하드 코딩하지 않고 다양한 환경에 맞게 사용자 지정할 수 있습니다.

변수 및 사실

변수를 사용하면 플레이북의 핵심 로직을 변경하지 않고도 매개변수를 수정할 수 있습니다.

사실, 변수 및 템플릿이 함께 작동하는 방식

  • 변수 유형:
    • 부울: True 또는 False 값입니다.

    • 목록: 순서가 지정된 항목 모음입니다.

    • 사전: 복잡한 데이터 구조를 위한 키-값 쌍입니다.

    • 등록된 변수: 나중에 플레이북에서 사용할 작업의 출력을 캡처합니다.

    • 사실: 관리 중인 원격 시스템에 대한 세부 정보를 제공하는 자동 수집 변수입니다.


주의: 대괄호 표기법을 사용하여 변수 이름의 충돌을 피하세요.


 - name: Print the distribution of the target hosts: all vars: curr_time: "{{ now() }}" tasks: - name: Distro Check ansible.builtin.debug: msg: "The target system is {{ ansible_facts['distribution'] }}. Timestamp: {{ curr_time }}"

템플릿 및 파일

Ansible의 템플릿은 Jinja2 템플릿 언어를 사용하여 변수 보간, 루프 및 조건을 사용하여 파일을 동적으로 생성합니다.


 - name: Write distro name hosts: all tasks: - name: Write distro name ansible.builtin.template: src: distro.j2 dest: /root/distro.txt mode: '644' # src: location of jinja2 template file # dest: location it will be copied to # permissions that will be granted to the file

관행

우리는 OS 제품군을 사용하여 Lighttpd의 NGINX를 설치할지 여부를 결정한 다음 호스트 이름을 하드코딩하지 않고 NGINX가 포함된 원격 호스트에 사용자 지정 홈페이지를 배포할 것입니다.


  1. 저장소를 복제합니다.
 git clone https://github.com/perplexedyawdie/ansible-learn.git


2. 디렉토리를 사실 및 템플릿 으로 변경

 cd ansible-learn/facts-and-templates


3. docker-compose를 사용하여 환경 가동

 docker compose up -d --build


4. Ansible 서버에 SSH로 접속

 ssh -o StrictHostKeyChecking=no -o NoHostAuthenticationForLocalhost=yes root@localhost -p 2200 # password: test123

변수 및 사실

5. server_setup.yaml 이라는 플레이북을 생성합니다. 여기서는 NGINX & Lighttpd를 설정한 다음 각 원격 호스트에 대한 배포판 이름을 출력합니다.


 - name: Install NGINX on Debian & Lighttpd on RedHat hosts: all vars: dev1: "Debian" dev2: "RedHat" tasks: - name: Install NGINX for Debian-based systems ansible.builtin.apt: name: nginx state: present when: ansible_facts['os_family'] == dev1 - name: Install Lighttpd for RedHat-based systems ansible.builtin.yum: name: lighttpd state: present when: ansible_facts['os_family'] == dev2 - name: Display the distribution ansible.builtin.debug: msg: "The server is running {{ ansible_facts['distribution'] }}"


6. ansible-lint.

 ansible-lint server_setup.yaml


7. 플레이북을 실행합니다.

 ansible-playbook --key-file /root/.ssh/id_rsa_ansible -u root -i inventory.yaml server_setup.yaml


8. 설정이 성공적으로 완료되었는지 확인합니다.

 ssh -i /root/.ssh/id_rsa_ansible root@server3 nginx -V ssh -i /root/.ssh/id_rsa_ansible root@server2 lighttpd -v ssh -i /root/.ssh/id_rsa_ansible root@server1 lighttpd -v

템플릿 및 파일

9. index.html.j2 라는 Jinja2 템플릿 파일을 생성합니다.


OS 제품군 및 배포판이 자동으로 채워집니다.


 <html> <head> <title>Welcome to {{ ansible_facts['os_family'] }}</title> </head> <body> <h1>Server running on {{ ansible_facts['distribution'] }}</h1> </body> </html>


10. custom_homepage.yaml.


위에서 만든 사용자 정의 홈페이지를 NGINX에 배포한 다음 서버를 다시 시작합니다.


 - name: Deploy Custom Homepage and restart hosts: all vars: dev1: "Debian" dev2: "RedHat" tasks: - name: Create Homepage with Jinja2 Template for NGINX ansible.builtin.template: src: index.html.j2 dest: /var/www/html/index.html mode: '644' when: ansible_facts['os_family'] == dev1 notify: restart nginx handlers: - name: Restart NGINX listen: "restart nginx" ansible.builtin.service: name: nginx state: restarted when: ansible_facts['os_family'] == dev1


11. 린터를 실행합니다.

 ansible-lint custom_homepage.yaml


12. 플레이북을 실행합니다.

 ansible-playbook --key-file /root/.ssh/id_rsa_ansible -u root -i inventory.yaml custom_homepage.yaml


13. 브라우저에서 http://localhost:2203 방문하여 배포를 확인합니다.

요약

노력이 대단해요! 🙌 템플릿을 사용하여 동적 파일을 만드는 방법과 함께 플레이북에서 변수 및 사실을 사용하는 방법을 배웠습니다. 다음으로 모듈화와 오류 처리에 대해 살펴보겠습니다. 그때까지 조심하세요!