1.给受管主机部署yum仓库,尝试安装httpd服务
#确保ansible.con和inventory文件都配置好的前提下,编写以yml为后缀名的文件
[xiaoming@centos78 chap01]$ vim test.yml
---
- name: yum仓库管理
hosts: all
tasks:
- yum_repository:
name: aliyun-baseos
description: aliyun-baseos
baseurl: https://mirrors.aliyun.com/centos/8.5.2111/BaseOS/x86_64/os/
gpgcheck: no
- yum_repository:
name: aliyun-appstream
description: aliyun-appstream
baseurl: https://mirrors.aliyun.com/centos/8.5.2111/AppStream/x86_64/os/
gpgcheck: no
- name: 安装httpd服务
yum:
name: httpd
state: latest
2.给web主机组写一个playbook,该playbook有两个play,第一个play可以保证在web主机组上安装httpd和php,确保web主机组的/var/www/html/目录下面有一个文件为index.php,内容如下:
$ cat /var/www/html/index.php
<?php
phpinfo();
#确定好web组中的受管主机
[xiaoming@centos78 chap01]$ cat inventory
[web]
node1
#编写文件内容:
[xiaoming@centos78 chap01]$ vim index.php
<?php
phpinfo();
#编写配置文件(剧本)
---
- name: yum仓库管理
hosts: all
tasks:
- yum_repository:
name: aliyun-baseos
description: aliyun-baseos
baseurl: https://mirrors.aliyun.com/centos/8.5.2111/BaseOS/x86_64/os/
gpgcheck: no
- yum_repository:
name: aliyun-appstream
description: aliyun-appstream
baseurl: https://mirrors.aliyun.com/centos/8.5.2111/AppStream/x86_64/os/
gpgcheck: no
- name: 安装httpd php服务
yum:
name:
- httpd
- php
state: latest
- name: 启动HTTP服务
service:
name: httpd
state: started
- name: 开启防火墙
service:
name: firewalld
state: started
- name: 防火墙服务
firewalld:
service: http
permanent: yes
immediate: yes
state: enabled
- name: copy /var/www/html/index.php
copy:
src: index.php
dest: /var/www/html/index.php
3.在受控节点上添加一个普通用户xiaohong,配置当前控制节点的用户可以免密登录xiaohong用户,并且xiaohong可以sudo。
#编写ansible-playbook配置文件
[xiaoming@centos78 chap01]$ vim user-add.yml
---
- name: 添加用户
hosts: node1
tasks:
- name: useradd xiaohong
user:
name: xiaohong
state: present
- name: xiaohong提权
lineinfile:
line: xiaohong ALL=(ALL) NOPASSWD:ALL
path: /etc/sudoers
- name: 传递公钥
authorized_key:
user: xiaohong
state: present
key: "{{ lookup('file', '/home/xiaoming/.ssh/id_rsa.pub') }}"
检验:
[xiaoming@centos78 ~]$ ssh xiaohong@node1
welcome to ansible
Last login: Fri Nov 25 19:06:05 2022
[xiaohong@node1 ~]$
#sudo提权检验:
[xiaohong@node1 ~]$ cat /etc/sudoers
cat: /etc/sudoers: 权限不够
[xiaohong@node1 ~]$ sudo cat /etc/sudoers
Defaults !visiblepw
Defaults always_set_home
Defaults match_group_by_gid
Defaults always_query_group_plugin
Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root ALL=(ALL) ALL
xiaoming ALL=(ALL) NOPASSWD:ALL
xiaohong ALL=(ALL) NOPASSWD:ALL
#xiaohong用户提权成功