공부하기싫어
article thumbnail
  • 제어 구조

순차 구조 - 명령이 기술된 순서로 순차적으로 수행하는 구조

선택 구조 - 조건에 따라 명령의 실행 순서를 변경할 수 있는 구조 - 선택문

반복 구조 - 특정 명령을 일정 횟수 동안 반복해서 수행한느 구조 - 반복문

Ansible Playbook 에 선택문 / 반복문은 모듈 키워드 형태를 사용하여 적용

 

  • 조건문(선택문)

Task 가 특정 조건에만 작업을 수행하도록 구성할 때 사용

when 키워드 사용

- task 레벨의 조건문에서 사용하며 언제 실행하는가? 를 정의할 때 사용한다고 함

- 조건문을 사용하는 주된 이유중 하나는 RedHat 계열의 Debian 계열의 리눅스가 혼재할 때 조건을 걸어 각 OS 에 맞게 인프라를 세팅할 때 사용한다고 한다

---
- name: variable test
  hosts: managed
  gather_facts: True

  tasks: 
    - debug:
        msg: "hello CentOS"
      when: ansible_facts["distribution"] == "CentOS"
    - debug:
        msg: "hello Amazon"
      when: ansible_facts["distribution"] == "Amazon"
    - debug:
        msg: "hello Ubuntu"
      when: ansible_facts["distribution"] == "Ubuntu"

when 으로 fact 정보 안의 distribution 확인

조건에 대한 표현식을 test, filter 키워드 사용

조건문에 변수를 참조할때 "{{ 변수명}}" 사용하지 않고 바로 변수명을 사용함

조건 결과가 True 일때 task 실행

 

공부하려고 인터넷 뒤지다가 거의 교과서처럼 해놓은걸 발견함

https://nice-engineer.tistory.com/entry/Ansible-%EC%A1%B0%EA%B1%B4%EB%AC%B8

 

[Ansible] 조건문(Conditionals)

✔️ 조건문 Conditionals — Ansible Documentation In a playbook, you may want to execute different tasks, or have different goals, depending on the value of a fact (data about the remote system), a..

nice-engineer.tistory.com

 

  • Tests ( 테스트문 )

https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html

 

Tests — Ansible Documentation

The following tasks are illustrative of the tests meant to check the status of tasks Note From 2.1, you can also use success, failure, change, and skip so that the grammar matches, for those who need to be strict about it.

docs.ansible.com

테스트는 표현식을 평가하고 True / False 반환

when : 변수 연산 -> 변수를 테스트 하기 위한 테스트 문

 

Testing task results

- [변수] is failed - 작업 실패

- [변수] is changed - 작업 성공적 실행 및 변경 수행

- [변수] is succeeded - 작업 성공적 실행

- [변수] is skipped - 조건문에 의해 실행되지 않음

tasks:

  - shell: /usr/bin/foo
    register: result
    ignore_errors: True

  - debug:
      msg: "it failed"
    when: result is failed

  # in most cases you'll want a handler, but if you want to do something right now, this is nice
  - debug:
      msg: "it changed"
    when: result is changed

  - debug:
      msg: "it succeeded in Ansible >= 2.1"
    when: result is succeeded

  - debug:
      msg: "it succeeded"
    when: result is success

  - debug:
      msg: "it was skipped"
    when: result is skipped

이외에도 테스트문에는

 

Testing strings - To match strings against a substring or a regular expression, use the match, search or regex testsTesting truthiness - As of Ansible 2.10, you can now perform Python like truthy and falsy checks.Comparing versionsSet theory testsTesting if a list contains a value 등이 있다

 

  • filters ( 필터 )

https://docs.ansible.com/ansible/2.3/playbooks_filters.html#other-useful-filters

 

Filters — Ansible Documentation

Filters in Ansible are from Jinja2, and are used for transforming data inside a template expression. Jinja2 ships with many filters. See builtin filters in the official Jinja2 template documentation. Take into account that templating happens on the the Ans

docs.ansible.com

 

when: < 변수[ | (자료형)] > <조건 연산자> 값

변수 | (자료형) 표현은 변수 형 변환을 의미하고, | 다음에 형변환을 원하는 자료형 기입, 숫자형으로 변환할 때 사용

조건연산자 사용 - > < >= <= == !=

 

ex)

- debug: msg: "{{ hadoop_version is version(\"3.0.0\", '<') }}"

하둡 버전이 3.0.0 보다 낮은지를 비교함

- {{ zk_server_ip | join(',') }}

join 은 리스트 형식의 변수를 모아서 반환함.

- {% if list | length > 2 %} list 의 길이기 2 초과이면 처리

{% else %} list의 길이기 1이하이면 처리

 

예제)

---
- name: filter test
  hosts: managed
  gather_facts: True

  vars:
  - name : yeonwoo
    filepath : /home/ec2-user/ansible-workspace/playbook-yaml/playbookext.txt

  tasks:
  - debug:
      msg: "{{ (name == 'yeonwoo') | ternary('Mr','Ms') }}"
  - debug:
      msg: "{{ (name == 'yoonchan') | ternary('Mr','Ms') }}"
  - debug:
      msg: "{{ filepath | basename }}"

참이면 Mr 거짓이면 Ms , 변수가 path 일때 basename 만 출력

결과

 

 

  • 반복문

https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#playbooks-loops

 

Loops — Ansible Documentation

As of Ansible 2.8 you can get extended loop information using the extended option to loop control. This option will expose the following information. Note When using loop_control.extended more memory will be utilized on the control node. This is a result o

docs.ansible.com

 

Task 를 반복해서 동작시킬 때 사용

모듈의 키워드 (keyword, Attribute 성격) 로 사용

with_* 키워드와 loop 키워드 사용

- with_items

- with_nested

- with_sqeuence

+@ 이전 ansible 버전에서는 with_를 사용했었다가 loop 로 변경됫다고 함 -> 아직 같이 사용한다고 함

패키지 관련 모듈은 반복문을 사용하지 않는 것을 권장함

반복문에서 제공되는 목록을 참조하는 변수명은 항상 item 사용

 

예제)

https://nice-engineer.tistory.com/entry/Ansible-%EB%B0%98%EB%B3%B5%EB%AC%B8?category=1057046 

 

[Ansible] 반복문(Loops)

✔️ 반복문 Loops — Ansible Documentation Loops Ansible offers the loop, with_ , and until keywords to execute a task multiple times. Examples of commonly-used loops include changing ownership on s..

nice-engineer.tistory.com

 

 

 

  • include ( 포함 )

playbook 의 내용이 많아지거나 복잡한 경우 더 작은 단위로 나누면 관리 편의성이 높아진다.

모듈식으로 여러 개의 playbook 을 main playbook 에 결합하거나 파일의 task 를 play에 포함시킬 수 있다.

이와 같은 방식으로 playbook을 모듈로 나누면 재사용성이 높아진다 ( 모듈화 )

 

ansible 에서 파일이나 role을 특정 playbook 에 읽어들일 때 import / include 2가지 방법 중 하나를 사용할 수 있다.

https://docs.ansible.com/ansible/2.9/user_guide/playbooks_reuse_includes.html

 

Including and Importing — Ansible Documentation

As noted in Creating Reusable Playbooks, include and import statements are very similar, however the Ansible executor engine treats them very differently. All import* statements are pre-processed at the time playbooks are parsed. All include* statements ar

docs.ansible.com

 

 

  • import - static(정적) re-use

role, task, playbook 등을 playbook 에 정적으로 포함

ansible은 읽어들인 파일이나 role 등을 최상위 playbook 에서 작업을 실행하기 전에 사전 처리한다.

import 된 playbook 은 최상위 playbook 이 되며 다른 task 에 영향을 받지 않는다.

ex) import_playbook: <playbook 파일명>

 

 

  • include - dynamic(동적) re-use

role, task, playbook 등을 playbook 에 동적으로 포함

include 된 콘텐츠는 최상위 playbook 의 이전 작업 결과에 영향을 받음

최상위 playbook 의 실행 결과에 따라 실행 될 수도 안 될 수도 있다.

ex) include:<playbook 파일명>

 

관련해서 구글링하던중에 한 블로그에서 명확하게 둘의 차이점을 정리해놨어서 가져옴

https://hkjeon2.tistory.com/69

 

[Ansible] import vs include 차이점

주요 차이점은 다음과 같습니다. import * (import_playbook, import_tasks 등) 문은 플레이북이 Parsing될 때 사전에 처리가된다. include * (include_playbook, incloude_tasks 등) 문은 플레이북을 실행하는 동..

hkjeon2.tistory.com

 

 

 

  • Handler ( 핸들러 )

https://docs.ansible.com/ansible/latest/user_guide/playbooks_handlers.html

 

Handlers: running operations on change — Ansible Documentation

Sometimes you want a task to run only when a change is made on a machine. For example, you may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged. Ansible uses handlers to address this u

docs.ansible.com

Handler는 함수(function)와 비슷한 개념 - 단위 기능 실행

Task가 할 수 있는 일을 똑같이 할 수 있다.

playbook의 task 에서 handler 를 호출하게 되면 해당 handler 가 호출되어 실행되는 방식으로 동작함

반복되는 동작에 대하여 별도의 handler 로 정의

 

핸들러 설명 블로그

https://nice-engineer.tistory.com/entry/Ansible-%ED%95%B8%EB%93%A4%EB%9F%AC-Handler?category=1057046 

 

[Ansible] 핸들러 (Handler)

✔️ 핸들러 (Handler) Handlers: running operations on change — Ansible Documentation Sometimes you want a task to run only when a change is made on a machine. For example, you may want to restart a..

nice-engineer.tistory.com

핸들러의 실행 순서

- 알림을 받은 핸들러 작업만 순서대로 실행됨

- 모든 작업(task)이 완료되어야 핸들러가 실행됨

- 알림을 받은 횟수와 상관 없이 한번만 실행됨

 

handler는 이름이 호출되므로 notify 에 기술된 handler 이름이 실제 handler 색션에 정의된 handler 이름과 같아야 한다.

변수 사용시에는 include_vars 모듈 사용

 

---
- name: loop test
  hosts: managed
  gather_facts: False

  tasks: 
    - name: task1
      file: 
        path: /tmp/test1
        state: touch
      notify:
        - handle2
    - name: task2
      file: 
        path: /tmp/test2
        state: touch
      notify:
        - handle1

  handlers:
    - name: handle1
      debug:
        msg: "handle1"
    - name: handle2
      debug: 
        msg: "handle2"

예제 코드가 위와 같을때

결과는

결과

실행 순서는 task1 -> task2 -> handler1 -> handler2 순서로 실행된다.

 

listen key 를 handler task 에 부여하면 notify 시 listen 에 부여한 이름으로 호출하면 listen key 가 정의된 handler 가 모두 동작한다

handlers:
  - name: Restart memcached
    ansible.builtin.service:
      name: memcached
      state: restarted
    listen: "restart web services"

  - name: Restart apache
    ansible.builtin.service:
      name: apache
      state: restarted
    listen: "restart web services"

tasks:
  - name: Restart everything
    ansible.builtin.command: echo "this task will restart the web services"
    notify: "restart web services"

이렇게 notify 에 listen 에 부여한 이름을 호출하면 위의 memcached 랑 apache 모두 동작하는것 같다

 

 

  • Roles ( 역할 )

https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html#playbooks-reuse-roles

 

Roles — Ansible Documentation

The classic (original) way to use roles is with the roles option for a given play: When you use the roles option at the play level, Ansible treats the roles as static imports and processes them during playbook parsing. Ansible executes each play in this or

docs.ansible.com

Roles 는 include의 확장 개념

역할에 따라 roles 폴더에 필요한 파일들을 별도로 생성하여 사용

role 에서 다른 role 을 포함할 수 있고 변수 전달도 가능

역할에 따른 role을 작성해서 관리함으로써 관리의 편의성과 재사용성을 높일 수 있는 프로젝트 관리 방법

 

role 관리 방법

- roles 이름의 폴더(디렉토리) 생성

- roles 폴더 아래에 필요한 폴더 추가 생성 - files, handlers, tasks, templates, vars, meta)

   - tasks/main.yml - 역할 실행 task 저장 파일

   - handlers/main.yml - handler 저장 파일

   - vars/main.yml - 변수 저장 파일

- playbook 에는 적용하고 싶은 role을 roles 섹션에 추가

 

ansible roles 정리된 블로그

https://nice-engineer.tistory.com/entry/Ansible-artifact-%EC%9E%AC%EC%82%AC%EC%9A%A9-%EC%97%AD%ED%95%A0roles?category=1057046 

 

[Ansible] artifact 재사용 - 역할(roles)

✔️ artifact 재사용 - 역할 Roles — Ansible Documentation Role dependencies let you automatically pull in other roles when using a role. Ansible does not execute role dependencies when you include..

nice-engineer.tistory.com