Ansible远程自动化运维

目录

概念

安装ansible

modules模块和语法

命令行语法

模块

[1. command 基础模块](#1. command 基础模块)

常用的参数

[2. shell模块](#2. shell模块)

[3. cron定时任务模块](#3. cron定时任务模块)

[4. user用户管理模块](#4. user用户管理模块)

参数

[5. copy复制模块](#5. copy复制模块)

参数

[6. file模块 设置文件属性](#6. file模块 设置文件属性)

参数

实验:批量创建目录

[7. hostname模块](#7. hostname模块)

[8. ping模块](#8. ping模块)

[9. yum模块](#9. yum模块)

[10. service模块](#10. service模块)

常用的参数

[11. 防火墙和网络模块](#11. 防火墙和网络模块)

iptables模块

如何禁用和放空端口

firewalld模块

配置网卡

修改网卡

重启网卡

[12. script模块](#12. script模块)

[13. setup模块](#13. setup模块)

[14. tags模块](#14. tags模块)

实验:指定标签

实验:自定义标签

[15. templates 模板](#15. templates 模板)

实验:基于http

[16. roles角色](#16. roles角色)

实验

主机清单

直接在配置文件里面声明ssh

​编辑

批量匹配ip地址

组嵌套(匹配多个组)

​编辑

playbook剧本(ansible的脚本)

实验

用脚本远程给目标主机安装http

用脚本远程给目标主机安装nginx

定义变量,引用变量

脚本当中定义,以及脚本外传参

实验:创建用户

切换执行用户

在脚本中实现条件判断

实验:过滤主机

循环结构

[with_item 单循环输出](#with_item 单循环输出)

​编辑

with_list整个列表作为一个整体进行输出

with_together作为整体,两两配对输出

[with_nested 每一层都是遍历执行一遍,输出结果](#with_nested 每一层都是遍历执行一遍,输出结果)

练习


概念

ansible是基于python开发的配置管理和应用部署工具,也是自动化运维的重要工具。它可以批量配置、部署、管理上千台主机。只需要在一台主机配置ansible就可以完成其他主机的操作。

操作模式:

1.模块化操作,也可以理解为命令行执行

2.playbook 剧本,也就是把命令行脚本化,脚本的格式是yaml格式

ansible的特性:幂等性

幂等性:多次操作或者多次执行,对系统的影响不会发生变化,也就是不论执行多少次结果都是一样的。就是ansible什么都不会做。注:restart 不属于幂等性范围,因为restart是先stop再start是执行两次不同命令

ansible的四大组件:

1.Inventory 主机清单 又叫主机组

必须是要声明管理主机的地址或者其他配置,不声明ansible无法对目标主机进行操作

2.modules 模块 (核心)

ansible的功能是靠模块来实现的

3.插件

4.playbook 剧本(脚本) 主要作用:复用

安装ansible

yum -y install epel-release

yum -y install ansible

cd /etc/ansible/

vim hosts

添加主机组1 指向到被管理端的ip地址 (名字可以自定义)

添加主机组2 指向到被管理端的ip地址(名字可以自定义)

然后配置密钥对

ssh-keygen -t rsa 然后一路回车即可

sshpass -p '123' ssh-copy-id root@192.168.233.22

sshpass -p '123' ssh-copy-id root@192.168.233.23

如果报错重新再传一下即可

modules模块和语法

命令行语法

ansible-doc -l 列出ansible所有已安装的模块(支持的模块)

格式:ansible 组名/ip地址 -m 指定模块 -a '参数或者命令'

不加-m,默认使用command

模块

1. command 基础模块

基础模块,也是ansible的默认模块。它不支持管道符和重定向操作,它只能执行一般的Linux命令

ansible 192.168.233.23 -m command -a "date" 打印23主机当前的时间

ansible all -m command -a "date" 所有被管理的主机都会执行打印当前的时间

常用的参数

chdir 在目标主机提前进入目录,然后执行指令

ansible 192.168.233.23 -a 'chdir=/home ls'

creates 判断文件是否存在,如果存在,那么就不执行后面的指令

不执行ls /opt

removes 判断文件是否存在,如果存在,就执行指令

存在就会执行

ansible 192.168.233.23 -a 'tar -xf /opt/nginx-1.22.0.tar.gz -C /opt' 解压文件

ansible 192.168.233.23 -a 'chdir=/opt tar -xf /opt/nginx-1.22.0.tar.gz' 解压文件

2. shell模块

支持管道符和重定向,也可以用逻辑表达式 && 且 ; 逻辑或

ansible 192.168.233.23 -m shell -a 'useradd test' 创建test用户

ansible 192.168.233.23 -m shell -a 'echo 123456 | passwd --stdin test' 添加用户密码

ansible 192.168.233.23 -m shell -a 'echo 123 > /opt/123' 支持重定向

ansible 192.168.2233.23 -m shell -a 'touch /opt/123.txt && echo 123 > /opt/123.txt && cat /opt/123.txt' 可以执行多个命令

ansible 192.168.233.23 -m shell -a 'echo -e "#!/bin/bash\nifconfig" > /opt/test.sh && sh /opt/test.sh' 在23主机创建一个脚本,在脚本中写ifconfig 然后运行脚本

3. cron定时任务模块

minute/hour/day/month/weekday 分/时/日/月/周

格式:ansible 192.168.233.23 -m cron -a 'minute=30 hour=8 day=* job="ls /opt" name="test1"'

创建定时任务

job表示定时任务执行的命令

ansible 192.168.233.23 -a 'crontab -l' 查看定时任务

ansible 192.168.233.23 -m cron -a 'name="test1" state=absent' 删除定时任务

注:如果没有名字 name=None

4. user用户管理模块

参数

name 用户名 必选参数

state=present 或者 absent present创建 absent 删除

system=yes 或者 no yes是程序用户 no是普通用户

uid 指定用户的uid 注1000以上都是普通用户 ,1-999都是程序用户

group 指定用户组

shell 可以规定指定用户的登录的shell 默认是系统用户可以不加

create_home=yes 或者 no 不是默认的家目录/home,需要指定家目录时,yes就是创建 ,no就是不创建

password 给用户添加密码

remove=yes 或者 no 只有state=absent删除用户时,用remove=yes删除家目录

ansible 192.168.233.23 -m user -a 'name=xy102 shell=/sbin/nologin system=yes ' 创建程序用户

ansible 192.168.233.23 -m user -a 'name=xy103 home=/opt/xy create_home=yes password=123' 创建和用户、指定家目录、创建密码

ansible 192.168.233.23 -m user -a 'name=xy102 remove=yes state=absent' 删除用户并删除家目录

5. copy复制模块

就是把当前主机的文件复制到目标主机

参数

src 表示源文件

dest表示目标主机的保存路径

mode复制文件时,表示权限

owner 文件的所有者 属主

group 文件的所在组 属组

content 指定复制的内容,用了content 就不能用src

ansible 192.168.233.23 -m copy -a 'src=/opt/xy102.txt dest=/opt/'

ansible 192.168.233.23 -m copy -a 'src=/opt/xy102.txt dest=/opt/ mode=640 owner=dn group=dn'

ansible 192.168.233.23 -m copy -a 'content="黑" dest/opt/test1.txt mode=777 owner=dn group=dn' 指定内容复制

6. file模块 设置文件属性

参数

mode

owner

group

state=touch 创建 或者 absent 删除

state=directory 创建目录

ansible 192.168.233.23 -m file -a 'path=/opt/abc.txt state=touch mode=777 owner=dn group=dn'

创建文件

ansible 192.168.233.23 -m file -a 'path=/opt/abc.txt.link src=/opt/abc.txt state=link' 创建连接文件

ansible 192.168.233.23 -m file -a 'path=/opt/abc.txt.link state=absent' 删除连接文件

实验:批量创建目录
bash 复制代码
- name: test1
  hosts: 192.168.233.23
  gather_facts: false
  tasks:
    - name: create mulu
      file:
        path: "{{ item }}"
        state: directory
      with_items: [/opt/test1,/opt/test2,/opt/test3]
      

7. hostname模块

设置远程主机的主机名

ansible 192.168.233.23 -m hostname -a "name=nginx1"

8. ping模块

测试与远程主机之间通信是否正常 是否成功看 success

格式:ansible all -m ping

9. yum模块

在目标主机安装和卸载软件 注:yum只能安装和卸载软件,不能启动软件

ansible 192.168.233.23 -m yum -a 'name=httpd' 安装http

ansible 192.168.233.23 -m yum -a 'name=httpd state=adsent' 卸载http

ansible 192.168.233.23 -a 'systemctl status httpd' 查看httpd的状态

10. service模块

用来管理目标主机上的软件的运行状态

常用的参数

name 声明服务名称

state=started或者stopped或者restarted

enabled=true 开机自启

runlevel=40 运行级别 如果设置了开机自启,就需要声明运行级别

ansible 192.168.233.23 -m service -a 'name=nginx enabled=true state=started runlevel=60'

注:这里设置了开机自启,所以必须设置运行级别

11. 防火墙和网络模块

iptables模块

ansible 192.168.233.23 -m iptables -a 'chain=INPUT protocol=ICMP source=192.168.233.22 jump=REJECT' -b

拒绝22主机ping23主机

如何禁用和放空端口

ansible 192.168.233.23 -m iptables -a 'chain=INPUT protocol=tcp destination_port=80 jump=REJECT' -b

拒绝80端口访问

ansible 192.168.233.23 -m iptables -a 'chain=INPUT protocol=tcp destination_port=80 jump=ACCEPT' -b

允许80端口的访问

ansible 192.168.233.23 -m iptables -a 'chain=INPUT protocol=tcp destination_port=80 jump=REJECT state=absent' -b

删除策略 就是在后面加state=absent 即可

firewalld模块

ansible 192.168.233.23 -m firewalld -a 'service=http zone=public permanent=true state=enabled immediate=true' -b 指定服务

注:zone=public是指定区域,permanent=true表示永久生效,state=enabled表示开机自启,immediate=true表示立即生效

ansible 192.168.233.23 -m firewalld -a 'port=80/tcp zone=public permanent=true state=enabled immediate=true' -b

指定端口

ansible 192.168.233.23 -m firewalld -a 'port=80/tcp zone=public permanent=true state=disabled immediate=true' -b

删除firewalld策略

firewalld-cmd --get-services 获取firewalld支持所有services的类型

firewalld-cmd --get-services | grep http

配置网卡
修改网卡

ansible 192.168.233.23 -m ansible.builtin.lineinfile -a "path=/etc/sysconfig/network-scripts/ifcfg-ens33 regexp='^IPADDR' line='IPADDR=192.168.233.100'" -b

把192.168.233.23的ip地址改为192.168.233.100

重启网卡

ansible 192.168.233.23 -a 'systemctl restart network'

12. script模块

先本地写脚本,然后在目标主机上执行脚本,所以脚本执行的结果是目标主机的

absible 192.168.233.23 -m script -a '/opt/test.txt'

13. setup模块

查看目标主机的信息。包括ip地址、cpu、内核版本、系统信息

ansible 192.168.233.23 -m setup 查看目标主机的全部信息

ansible 192.168.233.23 -m setup -a 'filter=ansible_*processor*' 查看目标主机的cpu

ansible 192.168.233.23 -m setup -a 'filter=ansible_proc_cmdline' 查看目标主机的内核版本

ansible 192.168.233.23 -m setup -a 'filter=ansible_mem*' 查看目标主机的内存

ansible 192.168.233.23 -m setup -a 'filter=ansible_system*' 查看目标主机的系统信息

14. tags模块

可以给任务定义标签,可以根据标签来运行指定的任务

标签的类型:

always:如果设定了标签名为always,除非指定跳过这个标签,否则该任务将始终会运行,即使指定了其他的标签,它也会运行

ansible-playbook test.yaml --skip-tags=always 跳过always,这样就不执行always任务

never:始终不运行的任务,指定标签名never才可以运行

debug:用于调试

setup:收集主机的信息

标签名也可以自定义

实验:指定标签
bash 复制代码
- name: test1
  hosts: 192.168.233.23
  gather_facts: false
  tasks:
    - name: debug-test1
      debug:
        msg: "cow"
      tags:
        - debug
    - name: always-test1
      debug:
        msg: "ALWAYS-RUN"
      tags:
        - always
    - name: setup-test1
      debug:
        msg: "Setup-test1"
      tags:
        - setup
    - name: never-test1
      debug:
        msg: "Never-run"
      tags:
        - never

指定标签运行:ansible-playbook test.yaml --tags=setup

指定多标签运行:ansible-playbook test.yaml --tags="setup","debug"

实验:自定义标签
bash 复制代码
- name: test
  hosts: 192.168.233.23
  remote_user: root
  tasks:
    - name: copy-test1
      copy: src=/ect/hosts dest=/opt/hosts
      tags:
        - aaa
    - name: touch file
      file: path=/opt/test1 state=touch
      tags:
        - bbb

15. templates 模板

作用:对应用的配置文件初始化

它里面有Jinja组件,Jinja的作用就是把编译过的模板文件传递给目标文件

实验:基于http

cd /etc/httpd/conf

cp httpd.conf /opt/httpd.conf.j2

cd /opt

vim httpd.conf.j2

设置模板

bash 复制代码
- name: test
  hosts: 192.168.233.23
  gather_facts: false
  remote_user: root
  vars:
    - pg: httpd
    - sv: httpd
  tasks:
    - name: install httpd
      yum: name={{ pg }}
    - name: editon conf
      template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
      notify:
        - restart httpd
  handlers:
    - name: restart httpd
      service: name={{ sv }} state=restarted
      

16. roles角色

ansible为了层次化、结构化的组织playbook,使用roles(角色)通过层次化来自动装载变量、任务和处理器等等

roles把变量、任务和模块的文件单独放置在各个不同的目录中,通过roles一键的编排

mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p

mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p

mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p

yum -y install tree

然后执行 tree 就会出现下面的

── httpd 角色名称,可以自定义

│ ├── defaults 存放配置文件的目录,可以不写

│ ├── files 存放copy模块和script模块需要的文件

│ ├── handlers 存放处理器文件的目录

│ ├── meta 保存角色元信息的文件

│ ├── tasks 保存任务的文件

│ ├── templates 保存模板的文件

│ └── vars 保存变量的文件

就是把原来写一个yaml的配置,分开到不同目录,不同的目录保存在一个名字的yaml里面,执行的时候调用不同目录的同一个yaml文件

必须保存在main.yaml

实验

cd /etc/ansible/roles/php/

cd tasks/

vim main.yaml

bash 复制代码
- name: install httpd
  yum: name={{pkg}}
- name: start apach
  service: name={{svc}} enabled=true state=started

cd vars/

vim main.yaml

bash 复制代码
pkg: httpd
svc: httpd

cd /etc/ansible/

vim test1.yaml

bash 复制代码
- hosts: 192.168.233.23
  remote_user: root
  roles:
    - httpd

ansible-playbook test1.yaml

主机清单

主机清单里面有主机组ip地址

cd /etc/ansible

vim hosts

直接在配置文件里面声明ssh

192.168.233.10 ansible_port=22 ansible_user=root ansible_password=123

这样声明就不需要ssh传密钥对,但是只对当前目标主机生效

这样写就是对组内所有主机都生效

批量匹配ip地址

192.168.233.1[1:3] 就是从11------13

192.168.233.[1:5][0:9] 就是从10------59

组嵌套(匹配多个组)

playbook剧本(ansible的脚本)

playbook的组成:

1.Tsaks 任务:每一个Tsaks就是一个模块

2.Variables 变量:用来存储和传递数据,可以是全局变量、自定义变量,也可以是脚本外传参

3.Templates 模板:用于生产配置文件和多任务的编排

4.Handlers 处理器:用于满足某些条件时触发的操作,一般用于重启等操作

5.roles 角色:它是组织和封装剧本的过程,角色可以把任务、变量、模板、处理器组合成一个可用单元

playbook用的是yaml文件的语法,注意格式和缩进

实验

用脚本远程给目标主机安装http

vim test.yaml (后缀名必须是 .yaml)

bash 复制代码
- name: first play
#定义剧本的名称(可以不写)
  gather_facts: false
#表示在执行剧本之前是否收集目标主机的信息。false就是不收集,可以加快执行速度,如果不写默认就是收集
  hosts: 192.168.233.20
#指定目标主机,可以写组名或者ip地址
  remote_user: root
#在目标主机的执行用户
  tasks: 
    - name: test connection
#定义一个任务的名称,可以自定义
      ping:
#ping就是模块的名称
    - name: close selinux
      command: '/sbin/setenforce 0'
      ignore_errors: True下去
#如果在执行任务中报错,如果返回码非0,就会报错,task就会停止,true就会忽略错误,继续执行下一个任务
    - name: close firewalld
      service: name=firewalld state=stopped
#调用service模块,关闭防火墙
    - name: install httpd
      yum: name=httpd state=latest
#latest,安装当前库中的最新版本的软件
    - name: interview
      shell: echo "this is httpd" > /var/www/html/index.html
#指定shell模块,修改默认的访问页面
      notify: restart httpd
#ansible在执行完任务之后不会立即执行重启,需要通过notify指令对应的名称传给触发器,让触发器在任务的最后执行重启,避免在任务中多次执行重启,影响执行的效率
#触发器:
  handlers:
    - name: restart httpd
      service: name=httpd state=restarted
     

运行命令: ansible-playbook test.yaml

用脚本远程给目标主机安装nginx

bash 复制代码
- name: first play
  gather_facts: false
  hosts: 192.168.233.22
  remote_user: root
  tasks:
    - name: test connection
      ping:
    - name: close selinux
      command: '/sbin/setenforce 0'
      ignore_errors: True
    - name: close firewalld
      service: name=firewalld state=stopped
    - name: install nginx
      yum: name=nginx state=latest
    - name: copy nginx.conf
      copy: src=/opt/nginx.conf dest=/etc/nginx/
    - name: interview
      shell: echo "this is nginx" > /usr/share/nginx/html/index.html
      notify: restart nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

定义变量,引用变量

脚本当中定义,以及脚本外传参
实验:创建用户
bash 复制代码
- name: second play
  hosts: 192.168.233.23
  remote_user: root
#定义变量:
  vars:
    groupname: mysql
    username:nginx
  tasks:
    - name: create group
      group:
        name: "{{ groupname }}"
        system: yes
        gid: 306
    - name: create user
      user:
        nmae: "{{ username }}"
        udi: 306
        group: "{{ groupname }}"    

ansible-playbook test.yaml -e 'groupname=test1 username=test2'

-e 脚本外传参

ansible-playbook test.yaml --syntax-check 检查脚本语法是否正确

如果什么都没有表示没有问题

ansible-playbook test.yaml --list-task 检测脚本中有几个任务

ansible-playbook test.yaml --list-hosts 检查对哪些主机生效

ansible-playbook test.yaml --start-at-task='create user' -e 'username=test3' 指定任务执行

注:外面传参优先级高,外面传参会把里面覆盖掉

切换执行用户

become_user 切换用户

在脚本中实现条件判断

when 满足条件的主机执行,不满足的主机跳过

实验:过滤主机
bash 复制代码
- name: this is if
  hosts: all
  remote_user: root
  tasks:
    - name: test when
      debug: msg='条件满足'
#debug相当于echo 就是echo"条件满足"
      when: ansible_default_ipv4.address == "192.168.233.23"

注:!= 取反

循环结构

ansible有多种循环方式,一般都命名为with_items,定义循环的内容

with_item 单循环输出
bash 复制代码
- name: item test
  hosts: 192.168.233.23
  remote_user: root
  gather_facts: false
  tasks:
    - debug:
        msg: "{{ item }}"
      with_items:[a,b,c,d]
#输出item的值,with_items:a,b,c,d 依次传入
with_list整个列表作为一个整体进行输出
with_together作为整体,两两配对输出

注:如果对应的是空,会以null的形式显示

with_nested 每一层都是遍历执行一遍,输出结果
bash 复制代码
- hosts: 192.168.233.23
  gather_user: root
  remote_user: root
  vars:
    - pg: httpd
    - sv: httpd
  tasks:
    - name: install httpd
      yum: name={{ pg }}
    - name: editon conf
      template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
      notify:
        - restart httpd
  handlers:
    - name: restart httpd
      service: name={{ sv }} state=restarted
      

练习

条件判断主机的ip,一次性创建4个文件

bash 复制代码
- name: item test
  hosts: all
  remote_user: root
  tasks:
    - name: test when
      debug: msg='条件满足'
      when: ansible_default_ipv4.address == "192.168.233.23"
    - name: touch test with file module
      file:
        path: "{{ item }}"
        state: touch
      with_items:
        - /opt/a
        - /opt/b
        - /opt/c
        - /opt/d
相关推荐
人类群星闪耀时1 分钟前
服务器管理:从零开始的服务器安装与配置指南
运维·服务器
王哲晓1 小时前
Linux通过yum安装Docker
java·linux·docker
gopher95111 小时前
linux驱动开发-中断子系统
linux·运维·驱动开发
码哝小鱼1 小时前
firewalld封禁IP或IP段
linux·网络
鼠鼠龙年发大财1 小时前
【x**3专享】安装SSH、XFTP、XShell、ARM Linux
linux·arm开发·ssh
nfgo1 小时前
快速体验Linux发行版:DistroSea详解与操作指南
linux·ubuntu·centos
河南宽信李工1503806 16862 小时前
测绘航空摄影专项资质在洛阳市的获取流程
服务器
Rookie_explorers2 小时前
Linux下go环境安装、环境配置并执行第一个go程序
linux·运维·golang
学习向前冲2 小时前
AD域控服务器
运维·服务器
weixin_424215842 小时前
shell运算实战案例-KFC点餐系统
linux·centos