자동화/Ansible

[Ansible] ansible의 설치와 시작(CentOS)

closun 2023. 6. 9. 11:54

1. IaC란

infrasturucture as a code의 약자로

인프라를 코드로 정의하고 자동으로 관리하는 방식이다.

1.1 장점

1. 자동화로 인한 효율성

반복 작업을 제거할 수 있다.

2. 일관된 환경 유지

개발, 테스트, 운영 환경을 동일하게 유지할 수 있다.

3. 버전 관리 기능

Git을 사용해서 버전을 관리할 수 있다.

2. ansible 이란

2.1 ansible의 설치

yum install -y epel-release epel
yum install -y ansible

 

ansible을 하나의 관리서버에 설치해서 관리하면 된다. 

 

 

2.2 inventory 생성

/etc/ansible/hosts 에서 기본적으로 관리할 서버들을 정의하므로, 이곳에 inventory를 생성한다.

inventory란? Ansible이 관리할 서버 목록을 정의하는 파일

/etc/ansible/hosts

[all]
10.0.0.2
10.0.0.3
10.0.0.4 

[web]
10.0.0.2

[was]
10.0.0.3

[db]
10.0.0.4

-> [all] 이 의미하는 것은 전체 서버 그룹
-> [web] 은 WEB 서버만 포함하는 그룹
-> [was] 는 WAS 서버만 포함하는 그룹
-> [db]는 DB 서버만 포함하는 그룹

 

 

 

ansible all -m ping

▲ ansible이 서버들에 접속 가능한지 확인

 

 

 

2.3 ansible의 shell 모듈 사용하기

shell 모둘 => 터미널에서 명령을 실행하는 것과 같음 

root 디렉토리 내용 출력

ansible all -m shell -a "ls -al /root"

-> all : [all] inventory에 등록된 모든 서버에서 실행 

-> -m: shell 모듈을 호출

-> -a: 뒤의 명령어를 실행하여 /root 디렉토리의 내용을 전부(a) 길게(l) 리스트로 보여준다. 

2.4 디렉토리, 파일 생성, 파일 삭제-File 모듈 사용하기 

ansible all -m shell -a "mkdir /test"
ansible all -m file -a "path=/test state=directory"
ansible all -m file -a "path=/test state=absent"

shell 모듈 외에도 다른 모듈들을 활용하여 ansible 코드를 작성할 수 있다.

아래 링크에서 다양한 모듈을 확인할 수 있다.

All modules — Ansible Documentation

[All modules — Ansible Documentation

docs.ansible.com](https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html)