关于ansible:ansible使用笔记二常用命令使用及常用模块介绍

21次阅读

共计 9796 个字符,预计需要花费 25 分钟才能阅读完成。

一、常用命令应用

后面有提到过 ansible 的罕用的命令和应用
列出要执行主机
ansible all –list-hosts
批量检测主机
ansible all -m ping -k
ansible 主机汇合 -m 模块名称 -a 模块参数

主机汇合 主机名或分组名, 多个应用 "逗号" 分隔
-m 模块名称, 默认 command 模块
-a or --args 模块参数

其它参数
-i inventory 文件门路, 或可执行脚本
-k 应用交互式登陆密码
-e 定义变量
-v 显示详细信息

二、双引号 ” ” 单引号 ’ ‘ 对执行后果的影响

执行以下命令来查看 ansible 的执行后果
1)shell
ansible web -m shell -a “echo ${HOSTNAME}”
ansible web -m shell -a ‘echo ${HOSTNAME}’
2)创立的文件在哪查看
ansible cache -m shell -a ‘cd /tmp’
ansible cache -m shell -a ‘touch testfile’

[root@ansible ~]# ansible  web  -m shell -a "echo \${HOSTNAME}"
web1 | CHANGED | rc=0 >>
ansible                // 能够看到应用双引号 "echo \${HOSTNAME}" 显示的是本机的主机名
web2 | CHANGED | rc=0 >>
ansible
[root@ansible ~]# ansible  web  -m shell -a 'echo \${HOSTNAME}'
web2 | CHANGED | rc=0 >>
web2                  // 应用单引号 'echo \${HOSTNAME}' 显示的才是近程主机名 才是咱们想要的后果
web1 | CHANGED | rc=0 >>
web1
[root@ansible ~]# ansible cache -m shell -a 'cd /tmp'
cache | CHANGED | rc=0 >>

[root@ansible ~]# ansible cache -m shell -a 'touch testfile'
[root@ansible ~]# ssh cache
[root@cache ~]# ll
总用量 4
drwxr-xr-x 2 root root  6 4 月  13 2019 Desktop
-rw-r--r-- 1 root root 55 10 月 20 15:04 resolv.conf
-rw-r--r-- 1 root root  0 10 月 29 15:25 testfile              // 创立的文件在家目录下 并没有在 /tmp 目录下

注:
1)变量解析 双引号 ”” 与单引号 ” 应用区别
ansible 执行命令是二次解析,第一次在本机解析, 第二次在执行机器解析,须要第二次解析的变量要转移
总结:  参数默认应用 ‘ ‘ 号就对了

2)创立的文件在哪里
文件在用户家目录,ansible 是应用 ssh 屡次连贯执行,连贯退出当前之前的状态就全副生效了
解决办法:应用 chdir 代替 cd 命令
ansible cache -m shell -a ‘chdir=/tmp touch testfile’

三、ansible-console 工具

是 ansible 为用户提供的交互式工具, 用户能够在 ansible-console 虚构进去的终端进去的终端上像 shell 一样应用 ansible 内置的各种命令, 这为习惯应用 shell 交互方式的用户提供了良好的应用体验

[root@ansible ~]# ansible-console        // 对所有主机执行操作
[root@ansible ~]# ansible-console  db    // 对 db 组主机执行操作
Welcome to the ansible console.
Type help or ? to list commands.

root@db (2)[f:5]$ pwd                   // 和失常在 shell 下操作一样
db1 | CHANGED | rc=0 >>
/root
db2 | CHANGED | rc=0 >>
/root

root@db (2)[f:5]$ cat /etc/hosts
db1 | CHANGED | rc=0 >>
# ::1        localhost localhost.localdomain localhost6 localhost6.localdomain6
127.0.0.1    localhost localhost.localdomain localhost4 localhost4.localdomain4
db2 | CHANGED | rc=0 >>
# ::1        localhost localhost.localdomain localhost6 localhost6.localdomain6
127.0.0.1    localhost localhost.localdomain localhost4 localhost4.localdomain4

root@db (2)[f:5]$ cat /etc/hostname
db1 | CHANGED | rc=0 >>
db1
db2 | CHANGED | rc=0 >>
db2
root@db (2)[f:5]$ ls
db2 | CHANGED | rc=0 >>
abc.txt
Desktop
haha
resolv.conf
......

四、ansible 罕用模块

4.1 ) ansible-doc 和 ping 模块

ansible-doc 模块手册
模块的手册相当于 shell 的 man, 很重要

  • ansible-doc -l 列出所有模块
  • ansible-doc modulename 查看帮忙

ping 模块
测试网络连通性,ping 模块没有参数
注: 测试 ssh 连通性

  • ansible host-pattern -m ping

4.2 ) command 模块

默认模块, 近程执行命令
用法

  • ansible host-pattern -m command -a ‘[args]’

command 模块注意事项:
该模块通过 - a 跟上要执行的命令能够间接执行, 若命令里有如下字符则执行不胜利
“<” “>” “|” “&”
command 模块不能解析零碎变量
该模块不启动 shell 间接在 ssh 过程中执行, 所有应用到 shell 的命令执行都会失败

  • ansible all -m command -a ‘ps aux|grep ssh’
  • ansible all -m command -a ‘set’

查看所有机器负载

  • ansible all -m command -a ‘uptime’

查看日期和工夫

  • ansible all -m command -a ‘date +%F_%T’

4.3 )shell 模块

shell 模块用法根本和 command 一样, 区别是 shell 模块是通过 /bin/sh 进行执行命令, 能够执行任意命令
不能执行交互式的命令, 例如 vim top 等

[root@ansible ~]# ansible web1 -m shell -a 'useradd by'
web1 | CHANGED | rc=0 >>

[root@ansible ~]# ansible web1 -m shell -a 'echo 123|passwd --stdin by'
web1 | CHANGED | rc=0 >>
更改用户 by 的明码。passwd:所有的身份验证令牌曾经胜利更新

[root@ansible ~]# ssh -l by web1
by@web1's password: 
[by@web1 ~]$

4.4 ) script 模块

命令太简单?
在本地写脚本, 而后应用 script 模块指量执行
ansible web -m script -a ‘urscript’
留神: 该脚本蕴含但不限于 shell 脚本, 只有指定 sha-bang 解释器的脚本都可运行

案例:
给所有 web 主机增加用户 wk
1. 要求 by 用户与 wk 用户不能呈现在同一台主机上
2. 设置 wk 用户的明码是 456

[root@ansible ~]# cat a.sh 
#!/bin/bash
id by
if [$? != 0];then
    useradd wk
    echo 456|passwd --stdin wk
fi

[root@ansible ~]# ansible web -m script -a '/root/a.sh'
web1 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to web1 closed.\r\n", 
    "stderr_lines": ["Shared connection to web1 closed."], 
    "stdout": "uid=1000(by) gid=1000(by) 组 =1000(by)\r\n",             // 提醒 by 用户已存在
    "stdout_lines": ["uid=1000(by) gid=1000(by) 组 =1000(by)"
    ]
}
web2 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to web2 closed.\r\n", 
    "stderr_lines": ["Shared connection to web2 closed."], 
    "stdout": "id: by: no such user\r\n 更改用户 wk 的明码。\r\npasswd:所有的身份验证令牌曾经胜利更新。\r\n", 
    "stdout_lines": [
        "id: by: no such user", 
        "更改用户 wk 的明码。", 
        "passwd:所有的身份验证令牌曾经胜利更新。"       // 增加 wk 用户 设置明码 456
    ]
}

[root@ansible ~]# ssh web1 ls /home
by
[root@ansible ~]# ssh web1 id by
uid=1000(by) gid=1000(by) 组 =1000(by)
[root@ansible ~]# ssh web1 id wk
id: wk: no such user

[root@ansible ~]# ssh web2 id by
id: by: no such user
[root@ansible ~]# ssh web2 id wk
uid=1000(wk) gid=1000(wk) 组 =1000(wk)

4.5 ) yum 模块

应用 yum 包管理器来治理软件包
name: 要进行操作的软件包名字
state: 动作(installed 装置、removed 删除)

4.6 ) service 模块

name: 必须项, 服务名称
enabled: 是否开机启动 yes|no
sleep: 执行 restarted, 会在 stop 和 start 之间沉睡几秒钟
state: 对过后服务执行启动、进行、重启中、从新加载等操作(started,stopped,restarted,reloaded)
案例:
1. 给 db 组装置 mariadb
2. 开启 mariadb 服务并设置开机启动

[root@ansible ~]# ansible db -m yum -a 'name="mariadb-server"state=installed'    \\ 给所有 db 主机装置 mariadb
[root@ansible ~]# ansible db -m service -a 'name="mariadb"enabled="yes"state="started"'   \ 开启服务并设置开机启动
[root@ansible ~]# ssh db1 "systemctl status mariadb"             // 检测服务是否开启
● mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since 一 2020-10-26 17:21:11 CST; 3 days ago
  Process: 852 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 794 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 851 (mysqld_safe)
   CGroup: /system.slice/mariadb.service
           ├─851 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           └─996 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/lib/mysql/db1.err --pid-file=db1.pid

10 月 26 17:21:04 db1 systemd[1]: Starting MariaDB database server...
10 月 26 17:21:05 db1 mysqld_safe[851]: 201026 17:21:05 mysqld_safe Logging to '/var/lib/mysql/db1.err'.
10 月 26 17:21:06 db1 mysqld_safe[851]: 201026 17:21:06 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
10 月 26 17:21:11 db1 systemd[1]: Started MariaDB database server.

4.7 ) copy 模块

复制文件到近程主机
src: 复制本地文件到近程主机, 绝对路径和相对路径都能够, 门路为目录时会递归复制, 若门路以 ”/” 结尾, 只复制目录里的内容, 若不以 ”/” 结尾, 则复制蕴含目录在内的整个内容, 相似于 rsync

dest: 必须项, 近程主机的绝对路径, 如果源文件是一个目录, 那该门路必须是目录

backup: 笼罩前先备份原文件, 备份文件蕴含工夫信息, 有两个选项:yes|no

force: 若指标主机蕴含该文件, 但内容不同, 如果设置为 yes, 则强制笼罩, 设为 no, 则只有当指标主机的指标地位不存在该文件时才复制, 默认为 yes

案例:
拷到本机 /etc/resolv.conf 文件到所有拖管主机 并对原文件备份
给所有 db 主机开启 binlog 日志

[root@ansible ~]# ansible all -m shell -a 'cat /etc/resolv.conf'
web2 | CHANGED | rc=0 >>
; generated by /usr/sbin/dhclient-script
search vbr
nameserver 192.168.1.254
web1 | CHANGED | rc=0 >>
; generated by /usr/sbin/dhclient-script
search vbr
nameserver 192.168.1.254
......

[root@ansible ~]# ansible all -m copy -a 'src=/etc/resolv.conf dest=/etc/resolv.conf backup='yes''db2 | CHANGED => {"ansible_facts": {"discovered_interpreter_python":"/usr/bin/python"},"backup_file":"/etc/resolv.conf.3512.2020-10-30@11:31:52~",           // 备份文件门路"changed": true,"checksum":"7ab5654c93c18a1dd208eaadbb30428367315504","dest":"/etc/resolv.conf","gid": 0,"group":"root","md5sum":"db739b8728e142b7894ef64608a83d8c","mode":"0644","owner":"root","size": 55,"src":"/root/.ansible/tmp/ansible-tmp-1604028710.47-8488-12200601987494/source","state":"file","uid": 0
}
db1 | CHANGED => {
    "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, 
    "backup_file": "/etc/resolv.conf.3603.2020-10-30@11:31:51~", 
    "changed": true, 
    "checksum": "7ab5654c93c18a1dd208eaadbb30428367315504", 
    "dest": "/etc/resolv.conf", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "db739b8728e142b7894ef64608a83d8c", 
    "mode": "0644", 
    "owner": "root", 
    "size": 55, 
    "src": "/root/.ansible/tmp/ansible-tmp-1604028710.43-8485-88071037096399/source", 
    "state": "file", 
    "uid": 0
}
......

[root@ansible ~]# ansible all -m shell -a 'cat /etc/resolv.conf'
web2 | CHANGED | rc=0 >>
# Generated by NetworkManager
nameserver 192.168.44.54
db1 | CHANGED | rc=0 >>
# Generated by NetworkManager
nameserver 192.168.44.54
web1 | CHANGED | rc=0 >>
......

[root@ansible ~]# ssh web1 "ls /etc/resolv.conf.4369.2020-10-30@11:31:52~"
/etc/resolv.conf.4369.2020-10-30@11:31:52~

[root@ansible ~]# vim /root/my.cnf     // 编写配置文件
[mysqld]
log-bin=mysql-bin
binlog-format=mixed

[root@ansible ~]# ansible db -m copy -a 'src=/root/my.cnf dest=/etc/my.cnf'
[root@ansible ~]# ansible db -m service -a 'name="mariadb"enabled="yes"state="restarted"'
[root@ansible ~]# ssh db1 cat /etc/my.cnf
[mysqld]
log-bin=mysql-bin
binlog-format=mixed

4.8 ) lineinfile 模块 replace 模块

相似 sed 的一种行编辑替换模块
path 指标文件文件
regexp 正则表达式, 要批改的行
line 最终批改的后果

replace 模块
相似 sed 的一种行编辑替换模块
path 指标文件文件
regexp 正则表达式, 要批改的行
replace 替换后的后果

lineinfile 模块与 replace 模块区别
lineinfile 模块 是批改某个文件的单行并进行替换
replace 模块 是批改某个文件的所有匹配行并进行替换

[root@ansible ~]# cat abc.txt 
AAABBBCCC
DDDEEEFFF
AAABBBCCC
DDDEEEFFF

ansible all -m copy -a 'src=/root/abc.txt dest=/root/abc.txt'

[root@ansible ~]# ansible all -m replace -a 'path="/root/abc.txt"regexp="AAA"replace="ZZZ"'[root@ansible ~]# ansible all -m shell -a"cat /root/abc.txt"
cache | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
ZZZBBBCCC
DDDEEEFFF
db2 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
ZZZBBBCCC
DDDEEEFFF
db1 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
ZZZBBBCCC
DDDEEEFFF
web2 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
ZZZBBBCCC
DDDEEEFFF
web1 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
ZZZBBBCCC
DDDEEEFFF

[root@ansible ~]# ansible all -m lineinfile  -a 'path="/root/abc.txt"regexp="ZZZ"line="YYY"'[root@ansible ~]# ansible all -m shell -a"cat /root/abc.txt"
web2 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
YYY
DDDEEEFFF
web1 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
YYY
DDDEEEFFF
db2 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
YYY
DDDEEEFFF
db1 | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
YYY
DDDEEEFFF
cache | CHANGED | rc=0 >>
ZZZBBBCCC
DDDEEEFFF
YYY
DDDEEEFFF

4.9 ) setup 模块

次要用于获取主机信息,playbooks 里常常会用的另一个参数 gather_facts 与该模块相干,setup 模块下常常用的是 filter 参数

filter 过滤所需信息

执行以下命令可查看蕴含的所有信息, 可大抵浏览一遍, 蕴含的信息,
须要留神的是 filter 过滤条件必须以信息中模块名为过滤条件 模块中详细信息不能为过滤条件

[root@ansible ~]# ansible cache -m setup 
[root@ansible ~]# ansible cache -m setup -a 'filter=ansible_distribution'
cache | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution": "CentOS", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

[root@ansible ~]# ansible db1 -m setup -a 'filter=ansible_date_time'
db1 | SUCCESS => {
    "ansible_facts": {
        "ansible_date_time": {
            "date": "2020-10-30", 
            "day": "30", 
            "epoch": "1604039910", 
            "hour": "14", 
            "iso8601": "2020-10-30T06:38:30Z", 
            ......


[root@ansible ~]# ansible db1 -m setup -a 'filter=ansible_default_ipv4'
db1 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "192.168.4.143", 
            "alias": "eth0", 
            "broadcast": "192.168.4.255", 
            "gateway": "192.168.4.254", 
            "interface": "eth0", 
            "macaddress": "52:54:00:ef:6e:df
            ......

[root@ansible ~]# ansible db1 -m setup |grep 192.168  \\ 如果晓得信息的一部分能够用 grep 搜寻
            "192.168.4.143"
            "address": "192.168.4.143", 
            "broadcast": "192.168.4.255", 
            "gateway": "192.168.4.254", 
            "network": "192.168.4.0", 
                "192.168.44.54"

正文完
 0