
이전 블로그에서는 작업제어의 반복문까지 다루었다.
이번에는 반복문 이후에 조건문부터 다룰 예정이다.
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 . 조건문 작업 구문
- 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 변수에 따른 조건
- 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 . 변수 기반 조건부
- 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 . 반복문과 조건문 결합
- 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모듈을 사용한 조건문
- 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 값을 이용해 파일 존재유무와 디렉터리인지 파일인지 구분을 한다