Ansible 4일차

AeZan·2024년 7월 8일
0

반복문

목적: 코드 간소화 -> 파일 용량 감소, 문법적 오류 감소

반복문을 사용하지 않는 단순 구문

---
- name: httpd and mariadb are running
  hosts: 192.168.56.102
  become: yes
  tasks:
    - name: httpd is running
      service:
        name: httpd
        state: started
    - name: mariadb is running
      service:
        name: mariadb
        state: started

{{ item }}: ansible 에서 반복 작업을 위해 지정되어 있는 기본 변수

  • loop 와 함께 주로 많이 사용됨
---
- name: httpd and mariadb are running
  hosts: 192.168.56.11
  tasks:
    - service:
        name: "{{ item }}"
        state: started
      loop:
        - httpd
        - mariadb

실행 결과는 같음

변수 지정 후 반복문 사용 가능

---
- name: httpd and mariadb are running
  hosts: 192.168.56.11
  vars:
    web_db:
      - httpd
      - mariadb
  tasks:
    - service:
        name: "{{ item }}"
        state: started
      loop: "{{ web_db }}"

사전 반복문

키:값 의 형태인 사전 자료형을 이용하는 방법

  hosts: 192.168.56.102
  tasks:
    - user:
        name: "{{ item.name }}"
        group: "{{ item.group }}"
        state: present

      loop:
        - name: jin
          group: jin
        - name: user01
          group: user01


조건문

조건에 만족하면 구문을 수행하는 문장

변수를 이용한 조건문

조건이 참이면 mariadb 서비스를 중지하는 플레이북 작성

---
- name: boolean test
  hosts: 192.168.56.102
  become: true
  vars:
    run_my_task: true
  tasks:
    - name: mariadb is stopped
      service:
        name: mariadb
        state: stopped
      when: "{{ run_my_task }}"
      # when: run_my_task 이렇게 써도 변수로 인식함

변수가 존재하는지를 확인해서 조건문 사용 가능

# 변수가 선언되었는지를 확인함 -> is defined

---
- name: boolean test
  hosts: 192.168.56.102
  become: true
  vars:
    my_service: mariadb
  tasks:
    - name: mariadb is started
      service:
        name: mariadb
        state: started
      when: my_service is defined

조건 연산자

A == B        A와 B는 같다
A == "B"      A와 B는 같다 (문자열) -> A: "B" 로 선언시

A < B         A가 B보다 작다
A > B         A가 B보다 크다
A <= B       A가 B보다 작거나 같다
A >= B       A가 B보다 크거나 같다
A != B        A가 B가 다르다
A              A가 1이거나 true 면 참
not A         A가 0이거나 false면 참
A in B        A가 B 안에 있으면 참
A not in B    A가 B 안에 없으면 참

---
- name: Redhat in keyward
  hosts: 192.168.56.102
  gather_facts: yes
  become: yes
  vars:
    supported_distros:
      - Redhat
      - Fedora
      - CentOS # 추가해주면 skipped = 1 없어짐
  tasks:
    - name: stopped mariadb using service, where supported
      service:
        - name: mariadb
          state: stopped
      when: ansible_distribution in supported_distros
# ansible_distribution -> fact

해당 사항이 없어 mariadb 가 꺼지지 않고 skipped 됨

변수에 CentOS 추가해주면 됨

and와 or를 이용한 복수 조건 테스트

and: 둘 다 참이어야 함, 하나라도 거짓이면 거짓
or: 하나만 참이면 참, 둘 다 거짓이면 거짓

---
- name: and or test
  hosts: localhost
  vars:
    - A: "a"
    - B: "b"
  tasks:
    - name: and test1
      debug:
        msg: >
          This is working
      when: A=="a" and B=="c"  # 거짓

    - name: and test2
      debug:
        msg: >
          This is working
      when: A=="a" and B=="b"

    - name: or test1
      debug:
        msg: >
          This is working
      when: A=="a" or B=="c"
    - name: or test2
      debug:
        msg: >
          This is working
      when: A=="b" or B=="c"  # 거짓

조건문과 반복문 섞어 쓰기

---
- name: httpd and mariadb are running
  hosts: 192.168.56.102
  become: yes
  vars:
    web_db:
      - httpd
      - mariadb
  tasks:
    - service:
        name: "{{ item }}"
        state: started
      loop: "{{ web_db }}"
      when: "'A' == 'A'"
      # 문자열끼리 비교한 것을 각각을 따로 보기 때문에 문자열로 전체를 하나로 취급해서 참인지 확인
      # '"A" == "A"' 도 같은 결과


mariadb 서비스가 실행 중이면 중지시키는 플레이북 작성

---
- name: Restart httpd if httpd is running
  hosts: 192.168.56.102
  tasks:
    - name: Get httpd server status
      command: /usr/bin/systemctl is-active httpd
      ignore_errors: yes 
      # 노드가 2개라고 할 때, 둘 중 하나가 다운됐을 때 하나라도 살아있기 때문에 무시할 수 있도록 함
      # 또는 위 command 가 에러가 발생하더라도 다음 작업으로 넘어갈 수 있도록 함
      register: result  # result 변수에 command 의 결과가 저자됨

- name: Restart Apache HTTPD based on httpd status
  hosts: 192.168.56.102
  become: yes
  tasks:
    - service:
        name: httpd
        state: restarted
      when: result.rc == 0  # commandline 실행 후 반환 코드. linux 에서는 0: true, 1:false


핸들러

  • 트리거 기능 사용
  • name 항목이 중요함
  • 등록해놓고 가져다가 쓰는 개념

핸들러를 구현한 플레이북

---
- name: handler example
  hosts: 192.168.56.102
  tasks:
    - name: check handler
      command: echo "Your tasks are completed"
      notify: restart httpd

  handlers:
    - name: restart httpd
      become: yes
      service:
        name: httpd
        state: restarted

    - name: restart mariadb
      become: yes
      service:
        name: mariadb
        state: restarted
  • echo 의 출력값이 보이지 않는 이유는 ansible은 ssh로 연결하여 작업하기 때문에 다른 쉘에서 작동이 되었기 때문임

ignore_errors 없이 playbook 작성

---
- name: Latest version of notapkg is installed
  hosts: 192.168.56.102
  become: yes
  tasks:
    - yum:
        name: notapkg
        state: latest

- name: Latest version of ftpd is installed
  hosts: 192.168.56.102
  become: yes
  tasks:
    - yum:
        name: gnutls
        state: latest

작업 실패 무시하고 진행 -> ignore_errors 작성

---
- name: Latest version of notapkg is installed
  hosts: 192.168.56.102
  become: yes
  tasks:
    - yum:
        name: notapkg
        state: latest
  ignore_errors: yes

- name: Latest version of ftpd is installed
  hosts: 192.168.56.102
  become: yes
  tasks:
    - yum:
        name: gnutls
        state: latest


파일 배포

파일을 만드는 플레이북 파일 생성

---
- name: touch file
  hosts: all
  tasks:
    - file:
        mode: 0644
        path: /home/jin/jinjin
        owner: jin
        group: jin
        state: touch # touch 명령어로 빈파일 생성

0개의 댓글

관련 채용 정보