본문 바로가기
AWS/Part 4. Ch04 앤서블을 이용한 서버 형상 관리

CH04_08. 반복문 (Loop)

by Engineer-Lee 2022. 6. 17.
반응형

이번 시간에는 앤서블 반복문에 대해 알아보자

 

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

 

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 several files and/or directories with the file module, creating multiple users with the user module, a

docs.ansible.com

 

앤서블 반복문에는 loop, with_<lookup>, until 문이 있다.

 

먼저 until은 retry를 위해 사용된다.

이는 어떠한 조건을 만족할 때까지 작업을 반복시킨다.

 

 

loop는 앤서블2.5부터 생긴 신규 문법이다.


playbook.yaml 파일의 tasks를 보자

https://github.com/tedilabs/fastcampus-devops/tree/main/2-ansible/07-loop

 

GitHub - tedilabs/fastcampus-devops: 🚀 패스트캠퍼스 데브옵스 초격차 코스 자료

🚀 패스트캠퍼스 데브옵스 초격차 코스 자료. Contribute to tedilabs/fastcampus-devops development by creating an account on GitHub.

github.com

 

 

첫 번째 task는 with_items 문법을 사용해서 세 가지 요소를 정의했다.

state: "present"를 통해 생성한다는 의미를 부여했고 name에는 진자템플릿을 이용해서 "item"이라는 키워드를 사용했다.

"item" 키워드는 반복문에서 루프1에서는 backend, 루프2에서는 frontend, 루프3에서는 devops를 가리킨다.

 

플레이북을 실행해보면 ubuntu1, 2에 대해 item이 루프에 의해 잘 바뀌는 걸 볼 수 있다.

 

 

우분투에 접속해서 그룹파일을 열어보면 사용자가 잘 추가된 걸 볼 수 있다.


이번에는 루프가 사용된 코드를 보자

이것도 with 구문과 같이 item 변수에 john, alice, claud, henry, jeremy, may를 차례로 대입하여 사용자를 만든다.

 

 


loop를 좀 더 응용하면 아래와 같은 코드가 된다.

 

 

반응형

'AWS > Part 4. Ch04 앤서블을 이용한 서버 형상 관리' 카테고리의 다른 글

CH04_10. 상세 (Facts)  (0) 2022.06.17
CH04_09. 조건문 (Conditional)  (0) 2022.06.17
CH04_07. 변수 (Variables)  (0) 2022.06.17
CH04_06. 핸들러 (Handler)  (0) 2022.06.17
CH04_05. 모듈 (Module)  (0) 2022.06.16