Ansible的安装和使用

学习资料

http://www.ansible.com.cn/

 

一、安装

#安装源
# 1.安装
yum install epel-release -y 
yum install ansible -y

# 2.生成公钥
[root@vm01 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:3qbJMAm75****QKNHV/kZLRjAyWT6********gdMQG2M root@vm01
The key is randomart image is:
+---[RSA 3072]----+
|         .++E*o. |
|        . .X==.  |
|       ..  *O.   |
|       +.++o=o   |
|    . o Sooo     |
|     o = . .     |
|    . * + +      |
|     = * =       |
|    . o +        |
+----[SHA256]-----+

# 3.发送公钥到目标服务器
ssh-copy-id 127.0.0.1
ssh-copy-id 182.43.xx.xx

二、配置使用

1、基本信息使用


# 查看版本
ansible --version
# 配置文件目录
/etc/ansible
# 配置目标服务器
 vim /etc/ansible/hosts
# 按照组来划分服务器,配置文件中添加
[alihost]
182.43.xx.xx

2、功能使用

# 1、远程执行命令
[root@vm01 ansible]# ansible alihost -m command -a "df -h"
182.43.xx.xx | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        989M     0  989M   0% /dev
tmpfs          1000M  8.0K 1000M   1% /dev/shm
tmpfs          1000M  113M  887M  12% /run
tmpfs          1000M     0 1000M   0% /sys/fs/cgroup
/dev/vda1        40G   12G   29G  30% /
/dev/loop0      2.4G  2.4G     0 100% /home/KingbaseESV8
tmpfs           200M     0  200M   0% /run/user/0

# 2、批量发送文件
[root@vm01 ~]# ansible alihost -m copy -a "src=/root/111.txt dest=/tmp/"
182.43.xx.xx | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "53f649f4353ba3d7de0d1b47c094a1428f6ee676",
    "dest": "/tmp/111.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "1dc889cf64d32898b9c210dfa60f63f3",
    "mode": "0644",
    "owner": "root",
    "size": 24,
    "src": "/root/.ansible/tmp/ansible-tmp-1758525584.353497-2689-100513080225535/source",
    "state": "file",
    "uid": 0
}


#以peng用户执行ping存活检测
ansible all -m ping -u peng  -k

#以peng sudo至root执行ping存活检测
ansible all -m ping -u peng -k -b

#以peng sudo至xiao用户执行ping存活检测
ansible all -m ping -u peng -k -b --become-user=xaio

#以peng sudo至root用户执行ls 
ansible all -m command  -u peng -a 'ls /root' -b --become-user=root -k -K 

 

1、常用模块

Command 模块
#功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项
Shell 模块
#功能:和 command 相似,用 shell 执行命令 , 支持各种符号 , 比如 :*,$, >
Script 模块
#功能:在远程主机上运行 ansible 服务器上的脚本 ( 无需执行权限 )
Copy 模块
#功能:从 ansible 服务器主控端复制文件到远程主机
Get_url 模块
#功能 : 用于将文件从 http 、 https 或 ftp 下载到被管理机节点上
File 模块
#功能:设置文件属性 , 创建软链接等
stat 模块
#功能:检查文件或文件系统的状态
Hostname 模块
#功能:管理主机名
Cron 模块
#功能:计划任务
#支持时间: minute , hour , day , month , weekday
Yum 和 Apt 模块
#功能:
#yum 管理软件包,只支持 RHEL , CentOS , fedora ,不支持 Ubuntu 其它版本
#apt 模块管理 Debian 相关版本的软件包
Service 模块
#功能:管理服务
User 模块
#功能:管理用户
。。。。。。。。。。。。。。。。。。。

 

2、YAML 语言

 。。

 

posted @ 2025-09-22 15:40  大司徒  阅读(10)  评论(0)    收藏  举报