Ansible 自动化介绍
什么是 ANSIBLE?
自动化执行任务优点:
Ansible 特点
Ansible 概念和架构
Ansbile 环境部署
控制节点
# 控制节点安装 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.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 模块
[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
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=()
......
注意:command和shell模块要求被管理主机安装Python
编写和运行playbook
playbook编写
# 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列表
- 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
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
# 第二次执行剧本会全都是绿色
语法检查
[zhiqiang@controller web]$ ansible-playbook playbook.yaml --syntax-check
空运行
[zhiqiang@controller web]$ ansible-playbook playbook.yaml -C
提高输出详细程度
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
&spm=1001.2101.3001.5002&articleId=149403621&d=1&t=3&u=5a7b3d6891e243f0b22bb5236a6dcb68)
433

被折叠的 条评论
为什么被折叠?



