ansible深入理解和操作——02(主机清单,yml语法,
发表于:2025-12-01 作者:千家信息网编辑
千家信息网最后更新 2025年12月01日,本章内容:一.inventory主机清单二.yml语法三.playbook详解+操作inventory主机清单ansible默认的主机清单是/etc/ansible/hosts文件主机清单可以手动设置
千家信息网最后更新 2025年12月01日ansible深入理解和操作——02(主机清单,yml语法,
本章内容:
一.inventory主机清单
二.yml语法
三.playbook详解+操作
inventory主机清单
ansible默认的主机清单是/etc/ansible/hosts文件主机清单可以手动设置,也可以通过Dynamic Inventory动态生成一般主机名使用FQDNvi /etc/ansible/hosts[webserver] #方括号设置组名www1.example.org #定义被监控主机,这边可以是主机名也可以是IP地址,主机名需要修改/etc/hosts文件www2.example.org:2222 #冒号后定义远程连接端口,默认是ssh的22端口如果是名称类似的主机,可以使用列表的方式标识各个主机[webserver]www[01:50].example.org ansible_ssh_user=root ansible_ssh_pass=123456[dbbservers]db-[a:f].example.org下面是Inventory中变量
(1)主机变量[webserver]www1.magedu.com http_port=80 maxRequestsChild=808www2.magedu.com http_port=8080 maxRequestsChild=909(2)组变量[servers:vars]ntp_server=ntp.example.orgnfs_server=nfs.example.org(3)组嵌套[apache]http1.example.orghttp2.example.org[nginx]ngx1.example.orgngx2.example.org[webservers:children]apachenginx(4)inventory变量参数参数 说明ansible_ssh_host 将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.ansible_ssh_port ssh端口号.如果不是默认的端口号,通过此变量设置.ansible_ssh_user 默认的 ssh 用户名ansible_ssh_pass ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)ansible_ssh_private_key_file ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.ansible_ssh_common_args 此设置附加到sftp,scp和ssh的缺省命令行ansible_sftp_extra_args 此设置附加到默认sftp命令行。ansible_scp_extra_args 此设置附加到默认scp命令行。ansible_ssh_extra_args 此设置附加到默认ssh命令行。ansible_ssh_pipelining 确定是否使用SSH管道。 这可以覆盖ansible.cfg中得设置。ansible_shell_type 目标系统的shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为 'csh' 或 'fish'.ansible_python_interpreter 目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是"/usr/bin/python",比如 *BSD, 或者 /usr/bin/pythonansible_*_interpreter 这里的"*"可以是ruby 或perl 或其他语言的解释器,作用和ansible_python_interpreter 类似ansible_shell_executable 这将设置ansible控制器将在目标机器上使用的shell,覆盖ansible.cfg中的配置,默认为/bin/sh。yaml语法
对象和集合的区别:
对象 属性1 长:5m 属性2 宽:2m 属性3 高:1.5m集合 对象1 对象2 对象3YAML:另一种标记语言。是用来写配置文件的语言,非常简洁和强大。
YAML语法和其他语言类似,也可以表达散列表、标量等数据结构。
结构通过空格来展示;序列里配置项通过-来代表;Map里键值用:来分隔;YAML的扩展名为yaml
基本语法规则:
1.大小写敏感2.使用缩进表示层级关系3.缩进时不允许使用Tab键,只允许使用空格。4.缩进的空格数目不重要,只要相同层级的元素左侧对齐即可YAML支持的数据结构:1.对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary) 例如:name:Example Developer 键 值2.数组:一组按次序排列的值,又称为序列(sequence) / 列表(list) 例如:-Apple -Orange3.纯量:单个的、不可再分的值 例如:number:12.30 sure:trueyaml示例:
name:zhangsanage:20name:lisiage:22people:-name:zhangsan age:20 -name:lisi age:22playbook详解+操作
Ansible的脚本---playbook
通过task调用ansible的模板将多个play组织在一个playbook中运行。
playbooks本身由以下各部分组成
(1)Tasks:任务,即调用模块完成的某操作;相当于事务,没有执行成功就会回滚
(2)Variables:变量,主机清单,剧本,命令当中-e声明变量,三种场景
(3)Templates:模板
(4)Handlers:处理器,当某条件满足时,触发执行的操作;
(5)Roles:角色。
下面是一个playbook的示例
- hosts: webserver //定义的主机组,即应用的主机 vars: //定义变量 http_port: 80 max_clients: 200 user: root tasks: //执行的任务 - name: ensure apache is at the latest version #友好提示,自己定义 yum: pkg=httpd state=latest #检查httpd包是不是最新版本 - name: write the apache config file template: src=/srv/httpd.j2 dest=/etc/httpd.conf notify: #调用触发下面具体的操作 - restart apache - name: ensure apache is running service: name=httpd state=started handlers: //处理器 - name: restart apache #调这个操作 service: name=httpd state=restarted执行一个playbookansible-playbook [yaml文件名]例如:ansible-playbook ping.yml参数:-k(-ask-pass) 用来交互输入ssh密码 -K(-ask-become-pass) 用来交互输入sudo密码 -u 指定用户补充命令:ansible-playbook nginx.yml --syntax-check #检查yaml文件的语法是否正确ansible-playbook nginx.yml --list-task #检查tasks任务ansible-playbook nginx.yml --list-hosts #检查生效的主机ansible-playbook nginx.yml --start-at-task='Copy Nginx.conf' #指定从某个task开始运行实验环境
主控端
被控端01 192.168.136.168
被控端02 192.168.136.185
被控端03 192.168.136.253
ansibel环境部署,加入主机清单
[webserver]192.168.136.168[mysql]192.168.136.185[ftpserver]192.168.136.253#关闭所有主机防火墙[root@localhost ~]# systemctl stop firewalld.service [root@localhost ~]# setenforce 0#免交户ssh-keygen -t rsa #生成密钥,回车,输入密码#公钥推给对方主机ssh-copy-id root@192.168.136.168ssh-copy-id root@192.168.136.185 //配置密钥对验证ssh-copy-id root@192.168.136.253root@localhost ~]# ssh-agent bash #ssh代理[root@localhost ~]# ssh-add #添加密码hosts和users介绍
[root@localhost ~]# vim a.yml- hosts: webserver #指定主机组,可以是一个或多个组。 remote_user: root #指定远程主机执行的用户名[root@localhost ~]# ansible-playbook a.yml PLAY [webserver] ***************************************************************TASK [Gathering Facts] *********************************************************ok: [192.168.136.168]PLAY RECAP *********************************************************************192.168.136.168 : ok=1 changed=0 unreachable=0 failed=0 还可以为每个任务定义远程执行用户:
---- hosts: mysql remote_user: root tasks: - name: test connect ping: remote_user: root #指定远程主机执行tasks的运行用户为mysql执行playbook时:ansible-playbook ping.ymlLAY [webserver] *******************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.136.168]TASK [test connect] ****************************************************************ok: [192.168.136.168]PLAY RECAP *************************************************************************192.168.136.168 : ok=2 changed=0 unreachable=0 failed=0 指定远程主机sudo切换用户:
---- hosts: mysql remote_user: root become: yes #2.6版本以后的参数,之前是sudo,意思为切换用户运行 become_user: mysql #指定sudo用户为mysql执行playbook时:ansible-playbook ping.yml -Ktasks列表和action1.Play的主体部分是task列表,task列表中的各任务按次序逐个在hosts中指定的主机上执行,即在所有主机上完成第一个任务后再开始第二个任务。在运行playbook时(从上到下执行),如果一个host执行task失败,整个tasks都会回滚,请修正playbook 中的错误,然后重新执行即可。Task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量,模块执行时幂等的,这意味着多次执行是安全的,因为其结果一致。2.每一个task必须有一个名称name,这样在运行playbook时,从其输出的任务执行信息中可以很好的辨别出是属于哪一个task的。如果没有定义name,'action'的值将会用作输出信息中标记特定的task。3.定义一个task,常见的格式:"module: options" 例如:yum: name=httpd4.ansible的自带模块中,command模块和shell模块无需使用key=value格式小示例:---- hosts: webserver remote_user: root tasks: - name: disable selinux command: '/sbin/setenforce 0' - name: install httpd yum: name=httpd #这边还可以关闭防火墙,加上一段: - name: disable firewalld service: name=firewalld state=stopped - name: start httpd service: name=httpd state=started[root@localhost ~]# ansible-playbook a.yml PLAY [webserver] *******************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.136.168]TASK [disable selinux] *************************************************************changed: [192.168.136.168]TASK [install httpd] ***************************************************************changed: [192.168.136.168]TASK [start httpd] *****************************************************************changed: [192.168.136.168]PLAY RECAP *************************************************************************192.168.136.168 : ok=4 changed=3 unreachable=0 failed=0 play中只要执行命令的返回值不为0,就会报错,tasks停止修改如下:加入执行失败,我们可以设置一个参数跳过一个问题,继续下面的操作ignore_errors: True ---- hosts: webserver remote_user: root tasks: - name: disable selinux command: '/sbin/setenforce 0' ignore_errors: True #忽略错误,强制返回成功 - name: make sure apache is running service: name=httpd state=started以下是另外一个示例,可以读一读
---- hosts: webserver remote_user: root tasks: - name: create nginx group group: name=nginx system=yes gid=208 - name: create nginx user user: name=nginx uid=208 group=nginx system=yes- hosts: mysql remote_user: root tasks: - name: copy file to mysql copy: src=/etc/inittab dest=/opt/inittab.backHandlers介绍
Handlers也是一些task的列表,和一般的task并没有什么区别。是由通知者进行的notify,如果没有被notify,则Handlers不会执行,假如被notify了,则Handlers被执行不管有多少个通知者进行了notify,等到play中的所有task执行完成之后,handlers也只会被执行一次示例---- hosts: webserver remote_user: root tasks: - name: install httpd package yum: name=httpd state=latest - name: install configuration file for httpd copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf notify: -restart httpd - name: start httpd service service: enabled=true name=httpd state=started handlers: - name: restart httpd service: name=httpd state=restarted也可以引入变量 ---- hosts: webserver remote_user: root vars: - package: httpd - service: httpd tasks: - name: install httpd package yum: name={{package}} state=latest - name: install configuration file for httpd copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf notify: -restart httpd - name: start httpd service service: enabled=true name={{service}} state=started handlers: - name: restart httpd service: name={{service}} state=restarted#写一个创建用户的引入变量的小事列[root@localhost ~]# vim b.yml - hosts: ftpserver remote_user: root vars: - username: lisi tasks: - name: create user user: name={{username}}[root@localhost ~]# ansible-playbook b.yml --syntax-checkplaybook: b.yml[root@localhost ~]# ansible-playbook b.yml PLAY [ftpserver] *******************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.136.253]TASK [create user] *****************************************************************ok: [192.168.136.253]PLAY RECAP *************************************************************************192.168.136.253 : ok=2 changed=0 unreachable=0 failed=0 ansible-playbook b.yml -e username=lisi主机清单也可以加入要使用的用户playbook使用变量的方法:1.通过ansible命令传递例如:编辑如下yamlvi a.yml---- hosts: mysql remote_user: root vars: - user: tasks: - name: add new user user: name={{user}}然后执行命令: ansible-playbook a.yml -e "user=testvar"可以执行命令查看:ansible mysql -m command -a 'tail /etc/passwd'2.直接在yaml中定义变量---如上handlers示例3.直接引用一些变量如:引用ansible的固定变量#content指定文件内容到路径下vi test.yml---- hosts: mysql remote_user: root tasks: - name: copy file copy: content="{{ansible_all_ipv4_addresses}}," dest=/opt/vars.txt执行命令:ansible-playbook test.yml去253上查看vars.txt文件内容[root@localhost opt]# cat add.txt ["192.168.122.1", "192.168.136.253"]再如:引用主机变量vi /etc/ansible/hosts在mysql组的主机后面添加如下[mysql]192.168.80.183 testvar="80.183" #定义testvar变量的值为80.183vi test.yml #添加{{testvar}}主机变量---- hosts: mysql remote_user: root tasks: - name: copy file copy: content="{{ansible_all_ipv4_addresses}},{{testvar}}" dest=/opt/vars.txt执行命令:ansible-playbook test.yml去183上查看vars.txt文件内容--------条件测试--------
如果需要根据变量、facts(setup)或此前任务的执行结果来作为某task执行与否的前提时要用到条件测试,在Playbook中条件测试使用when子句。在task后添加when子句即可使用条件测试:when子句支持jinjia2表达式或语法,例如:vi when.yml---- hosts: mysql remote_user: root tasks: - name: "shutdown CentOS" command: /sbin/shutdown -h now #-r重启 when: ansible_distribution == "CentOS"PLAY [mysql] ***********************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.136.185]TASK [shutdown CentOS] *************************************************************fatal: [192.168.136.185]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to 192.168.136.185 closed.\r\n", "unreachable": true} to retry, use: --limit @/root/b.retryPLAY RECAP *************************************************************************192.168.136.185 : ok=1 changed=0 unreachable=1 failed=0 多条件判断
vi when.yml---- hosts: mysql remote_user: root tasks: - name: "shut down CentOS 6 systems" command: /sbin/shutdown -r now when: - ansible_distribution == "CentOS" - ansible_distribution_major_version == "6"组条件判断(和,且,或)
vi when.yml---- hosts: mysql remote_user: root tasks: - name: "shut down CentOS 6 and Debian 7 systems" command: /sbin/shutdown -t now when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")自定义变量进行条件测试
#满足为true就创建文件,满足为False旧删除vi when.yml---- hosts: all vars: exist: "True" tasks: - name: creaet file command: touch /tmp/test.txt when: exist | match("True") #match:匹配 - name: delete file command: rm -rf /tmp/test.txt when: exist | match("False") TASK [Gathering Facts] *************************************************************ok: [192.168.136.253]ok: [192.168.136.168]ok: [192.168.136.185]TASK [creaet file] ***************************************************************** [WARNING]: Consider using file module with state=touch rather than running touchchanged: [192.168.136.185]changed: [192.168.136.253]changed: [192.168.136.168]TASK [delete file] *****************************************************************skipping: [192.168.136.253]skipping: [192.168.136.168]skipping: [192.168.136.185]PLAY RECAP *************************************************************************192.168.136.168 : ok=2 changed=1 unreachable=0 failed=0 192.168.136.185 : ok=2 changed=1 unreachable=0 failed=0 192.168.136.253 : ok=2 changed=1 unreachable=0 failed=0 ----------迭代-------------#相当于遍历
当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句指明迭代的元素列表即可。例如:---- hosts: webserver remote_user: root tasks: - name: "Install Packages" yum: name={{ item }} state=latest #item:去下面的集合遍历 with_items: #一步一步安装 - httpd - mysql-server - php 也可以自己定义(还可以设置数组,看做一整行,后面根据调某一个属性变量名,就调出来了)---- hosts: webserver remote_user: root tasks: - name: "Add users" user: name={{ item.name }} state=present groups={{ item.groups }} with_items: - { name:'test1', groups:'wheel'} - { name:'test2', groups:'root'}#小事列- hosts: all vars: exist: "False" tasks: - name: create users user: name={{item}} with_items: - t01 - t02 - t03ok: [192.168.136.253]ok: [192.168.136.168]ok: [192.168.136.185]TASK [create users] ****************************************************************changed: [192.168.136.253] => (item=t01)changed: [192.168.136.168] => (item=t01)changed: [192.168.136.185] => (item=t01)changed: [192.168.136.253] => (item=t02)changed: [192.168.136.168] => (item=t02)changed: [192.168.136.185] => (item=t02)changed: [192.168.136.253] => (item=t03)changed: [192.168.136.168] => (item=t03)changed: [192.168.136.185] => (item=t03)PLAY RECAP *************************************************************************192.168.136.168 : ok=2 changed=1 unreachable=0 failed=0 192.168.136.185 : ok=2 changed=1 unreachable=0 failed=0 192.168.136.253 : ok=2 changed=1 unreachable=0 failed=0 #去主机查看有没有这些用户t01:x:1001:1001::/home/t01:/bin/basht02:x:1002:1002::/home/t02:/bin/basht03:x:1003:1003::/home/t03:/bin/bashTemplates模块
#把168的httpd配置文件复制过来[root@localhost ~]# vim /etc/ansible/hosts [root@localhost ~]# scp root@192.168.136.168:/etc/httpd/conf/httpd.conf ./httpd.conf 100% 11KB 4.0MB/s 00:00 #修改httpd配置文件Listen {{http_port}} #变量ServerName {{server_name}}MaxClients {{access_num}}mv httpd.conf httpd.conf.j2#赋值[root@localhost ~]# vim /etc/ansible/hosts [webserver]192.168.136.168 http_port=192.168.136.168:80 server_name="www.yun.com:80" access_num=200 #指定端口,域名,访问次数200[root@localhost ~]# vim apache.yml- hosts: webserver remote_user: root vars: - package: httpd - service: httpd tasks: - name: check latest yum: name-{{package}} state=latest - name: configure apache template: src=/etc/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #源在本地的控制端,指定对方的被控端 notify: - restart httpd - name: start httpd service: name={{server}} enabled=true state=started handlers: - name: restart httpd service: name={{server}} state=restarted[root@localhost ~]# ansible-playbook apache.yml --syntax-checkplaybook: apache.yml[root@localhost ~]# ansible-playbook apache.yml PLAY [webserver] *******************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.136.168]TASK [check latest] ****************************************************************ok: [192.168.136.168]TASK [configure apache] ************************************************************changed: [192.168.136.168]TASK [start httpd] *****************************************************************changed: [192.168.136.168]RUNNING HANDLER [restart httpd] ****************************************************changed: [192.168.136.168]PLAY RECAP *************************************************************************192.168.136.168 : ok=5 changed=3 unreachable=0 failed=0 #有了模板就根据这个模板就统一修改其他被控端的所有主机的配置文件去两台远程主机上查看grep -i listen /etc/httpd/conf/httpd.confgrep -i maxClient /etc/httpd/conf/httpd.confgrep -i servername /etc/httpd/conf/httpd.conftags模块
在一个playbook中,我们一般会定义很多个task,如果我们只想执行其中的某一个task或多个task时就可以使用tags标签功能了,格式如下:vi hosts.yml---- hosts: webserver remote_user: root tasks: - name: Copy hosts file copy: src=/etc/hosts dest=/etc/hosts tags: - only #打上标记我只执行我标记的操作 - name: touch file file: path=/opt/hosts state=touch执行命令:ansible-playbook hosts.yml --tags="only"PLAY [webserver] *******************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.136.168]TASK [Copy hosts file] *************************************************************ok: [192.168.136.168]PLAY RECAP *************************************************************************192.168.136.168 : ok=2 changed=0 unreachable=0 failed=0 ansible-playbook hosts.yml事实上,不光可以为单个或多个task指定同一个tags。playbook还提供了一个特殊的tags为always。作用就是当使用always当tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。vi hosts.yml---- hosts: webserver remote_user: root tasks: - name: Copy hosts file copy: src=/etc/hosts dest=/etc/hosts tags: - only - name: touch file file: path=/opt/hosts state=touch tags: - always执行命令:ansible-playbook hosts.yml --tags="only"分别去两台被管理服务器上去查看文件创建情况
主机
变量
命令
文件
用户
任务
模块
清单
语法
参数
条件
配置
多个
对象
示例
运行
内容
密码
测试
密钥
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
开展网络安全主题班会的班会总结
服务器咆哮
请求报文的服务器地址
计算机应用技术软件开发薪资
万方数据库库
小学生网络安全小视频素材
网络安全教育班会策划书模板
网络安全 班队会ppt
pc与服务器的关系
高青染色管理软件开发
软件开发技术大专学校
安全实时数据库
tomcat运行达梦数据库项目
网络安全进军营宣传
我的世界1.9.0服务器
数据库恢复中安全策略
华为网络技术大赛题目
代理服务器 台湾
宽带需要输入服务器名称吗
本特利铃声软件开发
为何什么药数据库
凡悟软件开发
gp数据库后台日志
浙江商业软件开发现价
森林服务器搜索不到
2018年网络安全周的主体
网络安全分析师岗位
静安区互联网络技术服务方案
软件平台服务器配置
三级网络技术文案高级