ansible
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseansible
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 for package management; organize code into roles for reusability, stored in directories like roles/webserver/tasks/main.yml.
apt - 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文件;例如,仅在软件包未安装时执行安装任务。
- 模块与角色:使用内置模块(如进行包管理);将代码组织为可复用的角色,存储在roles/webserver/tasks/main.yml这类目录中。
apt - 变量与模板:在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: to simulate and show changes; add
ansible-playbook site.yml --check --diffto limit to a host group.-l web - Ad Hoc Commands: to test connectivity; use
ansible web -m pingfor arbitrary commands.-a "uptime" - Manage Roles: to pull roles; build custom roles with
ansible-galaxy install geerlingguy.apache.ansible-galaxy init role_name - Inventory and Vars: Set vars via or environment vars like
-e "var1=value1"to bypass host key verification.export ANSIBLE_HOST_KEY_CHECKING=False - API Integration: Ansible's Python API via library; e.g., import ansible_runner and run
ansible_runnerto execute programmatically. For authentication, use env vars likeinterface.run(playbook='site.yml', extravars={'key': 'value'})for SSH keys or$ANSIBLE_PRIVATE_KEY_FILE=/path/to/key.pemfor sudo passwords.$ANSIBLE_BECOME_PASS
- 运行剧本:用于模拟变更并显示差异;添加
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的Python API;例如,导入ansible_runner并运行
ansible_runner以编程方式执行任务。 认证方面,可使用环境变量,如interface.run(playbook='site.yml', extravars={'key': 'value'})指定SSH密钥,或$ANSIBLE_PRIVATE_KEY_FILE=/path/to/key.pem设置sudo密码。$ANSIBLE_BECOME_PASS
Integration Notes
集成说明
Integrate Ansible with CI/CD tools like Jenkins by triggering playbooks via scripts; e.g., in a Jenkinsfile: . For cloud providers, use dynamic inventories; e.g., configure AWS with and run . 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.
sh 'ansible-playbook deploy.yml -e "env=prod"'export AWS_ACCESS_KEY_ID=$AWS_KEYansible-playbook -i ec2.py site.yml通过脚本触发剧本,将Ansible与Jenkins等CI/CD工具集成;例如,在Jenkinsfile中:。对于云提供商,使用动态清单;例如,配置AWS时设置,然后运行。与Terraform结合使用时,可在基础设施配置完成后运行Ansible;确保通过文件或环境变量传递变量。使用版本控制:将剧本存储在Git中,并在流水线中拉取使用。
sh 'ansible-playbook deploy.yml -e "env=prod"'export AWS_ACCESS_KEY_ID=$AWS_KEYansible-playbook -i ec2.py site.ymlError 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: . For common issues, enable verbose output with to debug SSH connections or module failures. Use facts gathering to handle variable errors, and set for non-critical tasks, but only when appropriate to avoid masking issues.
ansible-playbook site.yml && echo "Success" || echo "Failed"-vvvignore_errors: yes在剧本中,使用包含rescue和always子句的block;例如:
- block:
- debug: msg="Task succeeded"
rescue:
- debug: msg="Error occurred"
always:
- debug: msg="Cleanup step"检查命令退出码;例如,在脚本中:。对于常见问题,使用启用详细输出来调试SSH连接或模块故障。使用事实收集处理变量错误,并对非关键任务设置,但仅在合适的场景下使用,避免掩盖问题。
ansible-playbook site.yml && echo "Success" || echo "Failed"-vvvignore_errors: yesConcrete Usage Examples
具体使用示例
-
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: presentRun it with:to elevate privileges.ansible-playbook webserver.yml -i inventory.txt --become -
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: startedExecute:to target specific groups.ansible-playbook ntp_config.yml -l ntp_hosts
-
在Ubuntu主机上部署Web服务器:创建包含安装Apache任务的剧本(webserver.yml):
- hosts: webservers tasks: - name: Install Apache apt: name: apache2 state: present使用以下命令运行:以提升权限。ansible-playbook webserver.yml -i inventory.txt --become -
为多台主机配置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。