Cheat sheet dei moduli Ansible
Ansible è un potente strumento di automazione. Questo articolo introduce l’uso dei suoi moduli più comuni.
Formato
Struttura di base dei file
---
- hosts: production
remote_user: root
tasks:
- ···Inserisci i tuoi moduli sotto tasks.
Formato delle attività (Task Format)
Formato a riga singola
- apt: pkg=vim state=presentFormato di mappatura (Mapping)
- apt:
pkg: vim
state: presentFormato scalare piegato (Folded)
- apt: >
pkg=vim
state=presentÈ possibile utilizzare uno qualsiasi dei formati sopra indicati per definire le attività. Il formato a riga singola è consigliato per dichiarazioni brevi, mentre il formato di mappatura è consigliato per dichiarazioni più lunghe.
Moduli
Aptitude
Gestione dei pacchetti
- apt:
pkg: nodejs
state: present # absent | latest
update_cache: yes
force: noFile pacchetto Deb
- apt:
deb: "https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb"Gestione dei repository
- apt_repository:
repo: "deb https://··· raring main"
state: presentChiave del repository
- apt_key:
id: AC40B2F7
url: "http://···"
state: presentRelativi a Git
- git:
repo: git://github.com/
dest: /srv/checkout
version: master
depth: 10
bare: yesRiferimento: modulo git
Configurazione Git
- git_config:
name: user.email
scope: global # local | system
value: [email protected]Riferimento: modulo git_config
Gestione degli utenti
- user:
state: present # Stato: presente
name: git # Nome utente
system: yes # Utente di sistema
shell: /bin/sh # Shell di login
groups: admin # Gruppi
comment: "Git Version Control" # CommentoRiferimento: modulo user
Gestione dei servizi
- service:
name: nginx # Nome del servizio
state: started # Stato: avviato
enabled: yes # Abilita all'avvioRiferimento: modulo service
Relativi alla Shell
Comando shell
- shell: apt-get install nginx -yOpzioni extra
- shell: echo hello
args:
creates: /path/file # Salta se il file esiste
removes: /path/file # Salta se il file non esiste
chdir: /path # Passa a questa directory prima dell'esecuzioneEsempio di comando multilinea
- shell: |
echo "hello there"
echo "multiple lines"Riferimento: modulo shell
Esecuzione script
- script: /x/y/script.sh
args:
creates: /path/file # Salta se il file esiste
removes: /path/file # Salta se il file non esiste
chdir: /path # Passa a questa directory prima dell'esecuzioneRiferimento: modulo script
Operazioni sui file
Gestione dei file
- file:
path: /etc/dir
state: directory # Tipo: directory|file|link|hard|touch|absent
# Parametri opzionali:
owner: bin # Proprietario
group: wheel # Gruppo
mode: 0644 # Permessi
recurse: yes # Ricorsivo
force: yes # Forza la creazione del collegamento simbolicoRiferimento: modulo file
Copia file
- copy:
src: /app/config/nginx.conf # File sorgente
dest: /etc/nginx/nginx.conf # Destinazione
# Parametri opzionali:
owner: user # Proprietario
group: user # Gruppo
mode: 0644 # Permessi
backup: yes # Backup se esisteRiferimento: modulo copy
Template
- template:
src: config/redis.j2 # Sorgente del template
dest: /etc/redis.conf # Destinazione
# Parametri opzionali:
owner: user # Proprietario
group: user # Gruppo
mode: 0644 # Permessi
backup: yes # Backup se esisteRiferimento: modulo template
Azioni locali
Esecuzione locale
- name: Esegue localmente
local_action: shell echo helloOutput di debug
- debug:
msg: "Hello {{ var }}"Riferimento: modulo debug
title: “Ansible モジュール チートシート” date: 2025-04-22T15:09:28+08:00 keywords: “Ansible モジュール チュートリアル, 自動化モジュール, Ansible Playbook, IT 運用ツール, サーバー設定, 自動デプロイ” description: “Ansible モジュールの包括的なリファレンス マニュアル。ファイル処理、パッケージ管理、サービス制御などの一般的なモジュールの使用方法を網羅し、強力な自動化ソリューションの構築を支援します。” draft: false tags: [“python”, “ansible”] programming: [“devops”]
Ansible は強力な自動化ツールです。この記事では、その一般的なモジュールの使用方法を紹介します。
形式
基本的なファイル構造
---
- hosts: production
remote_user: root
tasks:
- ···モジュールは tasks の下に配置してください。
タスクの形式
1行形式
- apt: pkg=vim state=presentマッピング形式
- apt:
pkg: vim
state: present折りたたみスカラー形式
- apt: >
pkg=vim
state=present上記のどの形式を使用してもタスクを定義できます。短い宣言には1行形式、長い宣言にはマッピング形式が推奨されます。
モジュール
Aptitude
パッケージ管理
- apt:
pkg: nodejs
state: present # absent | latest
update_cache: yes
force: noDeb パッケージ ファイル
- apt:
deb: "https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb"リポジトリ管理
- apt_repository:
repo: "deb https://··· raring main"
state: presentリポジトリ キー
- apt_key:
id: AC40B2F7
url: "http://···"
state: presentGit 関連
- git:
repo: git://github.com/
dest: /srv/checkout
version: master
depth: 10
bare: yesリファレンス: git モジュール
Git 設定
- git_config:
name: user.email
scope: global # local | system
value: [email protected]リファレンス: git_config モジュール
ユーザー管理
- user:
state: present # 状態: 存在
name: git # ユーザー名
system: yes # システム ユーザー
shell: /bin/sh # ログイン シェル
groups: admin # 所属グループ
comment: "Git Version Control" # コメントリファレンス: user モジュール
サービス管理
- service:
name: nginx # サービス名
state: started # 状態: 開始
enabled: yes # 自動起動を有効にするリファレンス: service モジュール
Shell 関連
shell コマンド
- shell: apt-get install nginx -y追加オプション
- shell: echo hello
args:
creates: /path/file # ファイルが存在する場合はスキップ
removes: /path/file # ファイルが存在しない場合はスキップ
chdir: /path # 実行前にこのディレクトリに切り替える複数行コマンドの例
- shell: |
echo "hello there"
echo "multiple lines"リファレンス: shell モジュール
スクリプト実行
- script: /x/y/script.sh
args:
creates: /path/file # ファイルが存在する場合はスキップ
removes: /path/file # ファイルが存在しない場合はスキップ
chdir: /path # 実行前にこのディレクトリに切り替えるリファレンス: script モジュール
ファイル操作
ファイル管理
- file:
path: /etc/dir
state: directory # 種類: directory|file|link|hard|touch|absent
# オプション パラメータ:
owner: bin # 所有者
group: wheel # グループ
mode: 0644 # 権限
recurse: yes # 再帰的に作成
force: yes # ソフトリンクの作成を強制するリファレンス: file モジュール
ファイル コピー
- copy:
src: /app/config/nginx.conf # 元ファイル
dest: /etc/nginx/nginx.conf # コピー先
# オプション パラメータ:
owner: user # 所有者
group: user # グループ
mode: 0644 # 権限
backup: yes # 存在する場合はバックアップリファレンス: copy モジュール
テンプレート
- template:
src: config/redis.j2 # テンプレート元ファイル
dest: /etc/redis.conf # ターゲット先
# オプション パラメータ:
owner: user # 所有者
group: user # グループ
mode: 0644 # 権限
backup: yes # 存在する場合はバックアップリファレンス: template モジュール
ローカル アクション
ローカル実行
- name: ローカルで操作を実行
local_action: shell echo helloデバッグ出力
- debug:
msg: "Hello {{ var }}"リファレンス: debug モジュール
title: “Ansible 모듈 요약표 (Cheat Sheet)” date: 2025-04-22T15:09:28+08:00 keywords: “Ansible 모듈 튜토리얼, 자동화 모듈, Ansible Playbook, IT 운영 도구, 서버 구성, 자동 배포” description: “파일 처리, 패키지 관리, 서비스 제어 등 자주 사용하는 모듈의 사용법을 포함한 Ansible 모듈 종합 참조 매뉴얼로, 강력한 자동화 솔루션을 구축하는 데 도움을 줍니다.” draft: false tags: [“python”, “ansible”] programming: [“devops”]
Ansible은 강력한 자동화 도구입니다. 이 문서에서는 자주 사용되는 모듈의 사용법을 소개합니다.
형식
기본 파일 구조
---
- hosts: production
remote_user: root
tasks:
- ···모듈은 tasks 아래에 배치하십시오.
작업 형식 (Task Format)
단일 행 형식
- apt: pkg=vim state=present매핑 형식
- apt:
pkg: vim
state: present접힌 스칼라 형식 (Folded Scalar)
- apt: >
pkg=vim
state=present위의 형식 중 하나를 사용하여 작업을 정의할 수 있습니다. 짧은 선언에는 단일 행 형식이, 긴 선언에는 매핑 형식이 권장됩니다.
모듈
Aptitude (패키지 관리)
패키지 관리
- apt:
pkg: nodejs
state: present # absent | latest
update_cache: yes
force: noDeb 패키지 파일
- apt:
deb: "https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb"저장소 관리
- apt_repository:
repo: "deb https://··· raring main"
state: present저장소 키
- apt_key:
id: AC40B2F7
url: "http://···"
state: presentGit 관련
- git:
repo: git://github.com/
dest: /srv/checkout
version: master
depth: 10
bare: yes참조: git 모듈
Git 설정
- git_config:
name: user.email
scope: global # local | system
value: [email protected]참조: git_config 모듈
사용자 관리
- user:
state: present # 상태: 존재
name: git # 사용자 이름
system: yes # 시스템 사용자
shell: /bin/sh # 로그인 셸
groups: admin # 그룹
comment: "Git Version Control" # 주석참조: user 모듈
서비스 관리
- service:
name: nginx # 서비스 이름
state: started # 상태: 시작됨
enabled: yes # 부팅 시 활성화참조: service 모듈
Shell 관련
shell 명령
- shell: apt-get install nginx -y추가 옵션
- shell: echo hello
args:
creates: /path/file # 파일이 존재하면 건너뜀
removes: /path/file # 파일이 존재하지 않으면 건너뜀
chdir: /path # 실행 전 이 디렉터리로 전환다중 행 명령 예시
- shell: |
echo "hello there"
echo "multiple lines"참조: shell 모듈
스크립트 실행
- script: /x/y/script.sh
args:
creates: /path/file # 파일이 존재하면 건너뜀
removes: /path/file # 파일이 존재하지 않으면 건너뜀
chdir: /path # 실행 전 이 디렉터리로 전환참조: script 모듈
파일 작업
파일 관리
- file:
path: /etc/dir
state: directory # 유형: directory|file|link|hard|touch|absent
# 선택적 매개변수:
owner: bin # 소유자
group: wheel # 그룹
mode: 0644 # 권한
recurse: yes # 재귀적 생성
force: yes # 소프트 링크 생성 강제참조: file 모듈
파일 복사
- copy:
src: /app/config/nginx.conf # 소스 파일
dest: /etc/nginx/nginx.conf # 대상 위치
# 선택적 매개변수:
owner: user # 소유자
group: user # 그룹
mode: 0644 # 권한
backup: yes # 존재 시 백업참조: copy 모듈
템플릿
- template:
src: config/redis.j2 # 템플릿 소스 파일
dest: /etc/redis.conf # 대상 위치
# 선택적 매개변수:
owner: user # 소유자
group: user # 그룹
mode: 0644 # 권한
backup: yes # 존재 시 백업참조: template 모듈
로컬 작업
로컬 실행
- name: 로컬에서 작업 실행
local_action: shell echo hello디버그 출력
- debug:
msg: "Hello {{ var }}"참조: debug 모듈