Ansible

一、简介

ansible官网:Ansible Documentation — Ansible Documentation

1.安装

yum install epel-release ansible libselinux-python -y

yum install ansible -y

2.配置机器组

vi /etc/ansible/hosts  #主机清单文件

编辑内容:

[web]
192.168.52.210
192.168.52.211
192.168.52.212

[nfs]
192.168.52.214

[backup]
192.168.52.215

 3.基于公私钥的认证:ssh-copy-id三步实现SSH无密码登录和ssh常用命令

#生成公钥和私钥
ssh-keygen
#将本机公钥发布至目标主机实现免密登录
ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.52.210

4.基于密码的认证

#如果目标机器的信息被修改,那么对应下面的信息也需要同步更新
[backup]
192.168.52.215 ansible_port=23 ansible_user=root #可省略 ansible_password='123456'

#修改密码
passwd

#修改端口
vi /etc/ssh/sshd_config

#修改完端口后需要重启服务
systemctl restart sshd

#查看修改后的设备端口信息
netstat -tunlp

 5.定义公共变量

#注意公共变量需要独占一行
[web:vars]
ansible_port=22999 
ansible_password=xxx

[web]
192.167.52.21[0:2] #等同于 192.168.52.210,192.168.52.211,192.168.52.212

6.ansible连接远程机器报错处理

 7.ansible具体有哪些模块

#模块语法
ansible 主机组 -m 命令模块 -a "需要批量执行的命令"

#查看ansible提供的模块
ansible-doc -l

#ansible模块总数 3387
ansible-doc -l |wc -l

8.ansible与shell的区别

二、模块

1.ping(检测目标机器是否存活)

#仅对web组服务器进行操作
ansible web -m ping
#对所有服务器组进行操作
ansible all -m ping
#筛选出问题的服务器
ansible all -m ping|grep UNREACHABLE

2.command(远程执行简单linux命令,不支持特殊符号)

#查看nasible在command模块下可以执行的命令
ansible-doc -s command

- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be
                               interpreted incorrectly (for example "user name"). Only the string or the list
                               form can be provided, not both.  One or the other must be provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.

简写,command是ansible的基础模块,默认就是 -m command 

#ansible 默认模块是command,即在没有指定 -m 时,默认是在 -m command模块下运行命令
ansible web -m command -a "hostname"
192.168.217.205 | CHANGED | rc=0 >>
CentOS7.8-clear
192.168.217.204 | CHANGED | rc=0 >>
CentOS7.8-clear


ansible web  -a "hostname"
192.168.217.205 | CHANGED | rc=0 >>
CentOS7.8-clear
192.168.217.204 | CHANGED | rc=0 >>
CentOS7.8-clear

常用命令:

ansible web -m command -a "useradd yuchao"

ansible web -m command -a "userdel yuchao"

ansible web -m command -a "touch  /opt/test.txt"

ansible web -m command -a "touch  /opt/test1.txt warn=false"

ansible web -m command -a "rm -rf  /opt/test1.txt warn=false"

ansible web -m command -a "cat  /opt/test.txt"

使用command提供的专有命令

ansible web -m command -a "tar -zcf /opt/log.tgz  /var/log chdir=/"

ansible web -m command -a "tar -zcvf /opt/log.tgz  /var/log chdir=/"

ansible web -m command -a "ls -l  /opt"


ansible web -a "tar -zcf /backup_config/etc.tgz  etc chdir=/ removes=/backup_config"
192.168.217.204 | SUCCESS | rc=0 >>
skipped, since /backup_config does not exist
192.168.217.205 | SUCCESS | rc=0 >>
skipped, since /backup_config does not exist

ansible web -a "mkdir -p /backup_config"

ansible web -a "tar -zcf /backup_config/etc.tgz  etc chdir=/ removes=/backup_config"

ansible web -a "ls /backup_config"

#查看文件大小
ansible web -a "ls /backup_config -l"

#如文件已经存在则不创建文件
ansible web -m command -a "mkdir /opt creates=/opt"

因为command不支持特殊符号,远程过滤进行信息,无法使用

想使用特殊符号,更复杂的linux命令用shell模块
虽然ansible提供了大量模块

万能模块shell

但是在学习阶段,还是尽量采用专有模块

3.shell(万能模块,支持特殊符号)

#查看ansible提供的所有模块
ansible-doc -l

#查看指定模块
ansible-doc -l |grep ^user

user                                                          Manage user accounts
#查看user模块有哪些功能
ansible-doc -s user

#查看管理应用启动等命令的模块
ansible-doc -l |grep ^system
systemd                                                       Manage services
#查看systemd模块有哪些功能
ansible-doc -s systemd

使用重定向符号创建文件

ansible web -m shell -a "date '+%F %T' > /tmp/date.log"

192.168.217.205 | CHANGED | rc=0 >>

192.168.217.204 | CHANGED | rc=0 >>


ansible web -m shell -a "cat /tmp/date.log"

192.168.217.204 | CHANGED | rc=0 >>
2023-05-23 17:15:05
192.168.217.205 | CHANGED | rc=0 >>
2023-05-23 17:15:05

远程执行复杂linux命令

ansible web -m shell -a "mkdir /2023/;echo 'hostname' >/2023/hostname.sh;chmod +x /2023/hostname.sh;/2023/hostname.sh; warn=false"

192.168.217.204 | CHANGED | rc=0 >>
CentOS7.8-clear
192.168.217.205 | CHANGED | rc=0 >>
CentOS7.8-clear

4.copy(批量分发文件、文件夹)

copy模块记录了文件属性,能够根据checksum(文件的md5值),得到了文件的唯一校验,判断文件内容是否变化,如果未变化则不做处理,提升批量管理的效率:

目标主机创建www用户,权限修改为600,属主属组修改为www

ansible web -m shell -a "useradd www"

ansible web -m copy -a "src=/tmp/61-dnf.log dest=opt/web-dnf.log group=www owner=www mode=600"

#查看所有文件
ansible web -a "ls -a /opt"

#查看文件大小及文件从属关系
ansible web -a "ls -l /opt"

#查看文件大小及文件从属关系
ansible web -m shell -a "ls -l /opt/web-dnf.log"

192.168.217.204 | CHANGED | rc=0 >>
-rw-------. 1 www www 24 5月  24 00:32 /opt/web-dnf.log
192.168.217.205 | CHANGED | rc=0 >>
-rw-------. 1 www www 24 5月  24 00:32 /opt/web-dnf.log

发送文件且先做好备份

使用backup参数,防止覆盖远程文件,丢失备份数据,提前备份该目标机器的数据

# 1.检查目标服务器的文件
ansible web -m shell -a "ls -l /opt/web-dnf.log"

#2.远程拷贝文件,且做好备份
ansible web -m copy -a "src=/tmp/61-dnf.log dest=/opt/web-dnf.log backup=yes"

#3.发现ansible帮你做好的备份
ansible web -m shell -a "ls -l  /opt/web*"
192.168.217.205 | CHANGED | rc=0 >>
-rw-------. 1 www www 112 5月  24 00:56 /opt/web-dnf.log
-rw-------. 1 www www  71 5月  24 00:52 /opt/web-dnf.log.9233.2023-05-24@00:56:23~
192.168.217.204 | CHANGED | rc=0 >>
-rw-------. 1 www www 112 5月  24 00:56 /opt/web-dnf.log
-rw-------. 1 www www  71 5月  24 00:52 /opt/web-dnf.log.9585.2023-05-24@00:56:28~

指定数据写入到远程文件中

ansible web -m copy -a "content='远离毒奶粉,好好学linux才是王道' dest=/opt/web-dnf.log backup=yes"
查看文件内容
ansible web -m shell -a "cat /opt/web-dnf.log"

复制文件夹,注意结尾斜杠

远程拷贝/opt/下的所有内容到目标服务器
ansible web -m copy -a "src=/opt/ dest=/tmp/"

远程拷贝/opt整个目录到目标服务器
ansible web -m copy -a "src=/opt dest=/tmp/"

查看目标服务器目录结构情况
ansible web -m shell -a "tree /tmp/"

192.168.52.211 | CHANGED | rc=0 >>
/tmp/
├── ansible_command_payload_iJqbpg
│   └── ansible_command_payload.zip
└── opt
    └── ansible.log

2 directories, 2 files
192.168.52.210 | CHANGED | rc=0 >>
/tmp/
├── ansible_command_payload_HSfGnH
│   └── ansible_command_payload.zip
└── opt
    └── ansible.log

2 directories, 2 files
192.168.52.212 | CHANGED | rc=0 >>
/tmp/
├── ansible_command_payload_j6QaRX
│   └── ansible_command_payload.zip
└── opt
    └── ansible.log

2 directories, 2 files

5 file文件操作模块

file模块主要用于创建文件、目录以及对现有的文件、目录权限进行修改,对文件属性做各种操作

查看文件帮助命令

ansible-doc -s file

创建文件

ansible web -m file -a "path=/opt/hello_ansible.log state=touch"

192.168.217.205 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/opt/hello_ansible.log", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
192.168.217.204 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/opt/hello_ansible.log", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
 

创建文件夹/目录

ansible web -m file -a "path=/opt/hello_ansible  state=directory"


192.168.217.204 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/opt/hello_ansible", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
192.168.217.205 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/opt/hello_ansible", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
 

 创建文件且设定文件权限

ansible web -m file -a "path=/opt/hello-linux.log state=touch owner=www group=www mode=777"

创建软链接文件

给web服务器组的 /etc/hosts文件,添加软链接到/opt/hosts文件

ansible web -m file -a "src=/etc/hosts dest=/opt/hosts state=link" 

强制性创建软链接

 ansible web -m file -a "src=/etc/hostsss dest=/opt/hosts state=link force=yes"


[WARNING]: Cannot set fs attributes on a non-existent symlink target. follow should be
set to False to avoid this.
192.168.217.205 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/opt/hosts", 
    "src": "/etc/hostsss"
}
192.168.217.204 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/opt/hosts", 
    "src": "/etc/hostsss"
}

修改已存在文件/文件夹的属性(属主、属组)

 ansible 192.168.217.204 -m file -a "path=/opt/hello_ansible owner=www group=www"


192.168.217.204 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 1000, 
    "group": "www", 
    "mode": "0755", 
    "owner": "www", 
    "path": "/opt/hello_ansible", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 1000
}

修改已存在的文件属性及权限

ansible 192.168.217.204 -m file -a "path=/opt/hello_ansible.log owner=www group=www mode=666"


192.168.217.204 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 1000, 
    "group": "www", 
    "mode": "0666", 
    "owner": "www", 
    "path": "/opt/hello_ansible.log", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}

关于file模块的所有参数作用

ansible.builtin.file module – Manage files and file properties — Ansible Documentation

关于file模块实例的用法

playbook剧本的写法,yaml写法

ansible.builtin.file module – Manage files and file properties — Ansible Documentation

6 script脚本模块

一键部署rsync,nfs,nginx等,两个流派:

1.把脚本发到目标机器上执行

2.在目标机器上远程执行命令,目标机器上不需要存在这个脚本

为什么要用script模块?

因为使用它可以远程执行脚本,可以记录每一次文件修改的状态,这个状态可以让你更清晰的了解文件的情况,也可以防止反复执行命令,提升效率。

1.本机编辑安装nginx脚本

vi install_nginx.sh

2.脚本内容

yum install nginx -y
#yum remove nginx -y
echo "ansible is importent"

3.本机脚本所在目录

/root/install_nginx.sh

4.远程在目标机器运行nignx脚本

ansible 192.168.52.210 -m script -a "/root/install_nginx.sh"


192.168.52.210 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.52.210 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.52.210 closed."
    ],
    "stdout": "已加载插件:fastestmirror\r\nLoading mirror speeds from cached hostfile\r\n * base: ftp.sjtu.edu.cn\r\n * extras: mirrors.ustc.edu.cn\r\n * updates: mirrors.ustc.edu.cn\r\n没有可用软件包 \u001b[1mnginx\u001b(B\u001b[m。\r\n错误:无须任何处理\r\nansible is importent\r\n",
    "stdout_lines": [
        "已加载插件:fastestmirror",
        "Loading mirror speeds from cached hostfile",
        " * base: ftp.sjtu.edu.cn",
        " * extras: mirrors.ustc.edu.cn",
        " * updates: mirrors.ustc.edu.cn",
        "没有可用软件包 \u001b[1mnginx\u001b(B\u001b[m。",
        "错误:无须任何处理",
        "ansible is importent"
    ]
}
 

 查看ansible命令执行过程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值