插件窝 干货文章 如何在Linux上配置自动化部署工具(如Ansible)

如何在Linux上配置自动化部署工具(如Ansible)

Ansible inventory 使用 Playbook 96    来源:    2025-04-15

在Linux上配置Ansible自动化部署工具指南

1. 安装Ansible

在基于RPM的系统(如CentOS/RHEL/Fedora)

sudo yum install epel-release
sudo yum install ansible

在基于Debian的系统(如Ubuntu/Debian)

sudo apt update
sudo apt install software-properties-common
sudo apt-add-repository --yes --update ppa:ansible/ansible
sudo apt install ansible

使用pip安装(适用于所有Linux发行版)

sudo pip install ansible

2. 基本配置

检查安装

ansible --version

创建Ansible目录结构

mkdir -p ~/ansible/{inventory,group_vars,host_vars,roles,playbooks}

配置主配置文件(可选)

编辑 /etc/ansible/ansible.cfg 或创建 ~/.ansible.cfg

[defaults]
inventory = ~/ansible/inventory/hosts
remote_user = root
private_key_file = ~/.ssh/id_rsa
host_key_checking = False

3. 设置Inventory文件

创建 ~/ansible/inventory/hosts 文件:

[web_servers]
web1.example.com ansible_host=192.168.1.10
web2.example.com ansible_host=192.168.1.11

[db_servers]
db1.example.com ansible_host=192.168.1.20

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

4. 测试连接

ansible all -m ping

5. 创建第一个Playbook

创建 ~/ansible/playbooks/first_playbook.yml

---
- name: My first playbook
  hosts: web_servers
  become: yes

  tasks:
    - name: Ensure Nginx is installed
      apt:
        name: nginx
        state: present
      when: ansible_os_family == "Debian"

    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started
        enabled: yes

6. 运行Playbook

ansible-playbook ~/ansible/playbooks/first_playbook.yml

7. 进阶配置

使用Vault加密敏感数据

ansible-vault create ~/ansible/group_vars/production/vault.yml

创建角色

cd ~/ansible/roles
ansible-galaxy init nginx

使用动态Inventory(如AWS)

sudo pip install boto3

8. 最佳实践

  1. 使用版本控制(如Git)管理Playbook
  2. 为不同环境(dev/stage/prod)创建单独的Inventory文件
  3. 使用角色组织复杂的部署逻辑
  4. 对敏感数据使用Ansible Vault加密
  5. 使用标签(tags)组织任务
  6. 定期更新Ansible版本

常见问题解决

问题1: SSH连接失败 - 确保SSH密钥已正确配置 - 检查目标主机的SSH服务是否运行 - 验证防火墙设置

问题2: Python解释器问题 - 在Inventory文件中指定正确的Python路径 - 确保目标主机安装了Python

问题3: 权限问题 - 使用become: yes提升权限 - 配置正确的sudo权限

通过以上步骤,您应该能够在Linux系统上成功配置和使用Ansible进行自动化部署。