[Ansible] Playbook 개념, 구조, 실습 예
본문 바로가기
IT 이야기/Ansible

[Ansible] Playbook 개념, 구조, 실습 예

by 찬찬이 아빠 2020. 6. 6.
반응형
  1. Playbook 개념
  • 인벤토리 파일에서 정의한 대상 서버들이 무엇을 수행할 것인지 정의
  • YAML 문법을 사용하여 정의
  • 단독으로 사용되는 것이 아닌 인벤토리와 플레이북의 조합으로 수행

 

  2. Playbook 구조

Playbooks - play - tasks 구조

 

 

Playbooks - play - Roles 구조

 

 

Playbooks - Hosts - Roles 관계

 

  3. playbook 작성 시 유의사항 및 준비사항

(1) 유의사항

  • YAML 파일 작성 시 들여쓰기는 TAB 키가 아닌 Space Bar 키로 할 것
  • {{변수}}가 있는 곳은 " "로 감쌀 것
- file:
   path: "/etc/{{filename}}.conf"
   owner: chan
   group: chan
   mode: 0644

 

(2) 준비사항

  • ansible 환경 설정(ansible.cfg) 파일 설정
[defaults]
fork = 30
remote_user = ansible
remote_port = 12400

roles_path = ./roles

 

  • 디렉터리 구조 및 생성
# mkdir -p hosts group_vars playbooks roles

# ls
hosts				← 호스트 등록 디렉터리
group_vars			← 변수 디렉터리
playbooks			← playbook 디렉터리
roles				← roles 디렉터리
ansible.cfg			← ansible 환경설정 파일

 

  • 공통 변수 파일 생성

공통 변수를 파일로 관리하여 각 playbook에서 사용할 수 있습니다.

# vim group_vars/common.yml
user_id: chan
nginx:
   version: nginx-1.12.1
   download_url: https://nginx.org/download/{{nginx.version}}.tar.gz

 

 

  4. 실습 예

(1) ping 테스트

  • playbook을 사용하지 않고 명령어로 수행
# ansible all -i /hosts/web -m ping

 

  • playbook으로 변환
<basic.yml>

---
- name : ping test
  tasks:
     - name: test connection
       ping:

 

  • playbook 실행
# ansible-playbook playbooks/basic.yml -i hosts/web

 

 

(2) touch로 파일 생성

# vim playbooks/touch_files.yml

---
- name: touch files test
  vars_files:
     - ../group_vars/common.yml
  hosts: web
  tasks:
     - name: make directory
        file:
           path: /home/deploy/touch_files
           state: directory
           
     - name: touch file
        file:
           path: /home/deploy/touch_files/test.txt
           state: touch
# ansible-playbook playbooks/touch_files.yml

 

 

(3) 변수 활용 (vars, {{변수명}})

실습 예제 2번 설정을 보면 /home/deploy/touch_files 가 중복됩니다.

변수를 활용하면 깔끔하게 작성할 수 있습니다.

변수를 사용할 때는 {{variables}} 형태로 사용하면 됩니다.

# vim playbooks/touch_files2.yml

---
- name: touch files test2
  vars_files:
     - ../group_vars/common.yml
  hosts: web
  vars:
     touch_files_path: /home/deploy/touch_files
     id: chan
  tasks:
     - name: make directory
        file:
           path: "{{touch_files_path}}"
           state: directory
           
     - name: touch file
        file:
           path: "{{touch_files_path}}/{{id}}.txt"
           state: touch
# ansible-playbook playbooks/touch_files2.yml

 

 

(4) 루프를 이용하여 여러 파일 생성 (item, with_items)

{본인이름}[1-3].txt을 생성합니다.

# vim playbooks/with_items.yml

<방법1>
---
- name: with items test
  vars_files:
     - ../group_vars/common.yml
  hosts: web
  vars:
     touch_files_path: /home/deploy/touch_files
     id: chan
  tasks:
     - name: make directory
        file:
           path: "{{touch_files_path}}"
           state: directory
           
     - name: touch file
        file:
           path: "{{touch_files_path}}/{{item}}.txt"
           state: touch
        with_items:
           - "{{id}}1"
           - "{{id}}2"
           - "{{id}}3"
           
 
 <방법2>
---
- name: with items test
  vars_files:
     - ../group_vars/common.yml
  hosts: web
  vars:
     touch_files_path: /home/deploy/touch_files
     id: chan
  tasks:
     - name: make directory
        file:
           path: "{{touch_files_path}}"
           state: directory
           
     - name: touch file
        file:
           path: "{{touch_files_path}}/{{item.id}}{{item.num}}.txt"
           state: touch
        with_items:
           - {id: "{{id}}, num: 1}
           - {id: "{{id}}, num: 2}
           - {id: "{{id}}, num: 3}
# ansible-playbook playbooks/with_items.yml

 

 

(5) 조건문 실습

http://docs.ansible.com/ansible/latest/playbooks_conditionals.html

 

Conditionals — Ansible Documentation

Often the result of a play may depend on the value of a variable, fact (something learned about the remote system), or previous task result. In some cases, the values of variables may depend on other variables. Additional groups can be created to manage ho

docs.ansible.com

 

OS가 RHEL이고 버전이 7일 경우에만 실행되게 해봅니다.

vim playbooks/conditionals.yml

---
- name: conditionals test
  vars_files:
    - ../group_vars/common.yml
  hosts: web
  vars:
    touch_files_path: /home/deploy/touch_files
    id: chan
  tasks:
    - name: make directory
      file:
        path: "{{touch_files_path}}"
        state: directory
        
    - name: touch file
      file:
        path: "{{touch_files_path}}/{{item}}.txt"
        state: touch
      with_items:
        - "{{id}}1"
        - "{{id}}2"
        - "{{id}}3"
      when:
        - ansible_distribution == "RHEL"
        - ansible_distribution_major_version == "7"
        #- (ansible_distribution == "RHEL" and ansible_distribution_major_version == "7")
# ansible-playbook playbooks/conditionals.yml

 

 

(6) 파일이 존재하면 실행하고, 없으면 실행되게 수행 (stat, register, when)

https://docs.ansible.com/ansible/latest/modules/stat_module.html

 

stat – Retrieve file or file system status — Ansible Documentation

© Copyright 2019 Red Hat, Inc. Last updated on May 18, 2020.

docs.ansible.com

# vim playbooks/stat_test.yml

---
- name: stat test
  vars_files:
    - ../group_vars/common.yml
  hosts: web
  vars:
    touch_files_path: /home/deploy/touch_files
    id: chan
  tasks:
    - name: make directory
      file:
        path: "{{touch_files_path}}"
        state: directory
        
    - stat:
        path: "{{touch_files_path}}/{{id}}.txt"
      register: result
    
    - name: touch file
      file:
        path: "{{touch_files_path}}/{{item}}.txt"
        state: touch
      with_items:
        - "{{id}}1"
        - "{{id}}2"
        - "{{id}}3"
      when:
        - not result.stat.exists
        #- result.stat.exists == false
# ansible-playbook playbooks/stat_test.yml

 

 

(7) Playbook 안에 Playbook

vim playbook/site.yml

---
- include: web.yml
- include: db.yml



<web.yml>
---
- hosts: web
  roles:
    - common
    - apache
    
    
<db.yml>
---
- hosts: db
  roles:
    - common
    - cubrid
# ansible-playbook playbooks/site.yml --limit web
# ansible-playbook playbooks/web.yml

 

 

(8) Template 활용

http://docs.ansible.com/ansible/latest/template_module.html

 

template – Template a file out to a remote server — Ansible Documentation

© Copyright 2019 Red Hat, Inc. Last updated on May 18, 2020.

docs.ansible.com

  • 템플릿에 변수 {{variables}} 를 설정할 수 있습니다.
  • 템플릿을 이용하여 파일을 복사합니다.

<디렉터리 생성>

# mkdir -p roles/test_templates
# cd roles/test_templates
# mkdir tasks templates vars

 

<실습파일 생성>

vim roles/test_templates/vars/main.yml

templates_dir_path: /home/deploy/templates_test
user_id: chan
vim roles/test_templates/templates/test.txt

- user_id: {{user_id}}
- templates_dir_path: {{templates_dir_path}}
- hostname: {{inventory_hostname}}
vim roles/test_templates/tasks/main.yml

---
- name: make directory
  file:
    path: "{{templates_dir_path}}"
    state: directory
    
- name: copy test.text
  template:
    src: test.txt
    dest: "{{templates_dir_path}}/{{user_id}}.txt"
vim playbooks/test_templates.yml

---
- name: templates test
  vars_files:
    - ../group_vars/common.yml
  hosts: web
  roles:
    - test_templates
# ansible-playbook playbooks/test_templates.yml -i hosts/web -l alpha

 

(9) 템플릿 디렉터리 위치 변경

 

  • role 마다 templates 안에 템플릿들을 관리하는 것 보다 한 디렉토리 안에서 관리하는게 효율적입니다.
  • templates 디렉토리 생성 및 파일 복사
# mkdir templates
# cp roles/test_templates/templates/test.txt templates/

 

  • 실습 파일 생성
vim roles/test_templates/tasks/main.yml

---
- name: make directory
  file:
    path: "{{templates_dir_path}}"
    state: directory
    
- name: copy test.text
  template:
    src: ../../../templates/test.txt
    dest: "{{templates_dir_path}}/{{user_id}}.txt"

 

  • 공통 변수 group_vars에 등록하면 더 효율적입니다.
vim group_vars/common.yml

templates_path: ../../../templates
vim roles/test_templates/tasks/main.yml

---
- name: make directory
  file:
    path: "{{templates_dir_path}}"
    state: directory
    
- name: copy test.text
  template:
    src: "{{templates_path}}/test.txt"
    dest: "{{templates_dir_path}}/{{user_id}}.txt"
반응형

댓글