コンテンツにスキップ

Ansible

Comprehensive ansible commands and workflows for system administration across all platforms.

Basic Commands

Command Description
ansible --version Show ansible version
ansible --help Display help information
ansible init Initialize ansible in current directory
ansible status Check current status
ansible list List available options
ansible info Display system information
ansible config Show configuration settings
ansible update Update to latest version
ansible start Start ansible service
ansible stop Stop ansible service
ansible restart Restart ansible service
ansible reload Reload configuration

Installation

Linux/Ubuntu

# Package manager installation
sudo apt update
sudo apt install ansible

# Alternative installation
wget https://github.com/example/ansible/releases/latest/download/ansible-linux
chmod +x ansible-linux
sudo mv ansible-linux /usr/local/bin/ansible

# Build from source
git clone https://github.com/example/ansible.git
cd ansible
make && sudo make install

macOS

# Homebrew installation
brew install ansible

# MacPorts installation
sudo port install ansible

# Manual installation
curl -L -o ansible https://github.com/example/ansible/releases/latest/download/ansible-macos
chmod +x ansible
sudo mv ansible /usr/local/bin/

Windows

# Chocolatey installation
choco install ansible

# Scoop installation
scoop install ansible

# Winget installation
winget install ansible

# Manual installation
# Download from https://github.com/example/ansible/releases
# Extract and add to PATH

Configuration

Command Description
ansible config show Display current configuration
ansible config list List all configuration options
ansible config set <key> <value> Set configuration value
ansible config get <key> Get configuration value
ansible config unset <key> Remove configuration value
ansible config reset Reset to default configuration
ansible config validate Validate configuration file
ansible config export Export configuration to file

Advanced Operations

File Operations

# Create new file/resource
ansible create <name>

# Read file/resource
ansible read <name>

# Update existing file/resource
ansible update <name>

# Delete file/resource
ansible delete <name>

# Copy file/resource
ansible copy <source> <destination>

# Move file/resource
ansible move <source> <destination>

# List all files/resources
ansible list --all

# Search for files/resources
ansible search <pattern>

Network Operations

# Connect to remote host
ansible connect <host>:<port>

# Listen on specific port
ansible listen --port <port>

# Send data to target
ansible send --target <host> --data "<data>"

# Receive data from source
ansible receive --source <host>

# Test connectivity
ansible ping <host>

# Scan network range
ansible scan <network>

# Monitor network traffic
ansible monitor --interface <interface>

# Proxy connections
ansible proxy --listen <port> --target <host>:<port>

Process Management

# Start background process
ansible start --daemon

# Stop running process
ansible stop --force

# Restart with new configuration
ansible restart --config <file>

# Check process status
ansible status --verbose

# Monitor process performance
ansible monitor --metrics

# Kill all processes
ansible killall

# Show running processes
ansible ps

# Manage process priority
ansible priority --pid <pid> --level <level>

Security Features

Authentication

# Login with username/password
ansible login --user <username>

# Login with API key
ansible login --api-key <key>

# Login with certificate
ansible login --cert <cert_file>

# Logout current session
ansible logout

# Change password
ansible passwd

# Generate new API key
ansible generate-key --name <key_name>

# List active sessions
ansible sessions

# Revoke session
ansible revoke --session <session_id>

Encryption

# Encrypt file
ansible encrypt --input <file> --output <encrypted_file>

# Decrypt file
ansible decrypt --input <encrypted_file> --output <file>

# Generate encryption key
ansible keygen --type <type> --size <size>

# Sign file
ansible sign --input <file> --key <private_key>

# Verify signature
ansible verify --input <file> --signature <sig_file>

# Hash file
ansible hash --algorithm <algo> --input <file>

# Generate certificate
ansible cert generate --name <name> --days <days>

# Verify certificate
ansible cert verify --cert <cert_file>

Monitoring and Logging

System Monitoring

# Monitor system resources
ansible monitor --system

# Monitor specific process
ansible monitor --pid <pid>

# Monitor network activity
ansible monitor --network

# Monitor file changes
ansible monitor --files <directory>

# Real-time monitoring
ansible monitor --real-time --interval 1

# Generate monitoring report
ansible report --type monitoring --output <file>

# Set monitoring alerts
ansible alert --threshold <value> --action <action>

# View monitoring history
ansible history --type monitoring

Logging

# View logs
ansible logs

# View logs with filter
ansible logs --filter <pattern>

# Follow logs in real-time
ansible logs --follow

# Set log level
ansible logs --level <level>

# Rotate logs
ansible logs --rotate

# Export logs
ansible logs --export <file>

# Clear logs
ansible logs --clear

# Archive logs
ansible logs --archive <archive_file>

Troubleshooting

Common Issues

Issue: Command not found

# Check if ansible is installed
which ansible
ansible --version

# Check PATH variable
echo $PATH

# Reinstall if necessary
sudo apt reinstall ansible
# or
brew reinstall ansible

Issue: Permission denied

# Run with elevated privileges
sudo ansible <command>

# Check file permissions
ls -la $(which ansible)

# Fix permissions
chmod +x /usr/local/bin/ansible

# Check ownership
sudo chown $USER:$USER /usr/local/bin/ansible

Issue: Configuration errors

# Validate configuration
ansible config validate

# Reset to default configuration
ansible config reset

# Check configuration file location
ansible config show --file

# Backup current configuration
ansible config export > backup.conf

# Restore from backup
ansible config import backup.conf

Issue: Service not starting

# Check service status
ansible status --detailed

# Check system logs
journalctl -u ansible

# Start in debug mode
ansible start --debug

# Check port availability
netstat -tulpn|grep <port>

# Kill conflicting processes
ansible killall --force

Debug Commands

Command Description
ansible --debug Enable debug output
ansible --verbose Enable verbose logging
ansible --trace Enable trace logging
ansible test Run built-in tests
ansible doctor Run system health check
ansible diagnose Generate diagnostic report
ansible benchmark Run performance benchmarks
ansible validate Validate installation and configuration

Performance Optimization

Resource Management

# Set memory limit
ansible --max-memory 1G <command>

# Set CPU limit
ansible --max-cpu 2 <command>

# Enable caching
ansible --cache-enabled <command>

# Set cache size
ansible --cache-size 100M <command>

# Clear cache
ansible cache clear

# Show cache statistics
ansible cache stats

# Optimize performance
ansible optimize --profile <profile>

# Show performance metrics
ansible metrics

Parallel Processing

# Enable parallel processing
ansible --parallel <command>

# Set number of workers
ansible --workers 4 <command>

# Process in batches
ansible --batch-size 100 <command>

# Queue management
ansible queue add <item>
ansible queue process
ansible queue status
ansible queue clear

Integration

Scripting

#!/bin/bash
# Example script using ansible

set -euo pipefail

# Configuration
CONFIG_FILE="config.yaml"
LOG_FILE="ansible.log"

# Check if ansible is available
if ! command -v ansible &> /dev/null; then
    echo "Error: ansible is not installed" >&2
    exit 1
fi

# Function to log messages
log() \\\\{
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"|tee -a "$LOG_FILE"
\\\\}

# Main operation
main() \\\\{
    log "Starting ansible operation"

    if ansible --config "$CONFIG_FILE" run; then
        log "Operation completed successfully"
        exit 0
    else
        log "Operation failed with exit code $?"
        exit 1
    fi
\\\\}

# Cleanup function
cleanup() \\\\{
    log "Cleaning up"
    ansible cleanup
\\\\}

# Set trap for cleanup
trap cleanup EXIT

# Run main function
main "$@"

API Integration

#!/usr/bin/env python3
"""
Python wrapper for the tool
"""

import subprocess
import json
import logging
from pathlib import Path
from typing import Dict, List, Optional

class ToolWrapper:
    def __init__(self, config_file: Optional[str] = None):
        self.config_file = config_file
        self.logger = logging.getLogger(__name__)

    def run_command(self, args: List[str]) -> Dict:
        """Run command and return parsed output"""
        cmd = ['tool_name']

        if self.config_file:
            cmd.extend(['--config', self.config_file])

        cmd.extend(args)

        try:
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                check=True
            )
            return \\\\{'stdout': result.stdout, 'stderr': result.stderr\\\\}
        except subprocess.CalledProcessError as e:
            self.logger.error(f"Command failed: \\\\{e\\\\}")
            raise

    def status(self) -> Dict:
        """Get current status"""
        return self.run_command(['status'])

    def start(self) -> Dict:
        """Start service"""
        return self.run_command(['start'])

    def stop(self) -> Dict:
        """Stop service"""
        return self.run_command(['stop'])

# Example usage
if __name__ == "__main__":
    wrapper = ToolWrapper()
    status = wrapper.status()
    print(json.dumps(status, indent=2))

Environment Variables

Variable Description Default
ANSIBLE_CONFIG Configuration file path ~/.ansible/config.yaml
ANSIBLE_HOME Home directory ~/.ansible
ANSIBLE_LOG_LEVEL Logging level INFO
ANSIBLE_LOG_FILE Log file path ~/.ansible/logs/ansible.log
ANSIBLE_CACHE_DIR Cache directory ~/.ansible/cache
ANSIBLE_DATA_DIR Data directory ~/.ansible/data
ANSIBLE_TIMEOUT Default timeout 30s
ANSIBLE_MAX_WORKERS Maximum workers 4

Configuration File

# ~/.ansible/config.yaml
version: "1.0"

# General settings
settings:
  debug: false
  verbose: false
  log_level: "INFO"
  log_file: "~/.ansible/logs/ansible.log"
  timeout: 30
  max_workers: 4

# Network configuration
network:
  host: "localhost"
  port: 8080
  ssl: true
  timeout: 30
  retries: 3

# Security settings
security:
  auth_required: true
  api_key: ""
  encryption: "AES256"
  verify_ssl: true

# Performance settings
performance:
  cache_enabled: true
  cache_size: "100M"
  cache_dir: "~/.ansible/cache"
  max_memory: "1G"

# Monitoring settings
monitoring:
  enabled: true
  interval: 60
  metrics_enabled: true
  alerts_enabled: true

Examples

Basic Workflow

# 1. Initialize ansible
ansible init

# 2. Configure basic settings
ansible config set host example.com
ansible config set port 8080

# 3. Start service
ansible start

# 4. Check status
ansible status

# 5. Perform operations
ansible run --target example.com

# 6. View results
ansible results

# 7. Stop service
ansible stop

Advanced Workflow

# Comprehensive operation with monitoring
ansible run \
  --config production.yaml \
  --parallel \
  --workers 8 \
  --verbose \
  --timeout 300 \
  --output json \
  --log-file operation.log

# Monitor in real-time
ansible monitor --real-time --interval 5

# Generate report
ansible report --type comprehensive --output report.html

Automation Example

#!/bin/bash
# Automated ansible workflow

# Configuration
TARGETS_FILE="targets.txt"
RESULTS_DIR="results/$(date +%Y-%m-%d)"
CONFIG_FILE="automation.yaml"

# Create results directory
mkdir -p "$RESULTS_DIR"

# Process each target
while IFS= read -r target; do
    echo "Processing $target..."

    ansible \
        --config "$CONFIG_FILE" \
        --output json \
        --output-file "$RESULTS_DIR/$\\\\{target\\\\}.json" \
        run "$target"

done < "$TARGETS_FILE"

# Generate summary report
ansible report summary \
    --input "$RESULTS_DIR/*.json" \
    --output "$RESULTS_DIR/summary.html"

Best Practices

Security

  • Always verify checksums when downloading binaries
  • Use strong authentication methods (API keys, certificates)
  • Regularly update to the latest version
  • Follow principle of least privilege
  • Enable audit logging for compliance
  • Use encrypted connections when possible
  • Validate all inputs and configurations
  • Implement proper access controls

Performance

  • Use appropriate resource limits for your environment
  • Monitor system performance regularly
  • Optimize configuration for your use case
  • Use parallel processing when beneficial
  • Implement proper caching strategies
  • Regular maintenance and cleanup
  • Profile performance bottlenecks
  • Use efficient algorithms and data structures

Operational

  • Maintain comprehensive documentation
  • Implement proper backup strategies
  • Use version control for configurations
  • Monitor and alert on critical metrics
  • Implement proper error handling
  • Use automation for repetitive tasks
  • Regular security audits and updates
  • Plan for disaster recovery

Development

  • Follow coding standards and conventions
  • Write comprehensive tests
  • Use continuous integration/deployment
  • Implement proper logging and monitoring
  • Document APIs and interfaces
  • Use version control effectively
  • Review code regularly
  • Maintain backward compatibility

Resources

Official Documentation

Community Resources

Learning Resources

  • Git - Complementary functionality
  • Docker - Alternative solution
  • Kubernetes - Integration partner

Last updated: 2025-07-06|Edit on GitHub