ansible自动化运维 playbook

ansible自动化运维

最少两天机器:1.控制节点 2.受管节点 3.主机清单

1.安装ansible

先将ansible的镜像上传到虚拟机,可以使用 工具和xftp上传(镜像放在服务-红帽下了
要先配置好yum,再准备安装ansible

挂载光盘到 /opt
[root@localhost sky]# mount /root/Ansible.iso /opt/
mount: /opt: WARNING: device write-protected, mounted read-only.

添加仓库文件(前提是yum要配好,没配好还是安不了的)
[root@localhost sky]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# vim a.repo
[test]
name=test
baseurl=file:///opt
gpgcheck=0

可以查一下软件包,当然也可以不查
[root@localhost yum.repos.d]# yum list | grep ansible
ansible.noarch                                         2.9.22-1.el8ae  

[root@localhost yum.repos.d]# yum install -y ansible    //安装

正式配置前可以先查看一下配置文件
[root@localhost yum.repos.d]# rpm -qc ansible
/etc/ansible/ansible.cfg       // ansibe主配置文件
/etc/ansible/hosts             // ansibe清单文件

2.正式配置

下面内容中的切换用户和更改配置文件路径其实算是非必要的,但是题目很可能会有要求

切换用户更改配置文件路径
[root@localhost ~]# su - cy       //这里一定要加 -  完全切换  
[cy@localhost ~]$ mkdir ansible
[cy@localhost ~]$ cd ansible/
[cy@localhost ansible]$ pwd
/home/cy/ansible

 将主配置文件复制到 cy用户目录下
[cy@localhost ansible]$ cp /etc/ansible/ansible.cfg .
[cy@localhost ansible]$ ls
ansible.cfg

 查看配置文件路径是否更改
[cy@localhost ansible]$ ansible --version
ansible 2.9.22
config file = /home/cy/ansible/ansible.cfg      //看这个路径是否正确

更改清单文件路径
[cy@localhost ansible]$ vim ansible.cfg     //绝对路径为/home/cy/ansible/ansible.cfg
 14 inventory  = /home/cy/ansible/inventory     //后面的路径跟着题目要求改

创建并编辑新的清单
[cy@localhost ansible]$ touch inventory   //也可以用绝对路径/home/cy/ansible/inventory
[cy@localhost ansible]$ vim inventory
[test]                 //组名
192.168.109.131        //被管理的主机(这样就属于test组了)

验证命令,如果配置文件打错了会报错,会提示大概是哪有问题(英文的,看个大概)
[cy@localhost ansible]$ ansible-inventory --graph
@all:
  |--@test:
  |  |--192.168.109.131
  |--@ungrouped:
不记得最后一个单词可以  -h  查看  最下面就是的

3.验证

使用临时命令验证
临时命令格式:ansible 主机/主机组  [-m 模块] -a "命令"   []是可选项,可加可不加
相当于可以远程使用命令查看一些东西

要现在要连接的主机上创建用户
要连接的主机上要创建与主机器相同的用户名,我这边是cy  对面就创建cy
192.168.109.131下:
[root@localhost yum.repos.d]# useradd cy
[root@localhost yum.repos.d]# echo "123" | passwd cy --stdin 

回到主机:
这里用临时命令查看192.168.109.131主机的主机名
输入临时命令 (不要一上来就 -k ):
[cy@localhost ansible]$ ansible test -a "hostname"     //"" 里也可以改成其他命令
打   yes  回车

[cy@localhost ansible]$ ansible test -a "hostname" -k
SSH password:                 //输入对面用户的密码
192.168.109.131 | CHANGED | rc=0 >>
localhost.localdomain         //对面的主机名(效果)

成功 :)

免密

生成密钥
[cy@localhost ansible]$ ssh-keygen  //生成密钥
回车

将密钥传到另一台主机
[cy@localhost ansible]$ ssh-copy-id [email protected]
yes
输入对面root密码
回车

使用cy用户编辑
[cy@localhost ansible]$ vim ansible.cfg 
 71 host_key_checking = False
107 remote_user = root

[cy@localhost ansible]$ vim inventory 
[all:vars]
ansible_password=123       //输入对面root的密码 

[test]
192.168.109.131

再使用临时命令就不用 -k 也不用输密码了
[cy@localhost ansible]$ ansible test -a "id"
192.168.109.131 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) 组=0(root) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

playbook

文件格式:
playbook文件 以.yml结尾
格式和缩进也有要求
例子:

[cy@localhost ansible]$ vim playbook.yml
  1 ---                     //这是固定格式,一定要打           
  2 - name: useradd         //useradd相当于注释,可以不写 ( : 后一定要打空格
  3   hosts: test           //对哪台主机或主机组做        ( : 后一定要打空格
  4   tasks:                //下面是具体该怎么做(一般从帮助手册复制过来)
  5   - name: Add the user    
  6     user:
  7       name: dd              //创建的用户名
  8       comment: John Doe     //描述信息
  9       uid: 1040             //uid
  
更改vim设置
 先调整vim
  ~/. 是只设置cy下的vim
 [cy@localhost ansible]$ vim ~/.vimrc
 set nu  ts=2       sw=2     et    
       tab距离为2   宽为2    写入


调整缩进的方式
playbook格式要求很严格,缩进要标准
1.跳转到你要缩进的行
:5
2.按ctrl v进入可视化块模式
3.按↑↓方向键选中你要缩进的行
4.按I(大)进入输入模式
5.按tab键
6.按esc(两下)


查看帮助文档
不是用man查看了,使用ansible-doc 
当不清楚时,使用筛选来找到需要用到模块
[cy@localhost ansible]$ ansible-doc -l | grep user
user                                                          Manage user accounts 
需要自己判断一下,大致能找到需要使用的模块

例:
查看创建用户模块的帮助文档,用的时候直接复制就好
[cy@localhost ansible]$ ansible-doc user
/EX
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
  user:
    name: johnd
    comment: John Doe
    uid: 1040
    group: admin

综合案例

以下案例中一定要注意自己所在的路径和创建文件的路径
下面是使用playbook创建用户的例子:

 先调整vim
  ~/. 是只设置cy下的vim
 [cy@localhost ansible]$ vim ~/.vimrc
 set nu  ts=2       sw=2     et    
       tab距离为2   宽为2    写入

先查看一下帮助信息
[cy@localhost ansible]$ ansible-doc user
/EX
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
  user:
    name: johnd
    comment: John Doe
    uid: 1040
    group: admin

创建playbook文件  名字可以改,但要以.yml结尾
 [cy@localhost ansible]$ vim playbook.yml
  1 ---                     //这是固定格式,一定要打           
  2 - name: useradd         //useradd相当于注释,可以不写 ( : 后一定要打空格
  3   hosts: test           //对哪台主机或主机组做        ( : 后一定要打空格
  4   tasks:                //下面是具体该怎么做(一般从帮助手册复制过来)
  5   - name: Add the user    
  6     user:
  7       name: dd              //创建的用户名
  8       comment: John Doe     //描述信息
  9       uid: 1040             //uid

运行playbook
[cy@localhost ansible]$ ansible-playbook playbook.yml 

PLAY [useradd] *****************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.109.131]

TASK [Add the user] ************************************************************
changed: [192.168.109.131]

PLAY RECAP *********************************************************************
192.168.109.131            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

验证:
[cy@localhost ansible]$ ansible test -a "id dd"
192.168.109.131 | CHANGED | rc=0 >>
uid=1040(dd) gid=1040(dd) 组=1040(dd)
使用ansible安装http并开启
 先查看帮助信息
 [sky@localhost ~]$ ansible-doc yum
- name: install the latest version of Apache
  yum:
    name: httpd
    state: latest

[sky@localhost ~]$ ansible-doc service

- name: Start service httpd, if not started
  service:
    name: httpd
    state: started

编辑playbook文件  
[cy@localhost ansible]$ vim httpd.yml
  1 ---
  2 - name: apach
  3   hosts: test
  4   tasks:
  5   - name: install the latest version of Apache
  6     yum:
  7       name: httpd
  8       state: latest
  9   - name: Start service httpd, if not started
 10     service:
 11       name: httpd
 12       state: started

执行文件
[cy@localhost ansible]$ ansible-playbook httpd.yml

验证
查看是否安装httpd包,这个会报紫色的WARNING,不影响,是对的
[cy@localhost ansible]$ ansible test -a "rpm -q httpd"
查看服务状态
[cy@localhost ansible]$ ansible test -a "systemctl status httpd"
查找并添加内容

将/etc/test.txt文件内容增加
短主机名 hostname
长主机名 nodename
IP地址 ansible_default_ipv4.address
BIOS版本信息 ansible_bios_version

1.查找变量

setup:查找系统中的变量
使用setup 模块查找信息

还是先查看帮助文档
[sky@localhost ~]$ ansible-doc setup
/EX
# ansible all -m setup -a 'filter=ansible_*_mb'

查找主机名
[cy@localhost ansible]$ ansible all -m setup -a 'filter=*name*'
192.168.109.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_hostname": "localhost",              //短主机名    
        "ansible_nodename": "localhost.localdomain",  //长主机名    
        "ansible_product_name": "VMware Virtual Platform",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

查找ip地址
[cy@localhost ansible]$ ansible all -m setup -a 'filter=*ipv4*'
192.168.109.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.109.131",
            "192.168.122.1"
        ],
        "ansible_default_ipv4": {
            "address": "192.168.109.131",        //ip地址
            "alias": "ens160",
            "broadcast": "192.168.109.255",
            "gateway": "192.168.109.2",
            "interface": "ens160",
            "macaddress": "00:0c:29:6a:d9:60",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.109.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

查找BIOS信息
[cy@localhost ansible]$ ansible all -m setup -a 'filter=*bios*'
192.168.109.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_bios_date": "11/12/2020",
        "ansible_bios_version": "6.00",           //BIOS版本
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
2.定义模板

将变量写入模板test.j2中
变量名来自上面的setup查找

[cy@localhost ansible]$ vim test.j2
"{
   
   { ansible_hostname }} {
   
   { ansible_nodename }}  {
   
   { ansible_default_ipv4.address }} {
   
   { ansible_bios_version }}"                //注意,address在ipv4下,所以是用 . 分隔
3.将模板放入/etc/test.txt

使用template模块,将模板复制到指定路径

帮助文档
[cy@localhost ansible]$ ansible-doc template
/EX
- name: Template a file to /etc/files.conf
  template:
    src: /mytemplates/foo.j2
    dest: /etc/file.conf
    owner: bin
    group: wheel
    mode: '0644'

[cy@localhost ansible]$ vim temp.yml
  1 ---
  2 - name: template
  3   hosts: test
  4   tasks:
  5   - name: Template a file to /etc/files.conf
  6     template:
  7       src: /home/cy/ansible/test.j2     //源文件路径
  8       dest: /etc/test.txt               //要复制到的路径

执行
[cy@localhost ansible]$ ansible-playbook temp.yml 

PLAY [template] ******************************************************************************

TASK [Gathering Facts] ***********************************************************************
ok: [192.168.109.131]

TASK [Template a file to /etc/files.conf] ****************************************************
changed: [192.168.109.131]

PLAY RECAP ***********************************************************************************
192.168.109.131            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 


查看效果,已经到对面主机下/etc/test.txt 中了
[cy@localhost ansible]$ ansible test -a "cat /etc/test.txt"
192.168.109.131 | CHANGED | rc=0 >>
"localhost localhost.localdomain  192.168.109.131 6.00"

成功
使用playbook关闭selinux
使用linefile模块    更改文件行内容
[sky@localhost ~]$ ansible-doc -l | grep line
lineinfile        //有这个                            

查看帮助文档
[sky@localhost ~]$ ansible-doc lineinfile
/EX

- name: Ensure SELinux is set to enforcing mode
  lineinfile:
    path: /etc/selinux/config
    regexp: '^SELINUX='
    line: SELINUX=enforcing

创建并编辑playbook文件
[cy@localhost ansible]$ vim line.yml
  1 ---
  2 - name: line
  3   hosts: test
  4   tasks:
  5   - name: Ensure SELinux is set to enforcing mode
  6     lineinfile:
  7       path: /etc/selinux/config     //修改的文件路径
  8       regexp: '^SELINUX='
  9       line: SELINUX=disabled        //关闭(根据题目要求更改)
  
执行             
[cy@localhost ansible]$ ansible-playbook line.yml 

PLAY [line] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.109.131]

TASK [Ensure SELinux is set to enforcing mode] *********************************
changed: [192.168.109.131]

PLAY RECAP *********************************************************************
192.168.109.131            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

验证效果
[cy@localhost ansible]$ ansible test -a "grep ^SELINUX= /etc/selinux/config"
192.168.109.131 | CHANGED | rc=0 >>
SELINUX=disabled

成功
通过系统角色做NTP时间服务
1.搜索并安装角色包
查找系统角色包
[cy@localhost ansible]$ yum search role
a                                                             103 MB/s | 7.1 MB     00:00    
b                                                              75 MB/s | 2.5 MB     00:00    
CentOS Linux 8 - Extras                                       9.0 kB/s |  11 kB     00:01    
test                                                           47 MB/s | 105 kB     00:00    
================================== 名称 和 概况 匹配:role ===================================
policycoreutils-newrole.x86_64 : The newrole application for RBAC/MLS
====================================== 名称 匹配:role =======================================
rhel-system-roles.noarch : Set of interfaces for unified system management
这个包就是

默认cy普通用户是不能安包的
可以添加用root给cy添加sudo权限,也可以直接用root安装

[root@localhost sky]# visudo 
进去直接G到最后一行,往上翻移动就是了
99 ## Allow root to run any commands anywhere
100 root    ALL=(ALL)       ALL
101 cy      ALL=(ALL)       ALL    //添加这一行

[cy@localhost ansible]$ sudo yum install -y rhel-system-roles.noarch 
输入密码
2.查询相关文件,将角色路径写入配置文件
[cy@localhost ansible]$ rpm -ql rhel-system-roles 
在/usr/share/doc/开头的文件上方有/usr/share/ansible/roles 开头的
复制/usr/share/ansible/roles 这个路径(后面的不复制

[cy@localhost ansible]$ vim ansible.cfg 
 67 # additional paths to search for roles in, colon separated
 68 roles_path    = /usr/share/ansible/roles  //粘贴到这里
3.将样例复制到指定文件中
先查找样例
[sky@localhost sky]$ rpm -ql rhel-system-roles | grep example
/usr/share/doc/rhel-system-roles/timesync/example-timesync-playbook.yml
在倒数第二行,注意不要搞混了,是后面是playbook结尾的

将样例复制到指定文件中
cy可能没有权限,最好换root
[root@localhost ~]$ cp /usr/share/doc/rhel-system-roles/timesync/example-timesync-playbook.yml   /home/cy/ansible/ntp.yml
//这个ntp.yml文件是题目要求什么就是什么(一定要注意路径)

[cy@localhost ~]$ vim ntp.yml 
---
- hosts: test    //根据题目改
  vars:
    timesync_ntp_servers:
      - hostname: 192.168.109.131    //改ip或域名
        iburst: yes
      - hostname: 1.pool.ntp.org    //下面的就不用改了
        iburst: yes
      - hostname: 2.pool.ntp.org
        iburst: yes
      - hostname: 3.pool.ntp.org
        iburst: yes                
  roles:
    - rhel-system-roles.timesync

执行(要确保对面主机的yum(仓库)是配好了的,不然就是错的
[cy@localhost ansible]$ ansible-playbook ntp.yml 

 因为没有对面的主机没有配置NTP服务,会哟有报错,考试时候不会
4.验证
[cy@localhost ansible]$ ansible test -a "chronyc sources -v" //最好先打""内的命令,不然不能tab
192.168.109.131 | CHANGED | rc=0 >>
210 Number of sources = 4

  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^? localhost.localdomain         0   8     0     -     +0ns[   +0ns] +/-    0ns
^? time.neu.edu.cn               1   6     3    31  +1823us[+1823us] +/-   23ms
^- electrode.felixc.at           3   6    77    30  +2227us[+2227us] +/-  153ms
^* time.neu.edu.cn               1   6    77    32   -523us[-2933us] +/-   25ms

真正配置好的情况下,最下面是有ip的,但是现在环境不太行,只能这样了

猜你喜欢

转载自blog.csdn.net/qq_53454383/article/details/130833694