简介

ansible是使用python开发的自动化运维工具. 使用YAML作为配置文件, 解决了运维过程中多机器管理的问题

使用ansible可以让运维人员通过简单直观的配置文件对所有纳入管理的机器进行统一管理, 并且ansible使用了push架构, 不需要像其他工具一样去被控端安装agent.

相关配置

ansible.cfg

ansible.cfg是ansible的主要配置文件, 最简单的的配置示例:

[defaults]
hostfile = hosts
remote_user = root
remote_port = 22
host_key_checking = False

inventory

可以看到, 在ansible.cfg中指定了hosts文件, 这个文件用来对被控端机器进行管理, 默认路径在/wtc/ansible/hosts(使用pip方式安装没有该路径), 也可以使用-i参数在命令行中指定

# all表示使用hosts中管理的所有机器
# 在linux中使用ping模块, windows中使用win_ping
ansible -i /home/root/hosts all -m ping
未分组形式

不推荐使用未分组形式来管理机器

xxx.einverne.info
einverne.info
12.12.12.12
192.168.2.1
192.168.2.200
10.0.0.1
分组形式
[webservers]
192.168.1.123 ansible_user=administrator ansible_password=123

[webservers:vars]
ansible_port=5986
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore

[dbservers]
192.168.2.123 ansible_user=administrator ansible_password=123

[dbservers:vars]
ansible_port=5987
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
配置范围
[webservers]
www[001:006].example.com

[dbservers]
db-[99:101]-node.example.com
配置别名
dbserver1 ansible_ssh_host=127.0.0.1 ansible_ssh_port=22 color=red
dbserver2 ansible_ssh_host=127.0.0.2 ansible_ssh_port=220


[dbserver] #group
dbserver1
dbserver2

[forum:children] #groups of groups
webserver
dbserver

ansible如何管理windows

ansible管理linux系统主要使用ssh连接到目标机器, 管理windows系统, 可以使用一下三种方式

  1. Windows 10或Windows Server 2016上安装WSL(Windows Subsystem for Linux), 如果是早于该版本的Windows系统, 可安装Cygwin模拟Linux环境. 然后启动sshd服务, 便可让Ansible进行管理
  2. Windows上开启wimrn连接方式
  3. ansible 2.8中增加了win32-openssh的ssh连接方式

让ansible通过wsl基于ssh连接的方式管理windows系统是非常受限的, 只能完成一些文件类的操作. 所以, 这里使用winrm的方式让ansible管理windows

安装ansible控制端

虽然ansible被控端可以是linux或者windows, 但是控制端目前只能使用类linux系统.

ansible控制端可以选择从源码编译安装, 也可以更加发行版本选择合适的安装方式

Ubuntu

sudo apt update
sudo apt install ansible

CentOS

sudo yum install ansible

pip

除了上述几种安装方式, 也可以使用pip安装

pip install ansible

注意: 使用pip安装后需要将安装路径添加到环境变量, 例如:

export PATH=$/usr/local/python3/bin:$PATH

更多安装方式参考: https://cn-ansibledoc.readthedocs.io/zh_CN/latest/installation_guide/intro_installation.html

安装完成后, 可以使用命令ansible --version来查看是否安装成功

ansible管理windows前的配置

安装pywinrm

对于ansible端来说, 唯一需要安装的就是python的wimrm

pip install pywinrm

管理windows端配置

对于windows端来说, 要让ansible管理windows, 要求

  1. powershell 3.0+
  2. .Net 4.0+

所以默认支持的windows系统包括

  1. Windows 7 SP1, 8, 10
  2. Windows server 2008 SP2, 2008 R2 SP1, 2012, 2012 R2, 2016, 2019

当满足以上条件后, 就可以开启winrm了, 可以使用以下脚本, 以管理员身份打开powershell进行配置

$ansibleconfigurl = "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
$ansibleconfig = "$env:temp\ConfigureRemotingForAnsible.ps1"
(New-Object -TypeName System.Net.WebClient).DownloadFile($ansibleconfigurl, $ansibleconfig)
powershell.exe -ExecutionPolicy ByPass -File $ansibleconfig

有些Windows机器上winrm服务可能启动方式是手动启动, 这时需要执行以下命令, 将winrm服务设置为自动启动, 并且开启winrm服务

Set-Service -Name WinRM -StartupType Automatic
Start-Service -Name WinRM

配置好后, 使用以下命令查看端口是否正常启动

> netstat -an | Select-String -Pattern '5986'

  TCP    0.0.0.0:5986           0.0.0.0:0              LISTENING
  TCP    [::]:5986              [::]:0                 LISTENING

ansible使用

ansible命令的基本用法

ansible <pattern> -m <module_name> -a <module_arguments>

测试windows是否正常工作

配置被控端机器信息
$ vim hosts

[win]
192.168.1.123 ansible_user=administrator ansible_password=123

[win:vars]
ansible_port=5986
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore

对于上述inventory配置, 需要注意

  1. 对于自签CA, ansible_winrm_server_cert_validation必须设置为ignore
  2. 密码尽量不出现在inventory中, 而采用Vault加密方式或者使用-k, --ask-pass参数由用户输入
  3. 如果是域用户, 那么ansible_user的格式为: USERNAME@domain_name
测试连接是否正常
$ ansible -i ./hosts win -m win_ping

192.168.1.123 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
可能出现的问题
  1. 未安装windows扩展, 使用以下命令安装
ansible-galaxy collection install ansible.windows
  1. Connection refused
192.168.1.123 | UNREACHABLE! => {
    "changed": false,
    "msg": "ssl: HTTPSConnectionPool(host='192.168.1.123', port=5986): Max retries exceeded with url: /wsman (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f48e0964d00>: Failed to establish a new connection: [Errno 111] Connection refused'))",
    "unreachable": true
}

出现这种情况是因为winrm服务没有开启, 打开powershell, 执行以下命令

> Get-Service WinRM

Status   Name               DisplayName
------   ----               -----------
Stopped  WinRM              Windows Remote Management (WS-Manag...

> Start-Service -Name WinRM

使用playbook

ansible-playbook使用yaml语法, 主要由以下几个部分构成

  • inventory: 主机列表, 表示playbook任务要应用到哪些机器
  • tasks: 具体任务, 即调用哪些模块完成操作, 可以配置多个任务
  • variables: 变量, 包含内置变量和自定义变量
  • templates: 模板, 使用模板语法来灵活变更配置文件
  • handlers与notify: 触发器, 由某些事件触发的操作, 比如重启服务等
playbook语法
  1. playbook本质上是包含一个或多个play的yaml配置文件
  2. 在单一的playbook文件中, 使用---作为每个play的区分
  3. 缩进必须统一
playbook示例

示例中playbook使用了win_file创建了两个新文件夹, 然后使用win_copy模块拷贝两个文件到创建的文件夹中

- name: 'copy files'
  hosts: all
  gather_facts: false
  become_method: runas
  tasks:
    - name: 'create directory'
      win_file:
        path: '{{ item }}'
        state: directory
      loop:
        - C:\new_dir1
        - C:\new_dir2

    - name: 'copy files from windows share'
      become: true
      become_flags: logon_type=new_credentials logon_flags=netcredentials_only
      vars:
        ansible_become_user: '{{ share_username }}'
        ansible_become_password: '{{ share_password }}'
      win_copy:
        src: '{{ item.src }}'
        dest: '{{ item.dest }}'
        remote_src: true
      loop:
        - { src: '\\share.com\file1.zip', dest: 'C:\new_dir1\file1.zip' }
        - { src: '\\share.com\file2.zip', dest: 'C:\new_dir2\file2.zip' }
执行playbook
ansible-playbook -i ./hosts copy_files.yaml

参考资料