‌Ansible 如何安装使用?

Ansible 安装与使用指南

一、Ansible 核心概念

Ansible 架构

SSH/WinRM
SSH/WinRM
SSH/WinRM
控制节点
被管节点1
被管节点2
被管节点N
Inventory
主机清单
Playbook
自动化剧本

核心组件

  • 控制节点:运行Ansible的主机(Linux/Python环境)
  • 被管节点:被管理的主机(无需安装Ansible)
  • Inventory:主机清单文件
  • Playbook:自动化任务的YAML文件
  • Module:执行具体任务的单元(超过3000个内置模块)

二、控制节点安装指南(Linux)

1. 基础安装方法

# Ubuntu/Debian
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible -y

# CentOS/RHEL
sudo yum install epel-release
sudo yum install ansible -y

# 验证安装
ansible --version

2. Python虚拟环境安装(推荐)

python3 -m venv ansible-env
source ansible-env/bin/activate
pip install --upgrade pip
pip install ansible cryptography

3. macOS 安装

brew install ansible

三、被管节点准备

Linux/Unix 节点:

# 确保SSH服务运行
sudo systemctl enable sshd
sudo systemctl start sshd

# Python环境(大多数现代Linux已预装)
python3 --version

Windows 节点:

  1. 启用WinRM服务
  2. 配置防火墙允许5985/5986端口
  3. 执行配置脚本:
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/ansible/ansible-documentation/devel/examples/scripts/ConfigureRemotingForAnsible.ps1" -OutFile ConfigureRemotingForAnsible.ps1
.\ConfigureRemotingForAnsible.ps1

四、主机清单(Inventory)配置

基础格式 (/etc/ansible/hosts 或自定义文件)

[webservers]
web1.example.com ansible_port=2222
web2.example.com

[dbservers]
db1.example.com
db2.example.com

[cluster:children]
webservers
dbservers

[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=~/.ssh/ansible_key

动态清单脚本示例(AWS)

#!/usr/bin/env python
import boto3
import json

ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])

inventory = {
    "webservers": {
        "hosts": [],
        "vars": {"ansible_user": "ubuntu"}
    }
}

for instance in instances:
    for tag in instance.tags:
        if tag['Key'] == 'Role' and tag['Value'] == 'web':
            inventory['webservers']['hosts'].append(instance.public_ip_address)

print(json.dumps(inventory))

五、连接认证设置

SSH密钥认证(推荐)

# 生成密钥对
ssh-keygen -t rsa -b 4096 -f ~/.ssh/ansible_key

# 分发公钥
ssh-copy-id -i ~/.ssh/ansible_key.pub user@host

密码认证(仅测试用)

# inventory文件配置
[servers]
host1 ansible_ssh_pass=your_password
host2 ansible_ssh_pass=your_password

# 命令行指定
ansible all -i hosts -m ping -u user -k

六、Ad-Hoc命令快速开始

# 测试所有主机连通性
ansible all -m ping

# 收集主机信息
ansible webservers -m setup

# 执行Shell命令
ansible dbservers -a "free -h"

# 文件分发
ansible all -m copy -a "src=/local/path dest=/remote/path"

# 包管理
ansible ubuntu_servers -m apt -a "name=nginx state=present" --become
ansible centos_servers -m yum -a "name=nginx state=present" --become

# 服务管理
ansible webservers -m service -a "name=nginx state=restarted enabled=yes" --become

七、Playbook 核心语法

Playbook结构示例

---
- name: Configure Web Server
  hosts: webservers
  become: yes
  vars:
    http_port: 8080
    max_clients: 200
  
  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: latest
        update_cache: yes
      when: ansible_os_family == 'Debian'
    
    - name: Copy Nginx config
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
      notify: Restart Nginx
  
  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

关键元素解析:

  • hosts: 目标主机组
  • become: 特权升级
  • vars: 定义变量
  • tasks: 任务列表
  • handlers: 触发操作
  • templates: Jinja2模板文件(.j2后缀)

八、常用模块详解

1. 文件管理

- name: Create directory
  file:
    path: /data/web
    state: directory
    owner: www-data
    group: www-data
    mode: '0755'

- name: Download file
  get_url:
    url: https://example.com/file.tar.gz
    dest: /tmp/file.tar.gz
    checksum: sha256:abcd1234...

2. 包管理

# Ubuntu/Debian
- apt:
    name: 
      - nginx
      - postgresql-client
    state: latest
    update_cache: yes

# CentOS/RHEL
- yum:
    name: httpd
    state: present

# Python包
- pip:
    name: 
      - django
      - requests
    executable: pip3

3. 用户管理

- name: Create user
  user:
    name: deploy
    comment: "Deployment User"
    groups: www-data
    append: yes
    shell: /bin/bash
    ssh_key: "{{ lookup('file', '/home/user/.ssh/id_rsa.pub') }}"

4. 服务管理

- name: Enable and start service
  systemd:
    name: nginx
    enabled: yes
    state: started
    daemon_reload: yes

九、进阶技巧

1. 角色(Roles)组织

site.yml
roles/
    common/
        tasks/
        handlers/
        files/
        templates/
        vars/
        defaults/
        meta/
    webserver/
        ...

2. 变量优先级

最高
最低
命令行变量
Playbook vars
Inventory变量
Role defaults
全局变量

3. Vault加密敏感数据

# 创建加密文件
ansible-vault create secrets.yml

# 编辑加密文件
ansible-vault edit secrets.yml

# 运行Playbook使用加密数据
ansible-playbook site.yml --ask-vault-pass

4. 条件执行

tasks:
  - name: Shutdown Debian systems
    command: /sbin/shutdown -t now
    when: ansible_facts['os_family'] == "Debian"

十、企业级最佳实践

1. CI/CD集成

# GitLab CI 示例
deploy_production:
  stage: deploy
  script:
    - mkdir -p ~/.ssh
    - echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - ansible-playbook -i production site.yml
  only:
    - master

2. 性能优化

# ansible.cfg
[defaults]
forks = 50
host_key_checking = False
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
fact_caching_timeout = 86400

[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
pipelining = True

3. 测试框架

# 安装测试工具
pip install molecule docker

# 创建测试场景
molecule init scenario -d docker

# 运行测试
molecule test

十一、排错指南

常见问题解决:

# 增加详细输出
ansible-playbook playbook.yml -vvv

# 检查主机连接
ansible -m ping all

# 语法检查
ansible-playbook --syntax-check playbook.yml

# 测试运行(dry-run)
ansible-playbook -C playbook.yml

# 查看可用模块
ansible-doc -l
ansible-doc yum

错误处理示例:

- name: Handle task failure
  block:
    - name: Critical task
      command: /bin/false
  rescue:
    - name: Rollback action
      debug:
        msg: "Task failed, performing rollback"
  always:
    - name: Always execute
      debug:
        msg: "Cleanup operations"

十二、Windows管理示例

Playbook示例:

- name: Configure Windows Server
  hosts: windows_servers
  vars:
    ansible_connection: winrm
    ansible_winrm_transport: ntlm
    ansible_winrm_server_cert_validation: ignore

  tasks:
    - name: Install IIS
      win_feature:
        name: Web-Server
        state: present
        include_management_tools: yes

    - name: Create website
      win_iis_website:
        name: TestSite
        state: started
        port: 8080
        physical_path: C:\sites\test

学习资源推荐

  1. 官方文档:https://docs.ansible.com
  2. Ansible Galaxy:https://galaxy.ansible.com
  3. 最佳实践指南:https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html
  4. 官方培训:Red Hat Ansible Automation Platform

提示:生产环境建议使用 AWX (开源) / Ansible Automation Platform (企业版) 作为控制中心,提供API接口、RBAC权限控制和可视化任务调度。

使用Kolla Ansible部署RabbitMQ的步骤如下: 1. 确保已经安装Ansible和Kolla Ansible。可以使用以下命令来安装: ```shell pip install ansible pip install kolla-ansible ``` 2. 创建一个Kolla Ansible的工作目录,并进入该目录: ```shell mkdir kolla-ansible cd kolla-ansible ``` 3. 在工作目录中创建一个`multinode`文件夹,并在其中创建一个`inventory`文件,用于定义主机和主机组。在`inventory`文件中,指定RabbitMQ节点的IP地址或主机名。例如: ```shell [control] controller ansible_host=192.168.0.1 [network] network1 ansible_host=192.168.0.2 network2 ansible_host=192.168.0.3 [compute] compute1 ansible_host=192.168.0.4 compute2 ansible_host=192.168.0.5 ``` 4. 在工作目录中创建一个`globals.yml`文件,用于配置Kolla Ansible的全局变量。在该文件中,可以指定RabbitMQ的相关配置,例如: ```yaml kolla_internal_vip_address: 192.168.0.10 kolla_rabbitmq_enable: "yes" kolla_rabbitmq_password: mypassword ``` 5. 在工作目录中创建一个`passwords.yml`文件,用于指定各个服务的密码。在该文件中,可以指定RabbitMQ的密码,例如: ```yaml rabbitmq_password: mypassword ``` 6. 在工作目录中创建一个`globals.yml`文件,用于配置Kolla Ansible的全局变量。在该文件中,可以指定RabbitMQ的相关配置,例如: ```yaml kolla_internal_vip_address: 192.168.0.10 kolla_rabbitmq_enable: "yes" kolla_rabbitmq_password: mypassword ``` 7. 在工作目录中创建一个`passwords.yml`文件,用于指定各个服务的密码。在该文件中,可以指定RabbitMQ的密码,例如: ```yaml rabbitmq_password: mypassword ``` 8. 运行Kolla Ansible的部署命令,使用`ansible-playbook`命令并指定`kolla-ansible`的部署脚本: ```shell ansible-playbook -i multinode --become --become-user=root -e @globals.yml -e @passwords.yml /usr/local/share/kolla-ansible/ansible/site.yml ``` 9. 等待部署完成后,可以使用RabbitMQ的管理界面或命令行工具来验证RabbitMQ是否成功部署。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值