第三章:快速入门

通过实际案例快速掌握 Ansible 的基本使用方法。

最后更新: 2024-01-17
页面目录

Ansible 快速入门

本章通过实际案例,帮助你快速掌握 Ansible 的基本使用方法。

环境准备

创建测试环境

# 创建项目目录
mkdir -p ~/ansible-quickstart
cd ~/ansible-quickstart

# 创建目录结构
mkdir -p inventory group_vars host_vars roles

创建 Inventory 文件

# inventory/hosts
[local]
localhost ansible_connection=local

[webserver]
192.168.1.10 ansible_user=root ansible_ssh_pass=password
192.168.1.11 ansible_user=root ansible_ssh_pass=password

[webservers:children]
local
webserver

Ad-Hoc 命令

Ad-Hoc 命令是 Ansible 最简单的使用方式,适合执行一次性任务。

基础语法

ansible <主机_pattern> -m <模块> -a <参数>

常用 Ad-Hoc 命令

1. Ping 主机

# Ping 所有主机
ansible all -m ping

# Ping 本地主机
ansible localhost -m ping

# Ping 指定组
ansible webservers -m ping

2. 执行 Shell 命令

# 查看系统信息
ansible all -m command -a "uname -a"

# 查看磁盘使用
ansible all -m command -a "df -h"

# 查看内存使用
ansible all -m command -a "free -m"

# 查看运行时间
ansible all -m command -a "uptime"

# 查看网络配置
ansible all -m command -a "ip addr show"

3. 复制文件

# 复制单个文件
ansible all -m copy -a "src=./test.txt dest=/tmp/test.txt"

# 复制并设置权限
ansible all -m copy -a "src=./test.sh dest=/tmp/test.sh mode=0755"

# 复制并设置所有者
ansible all -m copy -a "src=./config.conf dest=/etc/myapp/ owner=myapp group=myapp mode=0640"

4. 包管理

# 安装软件包(Debian/Ubuntu)
ansible all -m apt -a "name=vim state=present" --become

# 安装软件包(RHEL/CentOS)
ansible all -m yum -a "name=vim state=present" --become

# 删除软件包
ansible all -m apt -a "name=vim state=absent" --become

# 更新软件包
ansible all -m apt -a "name=* state=latest" --become

5. 服务管理

# 启动服务
ansible all -m service -a "name=nginx state=started" --become

# 停止服务
ansible all -m service -a "name=nginx state=stopped" --become

# 重启服务
ansible all -m service -a "name=nginx state=restarted" --become

# 启用服务开机自启
ansible all -m service -a "name=nginx enabled=yes" --become

6. 用户管理

# 创建用户
ansible all -m user -a "name=testuser comment='Test User' shell=/bin/bash" --become

# 删除用户
ansible all -m user -a "name=testuser state=absent remove=yes" --become

# 修改用户密码
ansible all -m user -a "name=testuser password={{ 'password123' | password_hash('sha512') }}" --become

7. 文件/目录操作

# 创建目录
ansible all -m file -a "path=/tmp/testdir state=directory mode=0755" --become

# 创建符号链接
ansible all -m file -a "src=/etc/resolv.conf dest=/tmp/resolv.conf state=link" --become

# 删除文件/目录
ansible all -m file -a "path=/tmp/testdir state=absent"

8. 收集 Facts

# 收集所有主机的 Facts
ansible all -m setup

# 过滤 Facts
ansible all -m setup -a "filter=ansible_distribution*"

# 查看内存信息
ansible all -m setup -a "filter=ansible_memory_mb"

# 查看网络信息
ansible all -m setup -a "filter=ansible_interfaces"

第一个 Playbook

Playbook 是 Ansible 的核心,用于定义复杂的自动化任务。

创建第一个 Playbook

# hello.yml
---
- name: My First Playbook
  hosts: localhost
  connection: local
  become: yes

  tasks:
    - name: Install Vim
      apt:
        name: vim
        state: present
        update_cache: yes

    - name: Create a test file
      copy:
        content: "Hello from Ansible!"
        dest: /tmp/ansible_hello.txt
        mode: '0644'

    - name: Display message
      debug:
        msg: "Playbook completed successfully!"

运行 Playbook

# 运行 Playbook
ansible-playbook hello.yml

# 运行并显示详细输出
ansible-playbook hello.yml -v

# 更详细的输出(-vvvv 用于调试)
ansible-playbook hello.yml -vvv

Playbook 执行输出

PLAY [My First Playbook] *****************************************************

TASK [Gathering Facts] ********************************************************
ok: [localhost]

TASK [Install Vim] ************************************************************
changed: [localhost]

TASK [Create a test file] ****************************************************
changed: [localhost]

TASK [Display message] *******************************************************
ok: [localhost] => {
    "msg": "Playbook completed successfully!"
}

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=2    unreachable=0    failed=0

实战:配置 Web 服务器

让我们创建一个完整的 Playbook 来配置 Nginx Web 服务器。

Playbook 结构

# nginx.yml
---
- name: Configure Nginx Web Server
  hosts: webservers
  become: yes
  vars:
    nginx_port: 80
    server_name: example.com
    document_root: /var/www/html

  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
      when: ansible_os_family == "Debian"

    - name: Install Nginx
      apt:
        name: nginx
        state: present

    - name: Create document root
      file:
        path: "{{ document_root }}"
        state: directory
        owner: www-data
        group: www-data
        mode: '0755'

    - name: Create index.html
      copy:
        content: |
          <!DOCTYPE html>
          <html>
          <head>
            <title>Welcome to Ansible</title>
          </head>
          <body>
            <h1>Hello from Ansible!</h1>
            <p>Server: {{ ansible_hostname }}</p>
          </body>
          </html>
        dest: "{{ document_root }}/index.html"
        owner: www-data
        group: www-data
        mode: '0644'

    - name: Configure Nginx
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/sites-available/default
      notify: Reload Nginx

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

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

Nginx 配置模板

# nginx.conf.j2
server {
    listen {{ nginx_port }};
    listen [::]:{{ nginx_port }};

    server_name {{ server_name }};

    root {{ document_root }};
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    access_log /var/log/nginx/{{ server_name }}_access.log;
    error_log /var/log/nginx/{{ server_name }}_error.log;
}

常用命令速查表

Ansible 命令

# Ping 所有主机
ansible all -m ping

# 执行命令
ansible all -m command -a "whoami"

# 查看文件内容
ansible all -m fetch -a "src=/etc/hosts dest=/tmp/hosts flat=yes"

# 查看模块帮助
ansible-doc <module_name>

# 列出可用模块
ansible-doc -l

Ansible-Playbook 命令

# 运行 Playbook
ansible-playbook site.yml

# 检查模式(不实际执行)
ansible-playbook site.yml --check

# 列出将要执行的任务
ansible-playbook site.yml --list-tasks

# 列出所有主机
ansible-playbook site.yml --list-hosts

# 指定 inventory
ansible-playbook site.yml -i inventory/production

# 指定变量
ansible-playbook site.yml -e "var=value"

# 跳过标签
ansible-playbook site.yml --skip-tags "config"

# 仅执行带标签的任务
ansible-playbook site.yml --tags "deploy"

Ansible 执行流程

┌─────────────────────────────────────────────────────────────────┐
│                    Ansible Playbook 执行流程                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. 加载 Playbook                                                │
│         ↓                                                        │
│  2. 加载 Inventory 和变量                                         │
│         ↓                                                        │
│  3. 连接主机(SSH)                                               │
│         ↓                                                        │
│  4. 执行 Pre-Tasks                                               │
│         ↓                                                        │
│  5. 执行 Handlers(触发)                                         │
│         ↓                                                        │
│  6. 收集 Facts                                                   │
│         ↓                                                        │
│  7. 执行 Tasks                                                   │
│         ↓                                                        │
│  8. 执行 Post-Tasks                                              │
│         ↓                                                        │
│  9. 执行 Handlers(最终)                                         │
│         ↓                                                        │
│  10. 报告结果                                                    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

常见问题排查

连接问题

# 测试 SSH 连接
ssh -v user@hostname

# 调试 Ansible 连接
ansible all -m ping -vvvv

# 检查 SSH 密钥权限
chmod 600 ~/.ssh/id_rsa

权限问题

# 使用 sudo
ansible all -m command -a "systemctl status nginx" --become

# 指定 sudo 用户
ansible all -m command -a "whoami" --become --become-user www-data

调试输出

# 查看详细输出
ansible-playbook site.yml -vvvv

# 调试模式(失败时进入交互式调试)
ansible-playbook site.yml --step

# 检查模式
ansible-playbook site.yml --check

下一步

现在你已经掌握了 Ansible 的基础使用方法。接下来让我们深入学习主机清单管理。

👉 主机清单管理