[Devops] Ansible 기초

2025. 3. 6. 23:29·Linux

1. Ansible 이란?

  • Ansible은 IT 자동화를 위한 오픈소스 도구
  • 서버 구성 관리, 애플리케이션 배포, 프로비저닝 등의 작업을 자동화할 수 있다.
  • SSH를 기반으로 동작하며, 별도의 에이전트(Agent) 설치 없이 관리 노드에서 원격 시스템을 제어할 수 있다

 

ANsible 구성도

2. Ansible 장점

  • 자동화 도구와 같이 관리 대상 서버에 별도의 에이전트 설치하지 않음
  • 에이전트 없이 SSH로 접속하여 대상 서버 관리
  • 동일한 연산을 여러번 적용하더라도 결과가 달라지지 않음
  • Yaml 문법을 사용하여 읽고 쓰기가 용이
  • 리눅스 기본 명령어 및 시스템 관리모듈, 클라우드, 쿠버네티스 등 다른 모듈과 컬렉션을 제공

3. 주요 구성

  1. 인벤토리

vi /etc/ansible/hosts
호스트명/IP : 호스트 명 또는 주소가 한줄에 위치
그룹: 그룹을 지어 목적에 따라 작업을 처리 
사양 호스트 간소화 : 성질이 같은 여러대의 노두의 경우 [start:end] 범위를 지정이 가능

#ansible config 적용 우선순위
1. `ANSIBLE_CONFIG` (environment variable if set)
2. `ansible.cfg` (in the current directory)
3. `~/. ansible.cfg` (in the home directory)
4. `/etc/ansible/ansible.cfg`

  2.  플레이북

   2.1 명령어 기초

 

   2.1플레이북 설정

ansible.cfg 파일을 통한 설정이 가능

vi /etc/ansible/ansible.cfg

[defaults]
inventory = ./
ask_pass = false

[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false
inventory   인벤토리 파일 경로 지정
remote_user  엔서블 관리 호스트 연결 사용자 이름 지정
ask_pass SSH암호 표시 여부
become 권한 에스컬레이션 활성화 시, 호스트의 사용자 전환 여부 지정
become_method 권한 사용자 전환 방식의미
become_user 관리 호스트 전환 사용자 지정 기본값:root

 

  2.2 테스트

ansible -m ping [대상서버]

 

옵션 가용옵션 설명
-m  ping,command,shell,copy
user
모듈 지정
-i    인벤토리 파일 지정
-a   -m 옵션으로 지정한 모듈 전달할 인수 지정
-u   특정 사용자 계정 접속 지정
-b   관리자 권한 사용
-ㅏ    비밀번호 입력할 수 있도록 지

  

  2.3 플레이북 작성

  예)

 

 

 

Ansible 설치

준비물: Python ansible,epel-release 

dnf -y install epel-release
페도라에서 관리하는 추가 패키지 리포지터리

dnf -y install ansible
#ansible 패키지

 

 


실습

상대방 이름으로 유저 생성

nginx 웹 서버 설치

해당 서버 웹 디렉터리 임의 내용의 index.html 파일 복사

방화벽 끄기

접속

---
- name: nginx web servdr
  hosts: all
  tasks: 
     
    - name: install epel-release
      dnf: 
        name: epel-release
        state: latest

    - name: install nginx
      dnf: 
        name: nginx
        state: latest
    - name: copy index.html
      get_url:
       url: https://nginx.org/
       dest: /usr/share/nginx/html/
    - name: start nginx
      service:
       name: nginx
       state: started
    - name: Disable firewall
      service:
        name: firewalld
        state: stopped
    - name: Eusure exampleuser exist
      user:
         name: testuser
         password: "{{ '1234'}}"
         shell: /bin/bash

 

- 플레이북 사용 예제 - 

더보기
모듈 사용 목적 예제
shell 쉘 명령어 실행 shell: echo 'Hello, World!'
command 쉘 명령어 실행 (파이프 사용 불가) command: ls -l /etc
dnf 패키지 설치/제거 (Fedora, CentOS 8+) dnf: name=httpd
state=absent
yum 패키지 설치/제거 (RHEL, CentOS) yum: name=nginx
state=latest
apt 패키지 설치/제거 (Debian, Ubuntu) apt: name=nginx
state=present
copy 파일 복사 copy: src=/local/file dest=/remote/path
template Jinja2 템플릿 파일 전송 template:
  src=config.j2
  dest=/etc/config
service 서비스 관리 service:
=nginx state
=restarted
systemd systemd 서비스 관리 systemd:
name=nginx
enabled=yes
state=started
firewalld 방화벽 설정 (firewalld) firewalld:
service=http
permanent=yes
state=enabled
iptables iptables 방화벽 규칙 추가 iptables:
chain=INPUT
protocol=tcp
destination_port=22
jump=ACCEPT
user 사용자 계정 관리 user:
name=devops
state=present
group 그룹 관리 group:
name=developers state=present
cron 크론 작업 추가 cron:
name='Backup' minute=0
hour=2
job='/usr/bin/backup.sh'
lineinfile 파일 내 특정 라인 추가/수정 lineinfile:
path=/etc/sysctl.conf
line='net.ipv4.ip_forward=1'
blockinfile 파일 내 특정 블록 추가/수정 blockinfile:
path=/etc/hosts
block='192.168.1.1 example.com'
replace 파일 내 문자열 교체 replace:
path=/etc/hosts
regexp='127.0.0.1' replace='127.0.1.1'
fetch 원격 파일 가져오기 fetch:
src=/remote/file
dest=/local/path
file 파일/디렉토리 속성 변경 file:
path=/tmp/example mode=0644
owner=root
group=root
debug 디버그 메시지 출력 debug:
msg='Task completed successfully'
vars 변수 선언 vars:
my_var: 'Hello World'
set_fact 변수 동적 설정 set_fact:
my_dynamic_var={{ ansible_hostname }}
wait_for 포트/파일/시간 대기 wait_for:
port=22
delay=10 timeout=60
uri HTTP 요청 전송 uri: url=http://example.com
method=GET
git Git 리포지토리 클론 git: repo='https://github.com/example/repo.git'
dest=/opt/repo

 

출처: https://hackjsp.tistory.com/35

'Linux' 카테고리의 다른 글

[Linux] Docker  (0) 2025.03.20
[Devops] Ansible 실습  (0) 2025.03.13
[Linux] DHCP 설정  (0) 2025.03.04
[Network] offset List  (0) 2025.02.25
[Linux] 메일 서버 구성  (0) 2025.02.19
'Linux' 카테고리의 다른 글
  • [Linux] Docker
  • [Devops] Ansible 실습
  • [Linux] DHCP 설정
  • [Network] offset List
cumo
cumo
  • cumo
    이것저것
    cumo
  • 전체
    오늘
    어제
    • 분류 전체보기 (92)
      • 이것저것 (1)
      • 보안뉴스 (14)
      • Project (9)
      • wargame (1)
      • Cloud (7)
      • DevOps (11)
      • Linux (20)
      • 네트워크 (23)
      • AWS Developer BootCamp (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 도구모음 사이트
    • 참고 기술 블로그
  • 공지사항

  • 인기 글

  • 태그

    1
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
cumo
[Devops] Ansible 기초
상단으로

티스토리툴바