Ansible Commands Reference & Best Practices

Pavel 08.12.2025 18:44 4 просмотров

Course: Ansible for Beginners (ADV-IT)
Language: Russian
Updated: November 26, 2025


1. Installation Commands

# Ubuntu/Debian
sudo apt update && sudo apt install -y ansible

# CentOS/RHEL
sudo yum install -y epel-release && sudo yum install -y ansible

# macOS
brew install ansible

# Python pip (all platforms)
pip3 install ansible

# Verify installation
ansible --version

2. Ad-Hoc Commands

Basic Commands

# Syntax
ansible <pattern> -i <inventory> -m <module> -a '<arguments>'

# Ping all hosts
ansible all -i inventory.ini -m ping

# Run command
ansible webservers -i inventory.ini -m shell -a 'whoami'

# Get facts
ansible all -i inventory.ini -m setup
ansible all -i inventory.ini -m setup -a "filter=ansible_os_family"

Common Modules

# File operations
ansible all -i inventory.ini -m copy -a 'src=file.txt dest=/tmp/'
ansible all -i inventory.ini -m file -a 'path=/tmp/test state=directory'
ansible all -i inventory.ini -m file -a 'path=/tmp/test state=absent'

# Package management (Debian/Ubuntu)
ansible all -i inventory.ini -m apt -a 'name=nginx state=present'
ansible all -i inventory.ini -m apt -a 'update_cache=yes'

# Service management
ansible all -i inventory.ini -m service -a 'name=nginx state=started'
ansible all -i inventory.ini -m service -a 'name=nginx state=restarted'

# User management
ansible all -i inventory.ini -m user -a 'name=john groups=sudo'
ansible all -i inventory.ini -m user -a 'name=john state=absent'

# Shell commands
ansible all -i inventory.ini -m shell -a 'df -h'
ansible all -i inventory.ini -m shell -a 'ps aux | grep nginx'

Useful Flags

# Dry run (check mode)
ansible-playbook playbook.yml --check

# Verbose output
ansible-playbook playbook.yml -v      # verbose
ansible-playbook playbook.yml -vv     # more verbose
ansible-playbook playbook.yml -vvv    # very verbose

# Use sudo
ansible all -i inventory.ini -b -m shell -a 'whoami'

# Parallel forks
ansible all -i inventory.ini -f 20 -m ping

# Specify user
ansible all -i inventory.ini -u ubuntu -m ping

# Specify SSH key
ansible all -i inventory.ini --private-key=/path/to/key -m ping

# Limit to specific hosts
ansible-playbook playbook.yml -l webservers
ansible-playbook playbook.yml -l web1,web2

# Extra variables
ansible-playbook playbook.yml -e "var1=value1 var2=value2"
ansible-playbook playbook.yml -e "@vars.json"

# Tags
ansible-playbook playbook.yml --tags "install"
ansible-playbook playbook.yml --skip-tags "restart"

# Start from specific task
ansible-playbook playbook.yml --start-at-task "Install nginx"

3. Playbook Commands

# Run playbook
ansible-playbook playbook.yml -i inventory.ini

# Dry run
ansible-playbook playbook.yml -i inventory.ini --check

# Auto-approve (no prompt)
ansible-playbook playbook.yml -i inventory.ini -y

# Show differences
ansible-playbook playbook.yml -i inventory.ini --diff

# Verbose
ansible-playbook playbook.yml -i inventory.ini -v

# Limit to group
ansible-playbook playbook.yml -i inventory.ini -l webservers

# Limit to host
ansible-playbook playbook.yml -i inventory.ini -l web1

# Tag specific tasks
ansible-playbook playbook.yml -i inventory.ini --tags "install,configure"

# Skip tags
ansible-playbook playbook.yml -i inventory.ini --skip-tags "restart"

# Start from task
ansible-playbook playbook.yml -i inventory.ini --start-at-task "Configure"

# List all tasks
ansible-playbook playbook.yml -i inventory.ini --list-tasks

# List all hosts
ansible-playbook playbook.yml -i inventory.ini --list-hosts

# Check syntax
ansible-playbook playbook.yml --syntax-check

# Extra variables
ansible-playbook playbook.yml -i inventory.ini -e "env=prod version=1.2"

# Load variables from file
ansible-playbook playbook.yml -i inventory.ini -e "@vars.yml"

# Parallel execution
ansible-playbook playbook.yml -i inventory.ini -f 10

4. Inventory Commands

# List all hosts
ansible all -i inventory.ini --list-hosts

# List hosts in group
ansible webservers -i inventory.ini --list-hosts

# Show host variables
ansible web1 -i inventory.ini -m debug -a 'var=hostvars[inventory_hostname]'

# Show group variables
ansible webservers -i inventory.ini -m debug -a 'var=group_vars'

# Validate inventory syntax
ansible-inventory -i inventory.ini --list

# Get inventory in JSON format
ansible-inventory -i inventory.ini --list -y

5. Vault Commands

# Create encrypted file
ansible-vault create secrets.yml

# Edit encrypted file
ansible-vault edit secrets.yml

# View encrypted file
ansible-vault view secrets.yml

# Encrypt existing file
ansible-vault encrypt credentials.yml

# Decrypt file
ansible-vault decrypt secrets.yml

# Change vault password
ansible-vault rekey secrets.yml

# Run playbook with vault
ansible-playbook playbook.yml --ask-vault-pass
ansible-playbook playbook.yml --vault-password-file=.vault_pass

# Encrypt string
ansible-vault encrypt_string 'secret_value'

# Encrypt multiple files
ansible-vault encrypt file1.yml file2.yml file3.yml

6. Debugging Commands

# Set log file
export ANSIBLE_LOG_PATH=ansible.log

# Enable debug logging
export ANSIBLE_DEBUG=1

# Print all facts
ansible all -i inventory.ini -m setup | less

# Print specific fact
ansible all -i inventory.ini -m debug -a 'msg={{ ansible_os_family }}'

# Check registered variable
ansible-playbook playbook.yml -i inventory.ini -v | grep -A 10 'register'

# See what changed
ansible-playbook playbook.yml -i inventory.ini --diff

# Check syntax
ansible-playbook playbook.yml --syntax-check

7. Galaxy Commands (Roles)

# Initialize role structure
ansible-galaxy init my_role

# Install role from Galaxy
ansible-galaxy install username.role_name

# Install from requirements
ansible-galaxy install -r requirements.yml

# List installed roles
ansible-galaxy list

# Search for roles
ansible-galaxy search webserver

# Create role archive
ansible-galaxy import username role_name

8. Configuration Files

ansible.cfg

[defaults]
inventory = /etc/ansible/hosts
remote_user = ansible
host_key_checking = False
forks = 10
timeout = 10
log_path = /var/log/ansible.log
roles_path = ./roles

[privilege_escalation]
become = True
become_method = sudo
become_user = root

inventory.ini

[webservers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11

[databases]
db1 ansible_host=192.168.1.20

[all:vars]
ansible_user=ansible
ansible_python_interpreter=/usr/bin/python3

requirements.yml

---
roles:
  - username.web_server
  - username.database
  - community.general
  - ansible.netcommon

collections:
  - name: community.general
    version: ">=3.0.0"

9. Best Practices

# ✅ GOOD - Clear and well-structured
---
- name: Deploy web application
  hosts: webservers
  become: yes

  vars:
    app_version: "1.0"
    app_port: 8080

  pre_tasks:
    - name: Update package cache
      apt:
        update_cache: yes

  tasks:
    - name: Install dependencies
      apt:
        name: "{{ item }}"
        state: present
      loop:
        - nginx
        - curl
        - git

    - name: Copy configuration
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx

    - name: Start service
      service:
        name: nginx
        state: started
        enabled: yes

  post_tasks:
    - name: Verify service
      uri:
        url: "http://localhost:{{ app_port }}"
        status_code: 200

  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted

# ❌ BAD - Unclear and hard to maintain
---
- hosts: all
  tasks:
    - shell: apt-get update && apt-get install -y nginx && systemctl start nginx
    - copy: src=/local/nginx.conf dest=/etc/nginx/nginx.conf
    - shell: systemctl restart nginx

10. Project Structure

ansible-project/
├── ansible.cfg
├── inventory/
   ├── production.ini
   ├── staging.ini
   └── development.ini
├── playbooks/
   ├── site.yml
   ├── deploy.yml
   └── monitoring.yml
├── roles/
   ├── webserver/
   ├── database/
   └── monitoring/
├── group_vars/
   ├── all.yml
   ├── webservers.yml
   └── databases.yml
├── host_vars/
   └── web1.yml
├── files/
├── templates/
├── vars/
└── README.md

11. Common Playbook Patterns

Conditional Execution

- name: Task for Ubuntu only
  debug:
    msg: "Ubuntu system"
  when: ansible_os_family == "Debian"

- name: Task for specific host
  debug:
    msg: "Special task"
  when: inventory_hostname == "web1"

- name: Task if variable defined
  debug:
    msg: "Variable is defined"
  when: my_var is defined

Loops

- name: Install packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - curl
    - git

- name: Create users
  user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
  loop:
    - {name: 'john', groups: 'sudo'}
    - {name: 'jane', groups: 'wheel'}

Error Handling

- name: Run command with retry
  shell: curl http://api.example.com
  register: result
  until: result is succeeded
  retries: 3
  delay: 5

- name: Ignore errors
  shell: some_command
  ignore_errors: yes

- name: Fail with custom message
  fail:
    msg: "Critical error!"
  when: critical_condition

12. Useful Filters

tasks:
  - name: Use filters
    debug:
      msg: |
        Upper: {{ 'hello' | upper }}
        Lower: {{ 'HELLO' | lower }}
        Capitalize: {{ 'hello world' | capitalize }}
        Replace: {{ 'hello world' | replace('world', 'ansible') }}
        Join: {{ [1, 2, 3] | join(',') }}
        Unique: {{ [1, 2, 2, 3] | unique }}
        Sort: {{ [3, 1, 2] | sort }}
        Length: {{ 'hello' | length }}
        Default: {{ undefined_var | default('default value') }}

13. Quick Reference

Command Purpose
ansible all -m ping Test connectivity
ansible-playbook play.yml Run playbook
ansible-playbook play.yml --check Dry run
ansible all -m setup Gather facts
ansible-vault create secrets.yml Create vault file
ansible-galaxy init role_name Create role
ansible-inventory --list Show inventory
ansible-playbook play.yml --syntax-check Check syntax
ansible-playbook play.yml -l webservers Limit to group
ansible-playbook play.yml --tags install Run specific tags

14. Troubleshooting

# Check Ansible version
ansible --version

# Verify inventory
ansible-inventory -i inventory.ini --list

# Test connectivity
ansible all -i inventory.ini -m ping -vvv

# Check syntax
ansible-playbook playbook.yml --syntax-check

# Dry run
ansible-playbook playbook.yml --check --diff

# See registered variables
ansible-playbook playbook.yml -v | grep -A 5 "register"

# Enable debug mode
export ANSIBLE_DEBUG=1

# Check host keys
ssh-keyscan -H <hostname> >> ~/.ssh/known_hosts

For more help: ansible --help or visit https://docs.ansible.com/

Комментарии (0)

Для добавления комментария необходимо войти в аккаунт

Войти / Зарегистрироваться