Cloud Engineering/Ansible

[Ansible] 조건문 사용하기 - 문자열/버전/팩트변수/경로/파일/마운트 검사하기

minjiwoo 2023. 3. 6. 17:19
728x90

Ansbile 의 플레이북 파일을 작성할 때 조건문으로 작업을 제어할 수 있다. 

Ansbile에서는 when 이라는 키워드를 사용하여 조건을 걸 수 있다. 또한 비교연산자 및 키워드를 이용하여  값을 비교할 수 있다. 해당 조건문이 참이면 작업을 실행하고, 거짓이면 실행하지 않는다. 

키워드  부호 의미
lt < little than 
le <= little or equal 
gt \> greater than
ge \>= greater or equal
e =, == equal
ne != not equal

 

 

1. 문자열 검사하기 

해당 문자열과 일치하는지 / 포함되어 있는지 확인한다. 

  • match("PATTERN") : 패턴과 전체 문자열이 일치하는지 확인한다.  Bool 값을 리턴한다. 
  • search("PATTERN") : 패턴이 문자열에 있는지 확인한다.  Bool 값을 리턴한다. 
- hosts: ansi-node1
  vars:
    myurl: "www.singclairstudio.tistory.com/index.html"
  tasks:
  - debug:
      msg: "matched!"
    when: myurl is match(".*com.*")
  - debug:
      msg: "searched!"
    when: myurl is search("tistory")
  - debug:
      msg: "matched!"
    when: myurl is match("com")

결과는 다음과 같다. 마지막 task의 경우, myurl != "com" 이므로 조건문이 False 여서 skipped 되었다. 

2. 버전 비교하기 

일반적으로 버전은 문자열로 확인한다. 

version("VERSION", "비교연산자") : VERSION과 현재 버전을 비교연산자로 비교하고 Bool 값을 리턴한다. 

- hosts: ansi-node1
  vars:
    myversion: 20.0.1
  tasks:
  - debug:
      msg: "version is high"
    when: myversion is version("18.0.1", "gt")

결과는 다음과 같다. 조건문이 참이므로 메세지가 출력된다. 

TASK [debug] ************************************************************************************************************
ok: [ansi-node1] => {
    "msg": "version is high"
}

 

3. 경로 / 파일 / 마운트 검사하기 

  • file: 해당 경로가 파일인지 검사
  • directory: 해당 경로가 디렉토리인지 검사
  • exists : 해당 파일/ 경로가 존재하는지 검사
  • mount : 해당 경로가 마운트되었는지 검사 

우선 ansi-node1에 fileA 라는 파일과 new_dir라는 디렉토리를 생성해주었다. 

vagrant@ansi-node1:~$ touch fileA
vagrant@ansi-node1:~$ mkdir new_dir

playbook 예시 

- hosts: ansi-node1
  vars:
    var1: "/etc/hosts"
    var2: "/etc"
    var3: "/"
    var4: "/notdir"
  tasks:
  - debug: 
      msg: "This is file"
    when: var1 is file
  - debug: 
      msg: "This is dir"
    when: var2 is directory
  - debug: 
      msg: "This is mounted"
    when: var3 is mount
  - debug:
      msg: "exists"
    when: var4 is exists
  - debug: 
      msg: "not exists"
    when: var4 is not exists

결과적으로, var4 는 존재하지 않으므로, 이 조건문에 의해 4번째 작업은 수행되지 않았다. 

4. 작업 결과 상태 검사하기 

  • failed : 작업 실패 
  • success : 작업 성공
  • skipped : 작업이 조건문에 의해 실행되지 않고 넘어감. 
  • changed : 변경사항이 적용되었음 (멱등성이 있는 작업)

플레이북 예시

- hosts: ansi-node1         
  vars:                      
    dir1: /notdir           
  tasks:                    
  - command: ls {{ dir1 }}     
    register: result1       
    ignore_errors: yes      
  - debug:                  
      msg: "Failed!"        
    when: result1 is failed 
  - debug:                  
      msg: "Success!"       
    when: result1 is success

현재 /notdir 는 없는 디렉토리이다. 당연히 command 작업 실행 결과는 Failed 이고 두번째 작업의 조건문에 의해, Failed! 메세지가 출력된다. 

5. 팩트변수 사용하기 

== 또는 != 부등호를 팩트변수와 함께 사용할 수 있다. 

- hosts: DD
  tasks:
  - debug:
      msg: "{{ ansible_hostname }}"
    when: ansible_hostname == "ansi-node1"

현재 DD 그룹에는 ansi-node1, ansi-node2, ansi-node3 이 있다. 위의 조건문에 따라 hostname이 ansi-node1 인 경우에만 메세지를 출력한다. 

6. 복수 조건문 (and/or) 사용하기 

여러개의 조건을 and , or 를 통해 걸 수 있다. 

- hosts: DD
  vars:
    dict1:
      apple: 5000
      banana: 2000
      grape: 1000
  tasks:
  - debug:
      msg: "{{ item.key }} {{ item.value }}"
    loop: "{{ query('dict', dict1) | default({}) }}"
    when: item.value > 1000 and item.value < 5000

query() 는 dictionary 를 list 형태로 반환해준다. loop 문에는 리스트 변수가 들어가야 하므로 dictionary를 list 형태로 바꿔주어야 한다. 조건은 1000원보다 크고 5000원보다 작아야 한다. 따라서 조건을 만족하는 banana만 출력된다. 

 

 

728x90