[Ansible] Ansible의 핵심 Role 및 Variables
본문 바로가기
IT 이야기/Ansible

[Ansible] Ansible의 핵심 Role 및 Variables

by 찬찬이 아빠 2020. 6. 7.
반응형
  1. Role 개념

 

  • 중복 소스 제거
  • 자주 사용하는 것들은 Role 로 만듬
  • 미리 레시피를 만들어 놓고 호출만 하면 끝!

(1) 프로젝트 구조 예시

site.yml
web.yml
test.yml
roles/
   common/
      files/
      templates/
      tasks/
      handlers/
      vars/
      defaults/
      meta/
   chan/
      files/
      templates/
      tasks/
      handlers/
      vars/
      defaults/
      meta/

 

 

(2) 호출 방법

---
- hosts: web
  roles:
    - common
    - chan

 

(3) 변수나 조건 설정

---
- hosts: web
  roles:
    - {role: touch_files, touch_files_path: '/home/deploy/touch_files'}
    - {role: touch_files, touch_files_path: '/home/deploy/touch_files', when: "ansible_os_family == 'RedHat'"}

 

 

 

  2. Role 실습

(1) touch_files 을 Role로 실습

 

  • Role 디렉터리 생성
# mkdir -p roles/touch_files/tasks

 

  • Role로 변환
vim roles/touch_files/tasks/main.yml

---
- name: make directory
  file:
    path: "{{touch_files_path}}"
    state: directory
    
- stat:
    path: "{{touch_files_path}}/jacob.txt"
  register: result

- name: touch file
  file:
    path: "{{touch_files_path}}/{{item}}.txt"
    state: touch
  with_items:
    - "{{id}}1"
    - "{{id}}2"
    - "{{id}}3"
  when:
    - result.stat.exists == false
vim playbooks/touch_files_role.yml

<방법1>
---
- name: touch test
  vars_files:
    - ../group_vars/common.yml
  hosts: all
  vars:
    touch_files_path: /home/deploy/touch_files
    id: chan
  roles:
    - touch_files


<방법2>
---
- name: touch test
  vars_files:
    - ../group_vars/common.yml
  hosts: web
  roles:
    - {role: touch_files, touch_files_path: /home/deploy/touch_files, id: chan}

 

(2) Variables를 Role로 실습

 

  • 변수는 공통 파일로 관리

 

vim playbooks/install_nginx.yml

---
- hosts: web
  vars_files:
    - ../../group_vars/common.yml
  roles:
  	- install_nginx

 

vim playbooks/install_nginx.yml

---
- hosts: all
  vars_files:
    - ../../group_vars/common.yml
  roles:
  	- install_nginx

 

  • Hosts에서 관리
vim hosts/admin

[web]
test-web01	nginx_version=nginx-1.12.1
test-web02  nginx_version=nginx-1.12.1

[db]
test-db01

 

  • Playbook에서 관리
vim playbooks/install_nginx.yml

---
- hosts: all
  vars:
    - nginx:
        - version: nginx-1.12.1
        - download_url: https://nginx.org/download/nginx-1.12.1.tar.gz
  roles:
    - install_nginx

 

  • Roles 의 vars 에서 관리
vim roles/install_nginx/vars/main.yml

- nginx: 
   - version: nginx-1.12.1 
   - download_url: https://nginx.org/download/nginx-1.12.1.tar.gz
반응형

댓글