Ansible 自动化(基本配置与playbook)

Ansible 自动化介绍

什么是 ANSIBLE

Ansible is a simple automation language,通过Playbooks描述和配置IT基础架构。
Ansible可以管理强大的自动化任务,适用于不同的生产环境。同时,Ansible对于新用户来说,
也可以很快的上手运用到生产环境

自动化执行任务优点

1. 通过标准化,确保快速、正确地部署和配置所有系统。
2. 自动执行日常计划重复性任务,从而空出时间并专注于更重要的事情。
3. 更快速的交付应用。

Ansible 特点

1. 简单Ansible Playbooks是一个人们非常容易查阅,理解和更改的文本文件,用户不需要具备特定的代码编写技能。
2. 功能强大:可以使用Ansible部署应用,例如配置管理,工作流自动化,网络自动化。还可用于编排整个应用生命周期。
3. 无代理Ansible 是一个无代理的架构,通过OpenSSH或者WinRM连接到hosts,并执行任务,推送小的程序(Ansible modules)到这些主机上。这些程序用于设置系统到预期状态。在Ansible执行完成后,任何之前推送的模块,都会被删除。Ansible可以随时使用,因为被管理主机上不需要配置特定代理。正是因为这点,Ansible才更加高效和安全。
4. 跨平台支持:可以管理LinuxUNIXwindows 和网络设备。
5. 非常准确地描述应用Ansible Playbook使用YAML格式描述生产环境。
6. 可以通过版本控制管理Ansible Playbooksprojects是纯文本格式,可以当作源码存放在版本控制系统中。
7. 非常容易与其他系统集成: HP SAPuppetJenkins,红帽卫星服务器等。

Ansible 概念和架构

NODESAnsible架构中有两种计算机类型:
控制节点,安装有ansible软件的节点。
受管节点,被ansible管理的Linux系统、Windows系统、网络设备等。
INVENTORY:受管主机清单。
PLAYBOOKAnsible用户只需要编写playbook,确保主机是预期状态。
每个playbook可以包含多个play
每个play会在一组hosts上按顺序执行一系列tasks
每个task都执行一个模块,模块是一个小的代码段(PythonPowerShell,或者其他语言)Ansible自带几百个模块,执行不同类型自动化任务,例如操作系统文件,安装软件,API调用TasksplaysPlaybooks idempotent幂等的),在相同的主机上多次安全地执行 Playbooks,让主机是正确的状态。如果主机已经是预期状态,则Playbook不会做任何改变。
PLUGINS,添加到Ansible中的代码段,用于扩展Ansible平台。

Ansbile 环境部署

控制节点

控制节点即用来安装Ansible软件的主机节点。控制节点可以是一个或多个,由 ansible 管理的主
机不用安装Ansible
# 控制节点安装 ansible
[root@controller ~]# dnf install -y ansible

向受关节点添加用户,配置免密登录,并免提sudo提权执行任何命令

添加受关节点的控制用户
[root@ROG ~]# useradd zhiqiang
[root@ROG ~]# echo zhiqiang | passwd --stdin laoma

向控制用户自身配置免密登录
[zhiqiang@controller ~]$ ssh-keygen
[zhiqiang@controller ~]$ ssh-copy-id zhiqiang@localhost

配置受关节点用户sudo免密提权
[root@ROG ~]# echo 'zhiqiang ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/zhiqiang

取消主机密钥强校验
[zhiqiang@controller ~]# vim /etc/ssh/ssh_config
 StrictHostKeyChecking no
  • 克隆配置好的主机,并修改各受关节点名称与IP地址

  • 向各节点/etc/hosts增加域名解析

构建 ansible 主机清单

# 向各个节点中添加域名解析
[root@control ~/ansible]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.1.8.10 node1
10.1.8.20 node2
10.1.8.30 node3
10.1.8.100 control
[root@control ~]# for ((i=10;i<=30;i+=10));do scp /etc/hosts 10.1.8.$i:/etc/hosts;done


# 配置主机清单
[root@control ~]# cat ansible/inventory 
[group1]
node1

[group2]
node2

[group3]
node3

[group4:children]  # 增加children 在此组底下可写其他主机组
group1
group2

# 验证主机是否在 inventory 清单中
[root@control ~/ansible]# ansible -i inventory --list-hosts all
  hosts (3):
    node3
    node1
    node2

ansiblle:

  • -i:指定管理清单

  • -m:指定模块

  • -a:模块参数

  • -b:提权root

Ansible配置文件管理

配置ansible.cfg文件

  • 当前目录位置中的ansible.cfg:./ansible.cfg 优先级高,优先生效,建议优先使用

  • 用户配置文件位置:~/.ansible.cfg

  • 全局配置文件位置: /etc/ansible/ansible.cfg

  • 用命令生成ansible的文件,命令可去/etc/ansible/ansible.cfg查找:ansible-config init --disabled > ansible.cfg

命令执行结果颜色说明
Ansible的返回结果都非常友好,用3种颜色来表示执行结果:
红色:表示执行过程有异常,一般会中止剩余所有的任务。
绿色:表示目标主机已经是预期状态,不需要更改 。
黄色:表示命令执行结束后目标有状态变化,并设置为预期状态,所有任务均正常执行。

ansible.cfg配置文件

# 常用参数解释
# 主要包含以下部分
[defaults]
# inventory 指定清单文件路径
inventory = /etc/ansible/hosts
# 并发执行同一个任务的主机数量
forks          = 5
# ansible检查任务是否执行完成的时间间隔
poll_interval  = 15
# 连接登录到受管主机时是否提示输入密码
ask_pass = True
# 控制facts如何收集
# smart - 如果facts已经收集过了,就不收集了。
# implicit - facts收集,剧本中使用gather_facts: False关闭facts收集。
# explicit - facts不收集,剧本中使用gather_facts: True关闭facts收集。
gathering = implicit
# 收集facts超时时间
gather_timeout = 10
# 变量注入,通过ansible_facts引用
inject_facts_as_vars = True
# 定义角色路径,以冒号分隔
roles_path = /etc/ansible/roles
# SSH是否检验 host key
host_key_checking = False
# 连接登录到受管主机时使用的用户身份
remote_user = root
# ansible 命令和ansible-playbook 命令输出内容存放位置
log_path = /var/log/ansible.log
# ansible 命令默认模块
module_name = command
# ssh私钥文件位置
private_key_file = /path/to/file
# 默认ansible-vault命令的密码文件
vault_password_file = /path/to/vault_password_file
# 定义ansible_managed变量值
ansible_managed = Ansible managed
# 剧本执行过程中,遇到未定义的变量不报错
error_on_undefined_vars = False
# 系统告警启用
system_warnings = True
# 下架告警启用
deprecation_warnings = True
# 使用command和shell模块时,是否提示告警
command_warnings = False
# facts保存在哪里,例如redis
fact_caching = memory

[inventory]
# 启用的清单插件, 默认为: 'host_list', 'script', 'auto', 'yaml', 'ini', 
'toml'
#enable_plugins = host_list, virtualbox, yaml, constructed
# 当清单源是一个目录的时候,忽略这些后缀的清单文件
#ignore_extensions = .pyc, .pyo, .swp, .bak, ~, .rpm, .md, .txt, ~, .orig, .ini, .cfg, .retry

[privilege_escalation]
# 连接到受管主机后是否需要进行权限提升或切换用户
become=True
# 使用何种方式进行用户切换或提权
become_method=sudo
# 用户切换或提权后的对应用户
become_user=root
# 进行用户切换或提权时是否提示输入密码
become_ask_pass=False
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]
[defaults]

配置ansible.cfg 

# 配置配置文件
[defaults]
#指定主机配置清单位置
inventory=./inventory
#指定执行的用户
remote_user=zhiqiang
#连接主机时是否输入密码
ask_pass=True

[privilege_escalation]
#提权
become=True
#提权时是否输入密码
become_ask_pass=False
#提权方法
become_method=sudo
#提权的用户
become_user=root

ansible-config view

用于查看配置文件的内容

# ansible-config view 查看配置文件内容
[root@control ~/ansible]# ansible-config view
[defaults]
inventory=/etc/ansible/hosts
remote_user=zhiqiang

[privilege_escalation]
become=True
become_ask_pass=False
become_method=sudo
become_user=root


# 查看所有主机 id  -a 执行命令
[zhiqiang@control ~/ansible]$ ansible all -a id
node3 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
node2 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
node1 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
node4 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)

ansible-doc 命令

  • 快速执行单个**Ansible任务**,而不需要将它保存下来供以后再次运行。它们是简单的在线操作,无需编写playbook即可运行。

  • 快速测试和更改很有用。例如,您可以使用临时命令确保一组服务器上的/ etc/hosts文件存在某一特定的行。您可以使用另一个临时命令在许多不同的计算机上高效重启一项服务,或者确保特定的软件包为最新版本。

  • Ansible的返回结果都非常友好,用3种颜色来表示执行结果:

    • 红色:表示执行过程有异常,一般会中止剩余所有的任务。

    • 绿色:表示目标主机已经是预期状态,不需要更改 。

    • 黄色:表示命令执行结束后目标有状态变化,并设置为预期状态,所有任务均正常执行。

Ansible 部分模块

  • 文件模块

    • copy: 将控制主机上的文件复制到受管节点,类似于scp

    • *file: 设置文件的权限和其他属性

    • lineinfile: 确保特定行是否在文件中

    • synchronize: 使用 rsync** 将控制主机上的文件同步到受管节点

  • 软件包模块

    • package: 自动检测操作系统软件包管理器

    • yum: 使用 YUM 软件包管理器管理软件包

    • apt: 使用 APT 软件包管理器管理软件包

    • dnf: 使用 DNF 软件包管理器管理软件包

    • gem: 管理 Rubygem

    • pip: 从 PyPI 管理 Python 软件包

  • 系统模块

    • ansible.posix.firewalld : 使用firewalld管理任意端口和服务

    • reboot: 重新启动计算机

    • service: 管理服务

    • user、group:管理用户和组帐户

  • NetTools模块

    • get_url: 通过HTTP、HTTPS或FTP下载文件

    • nmcli: 管理网络

    • uri: 与 Web 服务交互

# ansible-doc 命令
[root@control ~]# ansible-doc --help
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH] [--playbook-dir BASEDIR]
                   [-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy,test,filter,role,keyword}]
                   [-j] [-r ROLES_PATH]
                   [-e ENTRY_POINT | -s | -F | -l | --metadata-dump]
                   [--no-fail-on-errors]
                   [plugin ...]

plugin documentation tool

positional arguments:
  plugin                Plugin

options:
  --metadata-dump       **For internal use only** Dump json metadata for all
                        entries, ignores other options.
  --no-fail-on-errors   **For internal use only** Only used for --metadata-dump. Do
                        not fail on errors. Report the error message in the JSON
                        instead.
  --playbook-dir BASEDIR
                        Since this tool does not use playbooks, use this as a
                        substitute playbook directory. This sets the relative path
                        for many features including roles/ group_vars/ etc.
  --version             show program's version number, config file location,
                        configured module search path, module location, executable
                        location and exit
  -F, --list_files      Show plugin names and their source files without summaries
                        (implies --list). A supplied argument will be used for
                        filtering, can be a namespace or full collection name.
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library
                        (default={{ ANSIBLE_HOME ~
                        "/plugins/modules:/usr/share/ansible/plugins/modules" }}).
                        This argument may be specified multiple times.
  -e ENTRY_POINT, --entry-point ENTRY_POINT
                        Select the entry point for role(s).
  -h, --help            show this help message and exit
  -j, --json            Change output into json format.
  -l, --list            List available plugins. A supplied argument will be used
                        for filtering, can be a namespace or full collection name.
  -r ROLES_PATH, --roles-path ROLES_PATH
                        The path to the directory containing your roles. This
                        argument may be specified multiple times.
  -s, --snippet         Show playbook snippet for these plugin types: inventory,
                        lookup, module
  -t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy,test,filter,role,keyword}, --type {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy,test,filter,role,keyword}
                        Choose which plugin type (defaults to "module"). Available
                        plugin types are : ('become', 'cache', 'callback',
                        'cliconf', 'connection', 'httpapi', 'inventory', 'lookup',
                        'netconf', 'shell', 'vars', 'module', 'strategy', 'test',
                        'filter', 'role', 'keyword')
  -v, --verbose         Causes Ansible to print more debug messages. Adding
                        multiple -v will increase the verbosity, the builtin
                        plugins currently evaluate up to -vvvvvv. A reasonable
                        level to start is -vvv, connection debugging might require
                        -vvvv. This argument may be specified multiple times.

See man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com

示例

# 查看模块清单说明
[root@control ~]# ansible-doc -l
amazon.aws.autoscaling_group                                               
amazon.aws.autoscaling_group_info                                           
amazon.aws.aws_az_info                                                     
amazon.aws.aws_caller_info                                                 
amazon.aws.aws_region_info
......

# 查看模块清单及位置
[root@control ~]# ansible-doc -F
amazon.aws.autoscaling_group                                               
amazon.aws.autoscaling_group_info                                         
amazon.aws.aws_az_info                                                     
amazon.aws.aws_caller_info                                                 
amazon.aws.aws_region_info                                                 
amazon.aws.backup_plan                                                     
amazon.aws.backup_plan_info
......

# 查看特定模块说明文档 编写 playbook 可查看
[root@control ~]# ansible-doc user
> ANSIBLE.BUILTIN.USER    (/usr/lib/python3.12/site-packages/ansible/modules/user.py)

        Manage user accounts and user attributes. For Windows targets,
        use the [ansible.windows.win_user] module instead.

ADDED IN: version 0.2 of ansible-core

OPTIONS (= is mandatory):

- append
        If `true', add the user to the groups specified in `groups'.
        If `false', user will only be added to the groups specified in
        `groups', removing them from all other groups.
        default: false
        type: bool
......




command 模块

command 模块允许管理员在受管节点的命令行中运行任意命令。要运行的命令通过-a选项指定
为该模块的参数。
[zhiqiang@controller web]$ ansible node1 -m command -a 'hostname'
node1 | CHANGED | rc=0 >>
node1.linux.fun
[zhiqiang@controller web]$ ansible node1 -m command -a 'hostname' -o
node1 | CHANGED | rc=0 | (stdout) node1.linux.fun
说明:
1. command模块执行的远程命令不受受管节点上的shell处理,无法访问shell环境变量,也不能执行重定向和传送等shell操作。
2. 如果临时命令没有指定模块,Ansible默认使用command模块。

shell 模块

shell模块允许您将要执行的命令作为参数传递给该模块。 Ansible随后对受管节点远程执行该命
令。与command模块不同的是, 这些命令将通过受管节点上的shell进行处理。因此,可以访问
shell环境变量,也可使用重定向和管道等shell操作。
[zhiqiang@controller web]$ ansible node1 -m command -a set
node1 | FAILED | rc=2 >>
[Errno 2] No such file or directory: 'set': 'set'
[zhiqiang@controller web]$ ansible node1 -m shell -a set
node1 | CHANGED | rc=0 >>
BASH=/bin/sh
BASHOPTS=cmdhist:complete_fullquote:extquote:force_fignore:hostcomplete
:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
......

注意:commandshell模块要求被管理主机安装Python

编写和运行playbook

adhoc 命令可以作为一次性命令对一组主机运行一项简单的任务。不过,若要真正发挥Ansible
能力,需要使用功能 playbook
playbook 是一个文本文件,其中包含由一个或多个按特定顺序运行的play组成的列表。play是针
对清单中选定的主机运行的一组有序任务。play可以让您将一系列冗长而复杂的手动管理任务转
变为可轻松重复的例程,并且具有可预测性。
playbook 中,您可以将play内的任务序列保存为人类可读并可立即运行的形式。根据任务的
编写方式,任务本身记录了部署应用或基础架构所需的步骤。

playbook编写

Playbooksyaml格式编写,通常以yamlyml扩展名保存
# playbook 文件格式
# 以 yaml或yml结尾
# 开始行以 --- 开头 以 ... 结束
# play的属性:name,hosts,becom,tasks等
---
# plya名称  
- name: manager user
# 管理的主机
  hosts: nodes
# 任务
  tasks:
# 任务名称  
    - name: add user
# 需要执行的模块    
      user:
# 模块中的参数 模块的具体内容可以通过 ansible-doc 查看      
        name: qiang
        uid: 9999

- name: manager user
  hosts: nodes
  tasks:
    - name: remove user
      command: userdel -r zhiqiang

...

yaml列表

一组按次序排列的值,又称为序列(sequence)和数组(array)。
以缩进块的形式编写的键值对集合,如下方所示:
- name: latest version of httpd and firewalld installed
  yum:
    name:
      - httpd
      - firewalld
    state: latest
- name: test html page is installed
  copy:
    content: "Welcome to the example.com intranet!\n"
    dest: /var/www/html/index.html
以上有两个任务,每个任务都是多个键值对描述。其中yum模块操作的软件包是一个简单的名称
列表。
内联格式:
name: [httpd, firewalld]

Playbook 运行

运行

[zhiqiang@controller web]$ ansible-playbook playbook.yaml 
PLAY [Enable intranet services] 
***************************************************
TASK [Gathering Facts] 
************************************************************
ok: [node1]
TASK [latest version of httpd and firewalld installed] 
****************************
changed: [node1]
TASK [test html page is installed] 
************************************************
changed: [node1]
TASK [firewalld enabled and running] 
**********************************************
ok: [node1]
TASK [firewalld permits access to httpd service] 
**********************************
changed: [node1]
TASK [httpd enabled and running] 
**************************************************
changed: [node1]
PLAY [Test intranet web server] 
***************************************************
TASK [Gathering Facts] 
************************************************************
ok: [localhost]
TASK [connect to intranet web server] 
*********************************************
ok: [localhost]
PLAY RECAP 
**********************************************************************
localhost                 : ok=2    changed=0    unreachable=0   
failed=0    skipped=0    rescued=0    ignored=0   
node1                   : ok=6    changed=4    unreachable=0   
failed=0    skipped=0    rescued=0    ignored=0



# 第二次执行剧本会全都是绿色

语法检查

选项--syntax-check,只检查剧本语法,不执行剧本。
[zhiqiang@controller web]$ ansible-playbook playbook.yaml --syntax-check

空运行

[zhiqiang@controller web]$ ansible-playbook playbook.yaml -C

提高输出详细程度

-v,显示任务结果。
-vv,任务结果和任务配置都会显示。
-vvv,包含关于与受管主机连接的信息。
-vvvv,增加了连接插件相关的额外详细程度选项,包括受管主机上用于执行脚本的用户,
以及所执行的脚本。

Playbook 提权

在playbook中指定此关键字将覆盖/etc/ansible/ansible.cfg文件中的设置升级属性

  • remote_user,指定ssh用户

  • become,启用或禁用特权升级

  • become_method,启用特权升级的方法

  • become_user,特殊升级的帐户

---
- name: Enable intranet services
  hosts: node1
  
  remote_user: laoma
  become: true
  become_method: sudo
  become_user: root
  
  tasks:
    - name: latest version of httpd and firewalld installed
      yum:
        name:
          - httpd
          - firewalld
        state: latest

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值