참고 사이트:
3-모듈
모듈은 단일 명령어 이자 수행할 작업입니다. `cp`, `apt`, `wget` 등의 단일 명령어가 모듈이라고 할 수 있습니다. 앤서블은 다양한 기본 모듈을 제공하고, 이 모…
wikidocs.net
공식 문서:
Ansible.Builtin — Ansible Documentation
© Copyright Ansible project contributors. Last updated on Jan 11, 2024.
docs.ansible.com
모듈(Module)
- ansible이 실행하는 코드 단위
- 단일 명령어
- 수행할 적업
- 데이터베이스 처리, 사용자 관리, 네트워크 장치 관리 등 다양한 용도로 사용
0. 호스트 정보
inventory.ini 파일에 ansible 호스트 생성된 상태.
1. 공통
ignore_errors: yes
- 오류 무시
become: yes
- root 권한으로 실행
when:
- 조건문 분기
tags:
- 실행 태그 추가
environment:
- 실행 환경 변수 설정
2. 파일
1) file
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html
ansible.builtin.file module – Manage files and file properties — Ansible Documentation
The permissions the resulting filesystem object should have. For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for
docs.ansible.com
mode
파일 권한
recurse: yes
하위 디렉토리 포함
state: link
심볼릭 링크 생성
state: hard
하드 링크 생성
state: absent
파일 삭제
state: directory
디렉토리 생성
state: touch
파일 생성
예시:
# 디렉토리 생성
---
- name: Create a directory if it does not exist
hosts: ansible
tasks:
- name: Ensure the directory exists
ansible.builtin.file:
path: ~/ansible_test
state: directory
mode: '0755'
결과:
2) 압축 해제
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/unarchive_module.html
ansible.builtin.unarchive module – Unpacks an archive after (optionally) copying it from the local machine — Ansible Documen
The permissions the resulting filesystem object should have. For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for
docs.ansible.com
unarchive:
src를 dest 위치로 압축 풀기
remote_src: yes
원격 서버의 압축파일 풀기
become: true
root권한으로 압축 풀기
3) 복사
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html
ansible.builtin.copy module – Copy files to remote locations — Ansible Documentation
The permissions of the destination file or directory. For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must either add a leading zero so that Ansible’s YAML parser knows it is an octal number (like 0644 or 01777) or qu
docs.ansible.com
copy:
src를 dest 위치로 복사
remote_src: yes
원격 서버의 파일을 복사
become: yes
root권한으로 파일 복사
with_items(=loop)
여러 항목에 대한 작업 수행
(with_items는 Ansible 2.5 버전 이전에 사용되어 loop 사용 권장)
---
# with_items 예시
- name: Copy files using with_items
hosts: your_target_host
tasks:
- name: Copy files
ansible.builtin.copy:
src: "{{ item.src }}" # with_items로부터 받은 각 항목의 src 값
dest: "{{ item.dest }}" # with_items로부터 받은 각 항목의 dest 값
with_items:
- { src: '/path/to/file1.txt', dest: '/path/on/remote/host/file1.txt' }
- { src: '/path/to/file2.txt', dest: '/path/on/remote/host/file2.txt' }
4) Template
파이썬의 jinja2 템플릿을 이용하여 파일을 변환하면서 복사
예시:
# template.j2
ServerName {{ server_name }}
Listen {{ port }}
DocumentRoot {{ document_root }}
# template_playbook.yaml
---
- name: Use template module to create a configuration file
hosts: your_target_host
vars:
server_name: example.com
port: 80
document_root: /var/www/html
tasks:
- name: Create configuration file using template
ansible.builtin.template:
src: template.j2 # 로컬 템플릿 파일 경로
dest: ~/httpd.conf # 원격 호스트에 배포될 경로
결과:
5) get_url
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/get_url_module.html
ansible.builtin.get_url module – Downloads files from HTTP, HTTPS, or FTP to node — Ansible Documentation
If a checksum is passed to this parameter, the digest of the destination file will be calculated after it is downloaded to ensure its integrity and verify that the transfer completed successfully. Format: : , e.g. checksum=”sha256:D98291AC[…]B6DC7B97
docs.ansible.com
get_url:
파일 다운로드
environment:
프록시 설정이 필요할 경우 사용
예시:
# ansible로 habor 다운로드 및 압축풀기
---
- name: Download and extract harbor
hosts: ansible
tasks:
- name: Download tar archive
ansible.builtin.get_url:
url: "https://github.com/goharbor/harbor/releases/download/v2.10.0/harbor-offline-installer-v2.10.0.tgz"
dest: "~/harbor-offline-installer-v2.10.0.tgz"
- name: Extract tar archive
ansible.builtin.unarchive:
src: "~/harbor-offline-installer-v2.10.0.tgz"
dest: "~/"
remote_src: yes #대상 호스트에 있는 파일 압축 해제
결과:
6) stat
stat:
파일 및 디렉토리 상태 확인
register:
파일 사이즈, 존재 여부, 권한 등 상태 확인
예시:
# ansible 폴더가 있는지 확인
---
- name: Check the status of a directory
hosts: ansible
tasks:
- name: Get the status of a harbor directory
ansible.builtin.stat:
path: ~/harbor
register: directory_status
- name: Display the directory status
ansible.builtin.debug:
var: directory_status.stat
결과:
3. 명령어 실행
1) shell
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html
ansible.builtin.shell module – Execute shell commands on targets — Ansible Documentation
Note This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name shell even without specifying the collections keyword. However, we recommend you use the Fully Qualified Collection Name (F
docs.ansible.com
shell:
명령어 또는 스크립트 실행
register:
명령어 실행 결과 저장
shell: |
여러 명령어를 한번에 실행
예시:
# 경로 확인
---
- name: Execute a shell command
hosts: ansible
tasks:
- name: Run a shell command
ansible.builtin.shell:
cmd: "ls -l ~/"
register: result # result 변수에 결과 저장
- name: Display the command result
ansible.builtin.debug:
var: result.stdout_lines # result 변수에서 결과 출력
결과:
2) apt
apt:
apt명령어 실행
state: absent
제거
update_cache: yes
apt 업데이트
예시:
# apt 업데이트 및 패키지 tree 설치
---
- name: Update APT package cache
hosts: ansible
become: yes
tasks:
- name: Update package cache
ansible.builtin.apt:
name: tree
update_cache: yes
3) systemd
systemctl 명령어로 서비스 실행
예시:
# Docker 재시작
---
- name: Start a systemd service
hosts: ansible
tasks:
- name: Restart Docker
ansible.builtin.systemd:
name: docker
state: restarted
daemon_reload: True #systemd 설정 변경 후에 해당 변경 사항이 즉시 적용
4. 기타
1) debug
플레이북 실행 중에 변수의 값을 출력하거나 디버그 정보를 확인하는 데 사용
예시:
# 변수 설정 후 변수값 출력
---
- name: Example using debug module
hosts: ansible
tasks:
- name: Set a variable
ansible.builtin.set_fact:
my_variable: "Hello, Ansible!"
- name: Display the value of the variable
ansible.builtin.debug:
var: my_variable
결과:
'Ansible' 카테고리의 다른 글
Ansible Missing sudo password (0) | 2024.01.30 |
---|---|
Ansible Roles ②Tasks(Apache 설치 유무에 따라 자동 설치/삭제) (0) | 2024.01.15 |
Ansible Roles ①개념(+ Ansible로 Apache 설치) (0) | 2024.01.15 |
Ansible 구성요소 (0) | 2024.01.11 |