쿠버네티스 전문가 양성과정 7주차 5일(2/3)

최수환·2023년 2월 3일
0

Kubernetes

목록 보기
31/75
post-thumbnail

Ansible

플레이북

작업제어

이전 블로그에서는 작업제어의 반복문까지 다루었다.
이번에는 반복문 이후에 조건문부터 다룰 예정이다.

조건문

  • Ansible은 조건문을 사용하여 특정 조건을 충족하는 작업 또는 플레이를 실행할 수 있음
  • 서비스를 설치하거나 구성하기 전에 관리 호스트에서 사용 가능한 메모리를 확인하는데 조건문을 사용할 수 있음
  • 조건문을 사용하여 관리자가 관리 호스트간의 차이점을 구분하고 충족된 조건을 기반으로 하여 기능 역활을 할당할 수 있음
  • 플레이북 변수, 등록된 변수 및 Ansible 팩트는 모두 조건문을 사용하여 테스트할 수 있음.
  • Ansible은 조건부에서 테스트 및 필터 를 사용
  • 테스트는 표현식을 평가하고 True 와 False를 반환
  • 조건문에서 변수를 참조 하더라도 변수명에 {{ }} 이중 중괄호를 사용하지 않음

1 . 문자열 테스트

- name: condition test
  hosts: ansi-node1
  gather_facts: 0
  vars:
    url: "http://www.nobreak.co.kr/guest/document/index.html"
  tasks:
  - debug:
      msg: "match pattern 1"
    when: url is match("http://")
  - debug:
      msg: "match pattern 2"
    when: url is match("http://....nobreak")
  - debug:
      msg: "match pattern 3"
    when: url is match("nodirect")
  - debug:
      msg: "match pattern 4"
    when: url is match("http://.*html")


-> 해당 url과 일치하는 패턴은 1,2,4가 나오는 것을 알 수 있다
-> 주로 정규표현식을 사용하여 일치하는 패턴을 찾아낸다

2 . 버전 비교 테스트

- name: condition
  hosts: ansi-node1
  vars:
    version: 1.2.3
  tasks:
  - debug:
      msg: " version is greater than 1.0.0 "
    when: version is version('1.0.0','>')
  - debug:
      msg: "version is greater than 1.0.0"
    when: version is version('1.0.0','gt')


-> 'gt' 와 '>'는 같기 때문에 문장이 두번 출력되는 것을 확인

3 . 경로 테스트

- name: condition test
  hosts: ansi-node1
  vars:
    path1: "/etc/passwd"
    path2: "/etc/ansible"
    path3: "/etc/ansible/facts.d/test.fact"
    path4: "/etc/ansible/facts.d/test1.fact"
    path5: "/"
  tasks:
  - debug:
      msg: "File type is File"
    when: path1 is file
  - debug:
      msg: "File typeis Directory"
    when: path2 is directory
  - debug:
      msg: "FIle is exists"
    when: path3 is exists
  - debug:
      msg: "File is exists"
    when: path4 is exists
  - debug:
      msg: "{{ path5 }} is mounted"
    when: path5 is mount

-> 파일인지 디렉터리인지, 존재하는지, 마운트 되어있는지 출력할 수 있다

4 . 작업 상태 테스트

- name: condition test
  hosts: ansi-node1
  gather_facts: 0
  tasks:
  - command: lt # 오타입력 
    register: result
    ignore_errors: yes # 오타를 입력했기 때문에 에러는 패스한다 
  - debug:
      msg: "This job is fail"
    when: result is failed 
  - debug:
      msg: "This job is success"
    when: result is success
  - debug:
      msg: "This job changed"
    when: result is changed


-> 작업이 실패인지, 성공인지, 변경인지를 알 수 있다
-> 변경은 멱등성을 생각한다 (ex. 패키지 설치...)

5 . 조건문 작업 구문

  • 작업 또는 플레이북을 실행하면 Ansible은 호스트에 대한 테스트를 평가
  • 테스트를 통과한(True 값을 반환하는) 모든 호스트에서 Ansible은 해당 작업을 실행
- name: condition test
  hosts: ansi-node3
  tasks:
  - name: install Ubuntu
    apt:
      name: tcsh
      update_cache: yes
      state: present
    when: ansible_facts.distribution == "Ubuntu"
  - name: install CentOS
    yum:
      name: tcsh
      state: present
    when: ansible_facts.distribution == "CentOS"


-> ansible_facts로부터 distribution정보를 가져왔을 때 ubuntu이기 때문에 첫번째 조건은 출력된다

- name: condition test
  hosts: ansi-node3
  vars_prompt:
  - name: pkg
    private: no
  tasks:
  - apt:
      name: "{{ pkg }}"
      update_cache: yes
      state: present
    when: pkg is defined
    # when: pkg != "" 구문이랑 같다

-> 변수가 선언되어야만 실행된다

6 . 복수 조건에 따른 실행

  • 여러 조건이 있는 경우 괄호를 사용해 연산의 우선 순위를 그룹화 할 수 있고, and, or 연산을 사용할 수 있음

  • 조건목록: 여러 조건을 목록으로 표현하면 and 연산이 적용

7 . register 변수에 따른 조건

  • 플레이북에서 이전 작업의 결과에 따라 작업을 실행하거나 건너뛰고 싶을 때가 있음
  • 이전 작업에서 업그레이드한 후 서비스를 구성할 수 있음
  • register 변수를 기반으로 조건을 생성하는 요건
    • 이전 작업의 결과를 변수로 등록
    • register 변수를 기반으로 조건부 테스트를 생성
  • register 변수에는 항상 변수를 생성한 작업의 상태와 작업이 생성한 모든 출력이 포함
  • register는 템플릿과 액션 라인뿐만 아니라 조건문에서도 사용 가능
- name: condition test
  hosts: ansi-node2
  tasks:
  - command: ls
    register: ls_result

  - debug:
      msg: "/home/vagrant is empty"
    when: ls_result.stdout == ""

  - debug:
      msg: "/home/vagrant is not empty"
    when: ls_result.stdout != ""

  - file:
      state: touch
      dest: /home/vagrant/testfile
    when: ls_result.stdout == ''


-> 플레이북 첫 실행에서 파일이 없기 때문에 empty문장을 출력하고 파일을 생성한다

-> 다시 실행하면 이미 파일이 생성되어있기 때문에 not empty문장을 출력하고 파일 생성을 스킵한다

- name: register + loop test
  hosts: ansi-node1
  tasks:
  - command: ls -al /home/vagrant
    register: ls_result

  - debug:
      msg: "{{ ls_result.stdout }}" # '/n'이 포함된 결과 출력
  - debug:
      msg: "{{ ls_result.stdout.split('\n') }}" # '/n'을 기준으로 한줄씩 출력
  - debug:
      msg: "{{ ls_result.stdout_lines }}" # 위의 결과와 같은 결과
  - debug:
      msg: "{{ item }}"
    loop: "{{ ls_result.stdout.split('\n') }}"
    # '\n'을 기준으로 한줄씩 끊어서 반복문에서 출력

8 . 변수 기반 조건부

  • 플레이북이나 인벤토리에 정의된 변수를 기반으로 조건문을 생성
  • 조건문에는 부울 입력이 필요하기 때문에(조건을 트리거하려면 테스트가 True로 평가되어야 함) 'yes', 'on', '1' 또는 'true'와 같은 콘텐츠가 포함된 문자열 변수와 같은 부울이 아닌 변수에 필터를 적용
- name: condition test
  hosts: ansi-node1
  vars:
    bool1: yes
    bool2: 'yes'
    bool3: 1
    bool4: no
  tasks:
  - debug:
      msg: "yes1"
    when: bool1
  - debug:
      msg: "yes2"
    when: bool2
    ignore_errors: yes
  - debug:
      msg: "yes3"
    when: bool2 | bool
  - debug:
      msg: "yes4"
    when: not bool3
  - debug:
      msg: "yes5"
    when: not bool4        


-> 부울값이 문자열이면 에러가 난다
-> 문자열 부울값을 ' | bool ' 필터를 통해 진짜 부울값으로 바꿀 수 있다

9 . 반복문과 조건문 결합

  • when 명령문을 loop 와 결합하면 Ansible은 각 항목에 대해 조건을 개별적으로 처리
  • 이것은 의도적으로 설계된 것이므로 루프의 일부 항목에서는 작업을 실행하고 다른 항목에서는 건너뛸 수 있음
  • 작업에서 loop와 함께 when을 사용하면 각 항목에 대해 when 문이 검사
- name: condition + loop test
  hosts: ABC
  vars:
    list1:
    - one
    - two
  tasks:
  - debug:
      msg: "{{ item }}"
    loop: "{{ list1 }}"
    when: ansible_hostname in ['ansi-node1','ansi-node2']        


-> ansible_facts에서 hostname을 참조해 node1과 node2에 한해서 반복문을 실행한다

9-1 . 리스트를 반복할 때

- name: condition + loop test
  hosts: ansi-node1
  vars:
    list1:
    - 1
    - 2
    - 3
    - 4
    - 5
    - 6
  tasks:
  - debug:
      msg: "num print {{ item }}"
    loop: "{{ list1 }}"
    when: item < 4


-> 리스트에서 조건문을 통해 4보다 작은 수만 출력하는 것을 확인

9-2 . 딕셔너리를 반복할 때

- name: condition + loop test
  hosts: ansi-node1
  gather_facts: 0
  vars:
    list1:
    - alpha: a # part1
      num: 1
    - alpha: b # part2
      num: 2
    - alpha: c # ...
      num: 3
    - alpha: d # ...
      num: 4
    - alpha: e # ...
      num: 5
  tasks:
  - debug:
      msg: "{{ item.alpha }}"
    loop: "{{ list1 }}"
    when: item.num < 4


-> list1이 반복문에 의해 item이 되어 한 파트씩 꺼내와서 num을 가져와 조건문에서 비교해 alpha를 출력한다

10 . stat모듈을 사용한 조건문

  • Ansible stat 모듈 을 사용하여 파일의 세부 정보를 확인 가능
  • stat 모듈 : Linux stat 명령을 사용하여 작업에 지정된 '경로'를 확인
- name: test stats
  hosts: ansi-node1
  gather_facts: 0
  tasks:
  - name: stat
    stat:
      path: /etc/passwd
    register: result
  - name: print
    debug:
      msg: " file exists "
    when: result.stat.exists == true
  - name: print
    debug:
      msg: "file not exists "
    when: result.stat.exists == false


-> stat 연산의 결과를 register에 저장하고 작업
-> stat 명령을 사용하여 원격 서버에서 passwd를 확인.
-> stat에는 boolean 값인 'exists'라는 반환 값이 있어서 파일이 존재하면 true를 반환하고 그렇지 않으면 false를 반환
-> 해당 경로에 파일이 존재하는지 안하는지 파악할 수 있다

-> result.stat을 출력을 해보면 exists항목이 존재하는 것을 볼 수 있다

- name: test stats
  hosts: ansi-node1
  gather_facts: 0
  tasks:
  - name: stat
    stat:
      path: /usr/lib
    register: result
  - name: print
    debug:
      msg: " is file "
    when: result.stat.exists == true and result.stat.isdir == false
  - name: print
    debug:
      msg: " is directory "
    when: result.stat.exists == true and result.stat.isdir == true


-> stat모듈로 해당 경로의 자세한 정보를 register에 담고 register에서 stat항목의 exists와 isdir 값을 이용해 파일 존재유무와 디렉터리인지 파일인지 구분을 한다

profile
성실하게 열심히!

0개의 댓글