ansible

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ansible

ansible

Purpose

用途

Ansible is an open-source automation tool that configures IT infrastructure, deploys applications, and orchestrates tasks using agentless YAML playbooks. It ensures idempotent operations, meaning runs produce the same result regardless of initial state, and operates over SSH without installing agents on target hosts.
Ansible是一款开源自动化工具,它使用无代理的YAML剧本配置IT基础设施、部署应用并编排任务。它支持幂等操作,意味着无论初始状态如何,运行结果始终一致;并且通过SSH运行,无需在目标主机上安装代理。

When to Use

适用场景

Use Ansible for repeatable infrastructure tasks in DevOps pipelines, such as provisioning servers, managing configurations across fleets, or deploying apps in dynamic environments. Apply it when you need agentless automation, like updating software on remote machines, orchestrating multi-step workflows, or integrating with CI/CD tools, but avoid it for real-time monitoring where tools like Prometheus are better suited.
在DevOps流水线中,可使用Ansible处理重复性基础设施任务,例如配置服务器、管理跨集群的配置,或在动态环境中部署应用。当你需要无代理自动化时(比如更新远程机器上的软件、编排多步骤工作流,或与CI/CD工具集成),可以选择Ansible;但实时监控场景更适合Prometheus这类工具,此时应避免使用Ansible。

Key Capabilities

核心功能

  • Agentless Execution: Connects via SSH or WinRM; specify hosts in inventory files (e.g., /etc/ansible/hosts) with formats like [web:children] for grouping.
  • Idempotent Playbooks: Write YAML files that define tasks; e.g., a task to install a package only if absent.
  • Modules and Roles: Use built-in modules like
    apt
    for package management; organize code into roles for reusability, stored in directories like roles/webserver/tasks/main.yml.
  • Variables and Templates: Define vars in YAML (e.g., { "http_port": 80 }) and use Jinja2 templates for dynamic configs, like generating nginx.conf from a template.
  • Orchestration: Handle dependencies with plays that sequence tasks across hosts, ensuring ordered execution.
  • 无代理执行:通过SSH或WinRM连接;在清单文件(如/etc/ansible/hosts)中指定主机,支持[web:children]这类分组格式。
  • 幂等剧本:编写定义任务的YAML文件;例如,仅在软件包未安装时执行安装任务。
  • 模块与角色:使用内置模块(如
    apt
    进行包管理);将代码组织为可复用的角色,存储在roles/webserver/tasks/main.yml这类目录中。
  • 变量与模板:在YAML中定义变量(例如{ "http_port": 80 }),并使用Jinja2模板生成动态配置,比如从模板生成nginx.conf。
  • 编排能力:通过Play处理主机间的任务依赖,确保任务按顺序执行。

Usage Patterns

使用模式

To automate tasks, create a playbook (e.g., site.yml) defining plays with hosts, tasks, and vars. Run it using ansible-playbook command. For dynamic inventories, use scripts that output JSON, like pulling from AWS EC2. Structure projects with an inventory file, group_vars for host-specific vars, and roles for modular code. Always test playbooks with --check flag first to simulate changes without applying them.
要自动化任务,需创建剧本(如site.yml),定义包含主机、任务和变量的Play。使用ansible-playbook命令运行它。对于动态清单,可使用输出JSON的脚本,比如从AWS EC2拉取主机信息。项目结构应包含清单文件、用于主机特定变量的group_vars目录,以及用于模块化代码的roles目录。运行剧本前,务必先用--check标志测试,模拟变更而不实际应用。

Common Commands/API

常用命令/API

  • Run a Playbook:
    ansible-playbook site.yml --check --diff
    to simulate and show changes; add
    -l web
    to limit to a host group.
  • Ad Hoc Commands:
    ansible web -m ping
    to test connectivity; use
    -a "uptime"
    for arbitrary commands.
  • Manage Roles:
    ansible-galaxy install geerlingguy.apache
    to pull roles; build custom roles with
    ansible-galaxy init role_name
    .
  • Inventory and Vars: Set vars via
    -e "var1=value1"
    or environment vars like
    export ANSIBLE_HOST_KEY_CHECKING=False
    to bypass host key verification.
  • API Integration: Ansible's Python API via
    ansible_runner
    library; e.g., import ansible_runner and run
    interface.run(playbook='site.yml', extravars={'key': 'value'})
    to execute programmatically. For authentication, use env vars like
    $ANSIBLE_PRIVATE_KEY_FILE=/path/to/key.pem
    for SSH keys or
    $ANSIBLE_BECOME_PASS
    for sudo passwords.
  • 运行剧本
    ansible-playbook site.yml --check --diff
    用于模拟变更并显示差异;添加
    -l web
    可限制仅针对特定主机组。
  • 临时命令
    ansible web -m ping
    用于测试连通性;使用
    -a "uptime"
    执行任意命令。
  • 管理角色
    ansible-galaxy install geerlingguy.apache
    用于拉取角色;使用
    ansible-galaxy init role_name
    创建自定义角色。
  • 清单与变量:通过
    -e "var1=value1"
    或环境变量(如
    export ANSIBLE_HOST_KEY_CHECKING=False
    )绕过主机密钥验证来设置变量。
  • API集成:通过
    ansible_runner
    库使用Ansible的Python API;例如,导入ansible_runner并运行
    interface.run(playbook='site.yml', extravars={'key': 'value'})
    以编程方式执行任务。 认证方面,可使用环境变量,如
    $ANSIBLE_PRIVATE_KEY_FILE=/path/to/key.pem
    指定SSH密钥,或
    $ANSIBLE_BECOME_PASS
    设置sudo密码。

Integration Notes

集成说明

Integrate Ansible with CI/CD tools like Jenkins by triggering playbooks via scripts; e.g., in a Jenkinsfile:
sh 'ansible-playbook deploy.yml -e "env=prod"'
. For cloud providers, use dynamic inventories; e.g., configure AWS with
export AWS_ACCESS_KEY_ID=$AWS_KEY
and run
ansible-playbook -i ec2.py site.yml
. Combine with Terraform by running Ansible post-provisioning; ensure vars are passed via files or env vars. Use version control: store playbooks in Git and pull them in pipelines.
通过脚本触发剧本,将Ansible与Jenkins等CI/CD工具集成;例如,在Jenkinsfile中:
sh 'ansible-playbook deploy.yml -e "env=prod"'
。对于云提供商,使用动态清单;例如,配置AWS时设置
export AWS_ACCESS_KEY_ID=$AWS_KEY
,然后运行
ansible-playbook -i ec2.py site.yml
。与Terraform结合使用时,可在基础设施配置完成后运行Ansible;确保通过文件或环境变量传递变量。使用版本控制:将剧本存储在Git中,并在流水线中拉取使用。

Error Handling

错误处理

In playbooks, use blocks with rescue and always clauses; e.g.:
- block:
    - debug: msg="Task succeeded"
  rescue:
    - debug: msg="Error occurred"
  always:
    - debug: msg="Cleanup step"
Check command exit codes; e.g., in scripts:
ansible-playbook site.yml && echo "Success" || echo "Failed"
. For common issues, enable verbose output with
-vvv
to debug SSH connections or module failures. Use facts gathering to handle variable errors, and set
ignore_errors: yes
for non-critical tasks, but only when appropriate to avoid masking issues.
在剧本中,使用包含rescue和always子句的block;例如:
- block:
    - debug: msg="Task succeeded"
  rescue:
    - debug: msg="Error occurred"
  always:
    - debug: msg="Cleanup step"
检查命令退出码;例如,在脚本中:
ansible-playbook site.yml && echo "Success" || echo "Failed"
。对于常见问题,使用
-vvv
启用详细输出来调试SSH连接或模块故障。使用事实收集处理变量错误,并对非关键任务设置
ignore_errors: yes
,但仅在合适的场景下使用,避免掩盖问题。

Concrete Usage Examples

具体使用示例

  1. Deploy a Web Server on Ubuntu Hosts: Create a playbook (webserver.yml) with tasks to install Apache:
    - hosts: webservers
      tasks:
        - name: Install Apache
          apt:
            name: apache2
            state: present
    Run it with:
    ansible-playbook webserver.yml -i inventory.txt --become
    to elevate privileges.
  2. Configure Multiple Hosts for NTP: Write a playbook (ntp_config.yml) to sync time:
    - hosts: all
      tasks:
        - name: Install NTP
          yum:
            name: ntp
            state: latest
        - name: Start NTP service
          service:
            name: ntpd
            state: started
    Execute:
    ansible-playbook ntp_config.yml -l ntp_hosts
    to target specific groups.
  1. 在Ubuntu主机上部署Web服务器:创建包含安装Apache任务的剧本(webserver.yml):
    - hosts: webservers
      tasks:
        - name: Install Apache
          apt:
            name: apache2
            state: present
    使用以下命令运行:
    ansible-playbook webserver.yml -i inventory.txt --become
    以提升权限。
  2. 为多台主机配置NTP:编写用于同步时间的剧本(ntp_config.yml):
    - hosts: all
      tasks:
        - name: Install NTP
          yum:
            name: ntp
            state: latest
        - name: Start NTP service
          service:
            name: ntpd
            state: started
    执行:
    ansible-playbook ntp_config.yml -l ntp_hosts
    以针对特定主机组。

Graph Relationships

关联关系

  • Related to: terraform (for infrastructure as code), kubernetes (for container orchestration), jenkins (for CI/CD integration), all within the devops-sre cluster.
  • Dependencies: Often pairs with vault for secret management.
  • Conflicts: Avoid with tools like Puppet if agent-based management is preferred.
  • 相关工具:terraform(基础设施即代码)、kubernetes(容器编排)、jenkins(CI/CD集成),均属于devops-sre集群范畴。
  • 依赖项:通常与vault配合进行密钥管理。
  • 冲突项:如果偏好基于代理的管理工具(如Puppet),则应避免使用Ansible。