# 官方提供@yunTaoScripts Ansible 常用模块🔥🔥

loading

# 安装

# 配置

# 编写ansible.cfg

指定清单文件。如果当前目录有,则使用当前目录下ansible.cfg。当前目录没有,则使用/etc/ansible/ansible.cfg

  • ssh首次登录是否保留主机记录
[root@server1 ~]# cat  /etc/ssh/ssh_config | grep -i strict
StrictHostKeyChecking no

主机公钥确认 StrictHostKeyChecking

  • StrictHostKeyChecking=no 最不安全的级别,当然也没有那么多烦人的提示了,相对安全的内网测试时建议使用。如果连接server的key在本地不存在,那么就自动添加到文件中(默认是known_hosts),并且给出一个警告。
  • StrictHostKeyChecking=ask 默认的级别,就是出现刚才的提示了。如果连接和key不匹配,给出提示,并拒绝登录。
  • StrictHostKeyChecking=yes 最安全的级别,如果连接与key不匹配,就拒绝连接,不会提示详细信息。

未指定清单文件

[root@server1 ~]# ansible server2 -m ping
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
[WARNING]: Could not match supplied host pattern, ignoring: server2
  • 指定清单文件
[root@server1 ~]# mkdir ansible/;cd ansible/
[root@server1 ansible]# cat ansible.cfg 
[defaults]
# some basic default values...
inventory      = /root/ansible/hosts
[root@server1 ansible]# cat hosts 
server2
server3

未配置ssh免密登录,不指定用户默认当前用户去连接。

[root@server1 ansible]# ansible server2 -m ping
server2 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: root@server2: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}
  • 配置免密登录
[root@server1 ansible]# ssh-keygen -N "" -C server1 # N:指定密码
[root@server1 ansible]# ssh-copy-id server1
[root@server1 ansible]# ssh-copy-id server2
[root@server1 ansible]# ssh-copy-id server3

server1 公钥和 server2 authorized_keys 大体一致

[root@server1 ansible]# cat ~/.ssh/id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCy3v20k7Sm5eJ47YpVhmdlxV3NfDF+R+f0JLAWA/t7XJIePUGA2kBDtKVFbgInORBtEiQ1rL8JIiuldK/7WT8aM0ragBVmDsJJKjsIi/I0Q9NXT4hUT64Yfl8f00c43Vzsg4RkJhWooqn4iXXLxaDGnRfaRxflKbBGGRF4LtcUFoc5SIrnvyHz1/X0MA/tAQJCIJEoOHzeOoJGDOc1Iblj3KZvxhrwcis03Qt8P4HnTzX87cNpvWqldf40HIbjVfc9FQJrZBHdTvDPpp2h/Q5vjIjgCbN7WZ6UIVyg9aEbYin2Yn5zfMur3WlSPs/Z9rFLyV3+TWqL0sSSOapZK9qL/Duew5A3A5ISsxLTQc/tz4LFdIRtPI9hcP0gOTqepe+odqs15REoKiwvwpiqn5FuffRFBRjSicqShly/0HrbndKhGc3rf9HsYj6llxnbcspuFGnqb5T/sIzu7xefqugg2gx/gy+PJnE6amiOmsi2cCLX0pENaOcKEzN9SYH7cws= server1
[root@server2 .ssh]# cat authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCy3v20k7Sm5eJ47YpVhmdlxV3NfDFJJKjsIi/I0Q9NXT4hUT64Yfl8f00c43Vzsg4RkJhWooqn4iXXLxaDGnRfaRxflKbBGGP4HnTzX87cNpvWqldf40HIbjVfc9FQJrZBHdTvDPpp2h/Q5vjIjgCbN7WZ6UIVyg9aELFdIRtPI9hcP0gOTqepe+odqs15REoKiwvwpiqn5FuffRFBRjSicqShly/0HrbndKhGaOcKEzN9SYH7cws= server1
  • 验证成功
[root@server1 ansible]# ansible server2 -m ping
server2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
  • ansible.cfg 指定用户连接到 被管理机器
[root@server1 ansible]# cat ansible.cfg 
[defaults]

# some basic default values...

inventory      = /root/ansible/hosts
remote_user = yuntao
[root@server1 ansible]# ansible server2 -m shell -a 'whoami'
server2 | CHANGED | rc=0 >>
yuntao

  • 权限提升 从yuntao用户提升到root有2种方法
  1. 增加 --become
  2. 或者在 ansible.cfg增加配置文件。
[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False

被管机器没有配置sudo权限会报错

[root@server1 ansible]# ansible server2 -m shell -a 'whoami' --become
server2 | FAILED | rc=-1 >>
Missing sudo password

sudo配置方法

## Allow root to run any commands anywhere 
root    ALL=(ALL)       ALL

## Allows members of the 'sys' group to run networking, software, 
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL
  • 第一个ALL是指网络中的主机,我们后面把它改成了主机名,
  • 第二个括号里的ALL是指目标用户,也就是以谁的身份去执行命令。
  • 最后一个ALL当然就是指命令名了。
  • 配置server2 sudo权限后不报错
[root@server2 ~]# cat /etc/sudoers.d/yuntao 
yuntao        ALL=(ALL)       NOPASSWD: ALL
[root@server1 ansible]# ansible server2 -m shell -a 'whoami' --become
server2 | CHANGED | rc=0 >>
root

配置普通用户无密码登录 root 机器

[yuntao@server1 ~]$ ssh-copy-id root@server2
[yuntao@server1 ~]$ ssh-copy-id root@server3
  • 在本机执行和在所有清单文件执行。
[root@server1 ansible]# ansible all -m shell -a 'whoami' 
server2 | CHANGED | rc=0 >>
yuntao
server3 | CHANGED | rc=0 >>
yuntao
[root@server1 ansible]# ansible localhost -m shell -a 'whoami' 
localhost | CHANGED | rc=0 >>
root

# 编写清单文件

所有要管理的机器必须写入清单文件。

  • hosts清单文件
station2 
workstation 
[aa]
station2 
workstation 
[bb] 
station[62:63]   # 指定62到63的机器

[xx:children]    #指定aa 和 bb 服务器组
aa
bb
[dd]
station ansible_ssh_port=222 # 指定ssh 端口
workstation ansible_ssh_user=tom
  • 列出组下面的主机
[root@server1 ansible]# ansible aa --list-hosts
  hosts (2):
    station2
    workstation
[root@server1 ansible]# ansible bb --list-hosts
  hosts (2):
    station62
    station63
[root@server1 ansible]# ansible xx --list-hosts
  hosts (4):
    station2
    workstation
    station62
    station63

# 常见模块的使用

查看模块解释

[root@server1 ansible]# ansible-doc command
[root@server1 ansible]# ansible-doc -l # 查看所有模块

# 1. ping

# 2. shell -a ""

# 3. command -a "" , # 默认模块

和shell 模块 区别

commad模块相较于shell模块 有些限制。

# 4. scripts -a "./test.sh" # 执行脚本。

# 5. get_url 下载文件

  • 下载文件到opt目录
[root@server1 ansible]# ansible xyt -m get_url -a 'url=ftp://server1/ansible_el8.tar.gz dest=/opt group=chrony owner=yuntao mode=4000' 
server2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum_dest": null,
    "checksum_src": "955db3eb081d90e812d01c2d67dc67e152af07c3",
    "dest": "/opt/87c01ec7gy1frmmvgfmw3j21kw0w04r1.jpg",
    "elapsed": 0,
    "gid": 0,
    "group": "root",
    "md5sum": "ba7b2e8764deceeec1d02dae116df484",
    "mode": "0644",
    "msg": "OK (1144733 bytes)",
    "owner": "root",
    "size": 1144733,
    "src": "/root/.ansible/tmp/ansible-tmp-1659418701.3280299-225829545669144/tmpviy7eion",
    "state": "file",
    "status_code": 200,
    "uid": 0,
    "url": "https://api.ixiaowai.cn/gqapi/gqapi.php"
}
[root@server2 ~]# ll /opt/
total 21512
---S------ 1 yuntao chrony 22025386 Aug  2 13:58 ansible_el8.tar.gz
  • 禁用 warning 提示 set 'command_warnings=False' in ansible.cfg
[root@server1 ansible]# ansible xyt -m shell -a 'rm -rf /opt/*'
[WARNING]: Consider using the file module with state=absent rather than running 'rm'.  If you need to use command because file is
insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.
server2 | CHANGED | rc=0 >>

server3 | CHANGED | rc=0 >>

# 6. debug用于打印信息

[root@server1 ansible]# ansible xyt -m debug -a 'msg=hah'
server3 | SUCCESS => {
    "msg": "hah"
}
server2 | SUCCESS => {
    "msg": "hah"
}

# 7. 创建或者删除组

  • 创建组
[root@server2 ~]# grep group /etc/group
group1:x:2011:
[root@server1 ansible]# ansible xyt -m group -a "name=group1 state=present"  
server2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 2011,
    "name": "group1",
    "state": "present",
    "system": false
}

  • 删除组
[root@server1 ansible]# ansible xyt -m group -a "name=group1 state=absent"
server2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "name": "group1",
    "state": "absent"
}
[root@server2 ~]# grep group /etc/group

# 8. 用户管理

user -a "name comment group groups passwd={{'密码'passwd_hash('sha512')}} present/absent" 
  • 创建用户
[root@server1 ansible]#  ansible xyt -m user -a "name=haha group=root groups=chrony comment='what a sham' password={{'red'|password_hash('sha512')}}"
  • 删除用户
[root@server1 ansible]#  ansible xyt -m user -a "name=haha state=absent remove=true" # remove 删除家目录

# 9. 文件管理

创建链接,目录,文件,修改权限

ansible server3 -m file -a "path=/opt/aa state=touch owner=yuntao chrony mode=0444 setype=httpd_sys_content_t"
ansible server3 -m file -a "path=/opt/aa.txt state=touch owner=yuntao chrony mode=0444 setype=httpd_sys_content_t"
cat /etc/yum.repos.d/iso.repo 
ansible server3 -m file -a "path=/opt/aa.txt state=touch owner=yuntao chrony mode=0444 setype=httpd_sys_content_t"
ansible server3 -m file -a "path=/opt/aa.txt state=touch owner=yuntao chrony mode=4444 setype=httpd_sys_content_t"
ansible server3 -m file -a "path=/opt/aa.txt state=touch owner=yuntao chrony mode=4544 setype=httpd_sys_content_t"
ansible server3 -m file -a "src= /opt/aa.txt path=/opt/bb state=link"
ansible server3 -m file -a "src=/opt/aa.txt path=/opt/bb state=link"
ansible server3 -m file -a "src=/opt/aa.txt path=/opt/cc state=hard"
ansible server3 -m file -a "path=/opt/bb state=absent"
ansible server3 -m file -a "path=/opt/cc state=file owner=root group=root 00"
ansible server3 -m file -a "path=/opt/xxx state=directory"
ansible server3 -m file -a "path=/opt/xxx state=directory owner=yuntao root mode=000"
ansible server3 -m file -a "path=/opt/xxx state=absent"
ansible server3 -m file -a "path=/opt/xxx state=directory owner=yuntao root mode=000"
ansible server3 -m file -a "src=/etc/hosts dest=/opt/ owner=yuntao group=root mode=000"

# 10. copy

ansible server3 -m copy -a "src=/etc/hosts dest=/opt/ owner=yuntao root mode=000"
ansible server3 -m copy -a "dest=/opt/hosts content='hah'"

# 11. fetch

ansible server3 -m fetch -a "src=/etc/hosts dest=./"
ansible all -m fetch -a "src=/etc/hosts dest=./"

# 12. setup

  • 获取系统信息
[root@server1 ansible]# ansible server3 -m setup -a 'filter=ansible_default_ipv4'
server3 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "192.168.26.131",
            "alias": "ens160",
            "broadcast": "192.168.26.255",
            "gateway": "192.168.26.2",
            "interface": "ens160",
            "macaddress": "00:0c:29:45:9f:bc",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.26.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
# 获取子参数
[root@server1 ansible]# ansible server3 -m setup -a 'filter=ansible_default_ipv4.addresss'
server3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

不显示子参数

虽然子参数不显示,但是是能获取到的。

# 13. yum_repository

ansible xyt -m yum_repository -a "name=AppStream description='this is appstream' baseurl='ftp://192.168.26.129/pub/AppStream' enabled=yes gpgcheck=no"
ansible xyt -m yum_repository -a "name=BaseOS description='this is baseos' baseurl='ftp://192.168.26.129/pub/BaseOS' enabled=1 gpgcheck=0"
setenforce 0

# 14. yum/package

  • 安装包
ansible xyt -m yum -a "name=vsftpd state=absent"
ansible xyt -m yum -a "name=vsftpd state=present"
# 如果没有yum,比如ubuntu,使用package
ansible xyt -m package -a "name=vsftpd state=absent"  
ansible xyt -m package -a "name=vsftpd state=present"

# 15. service/systemd

ansible xyt -m service -a "name=vsftpd state=started enabled=yes"
ansible xyt -m service -a "name=vsftpd state=stoped enabled=yes"
ansible xyt -m service -a "name=vsftpd state=stopped enabled=yes"

# 16. systemd

如果修改了启动文件,此时需要daemon_reload

[root@server3 ~]# systemctl restart vsftpd.service Warning: The unit file, source configuration file or drop-ins of vsftpd.service changed on disk. Run 'systemctl daemon-reload' to reload units.

ansible xyt -m systemd -a "name=vsftpd daemon_reload=yes"

# 17. firewalld


# 18. replace

# 替换文件中字符
ansible server3 -m replace -a 'path=/opt/aa.txt regexp=^aa replace=bb=22'
[root@server3 opt]# echo 'aa=122' > aa.txt
[root@server3 opt]# cat aa.txt 
bb=22=122

# 19. lineinfile

# 替换文件中的行
ansible server3 -m lineinfile -a 'path=/opt/aa.txt regexp=^bb line=bb=22'
[root@server3 opt]# cat aa.txt 
bb=22

总结:

replace是对字符进行替换,lineinfile是对行进行替换,如果replace要想对行进行替换 的话,在regexp后面必须要写上正则来表示一整行内容。

# 20. parted 分区

  • 创建分区
ansible server3 -m parted -a 'device=/dev/sdb number=3 part_start=7.8GiB part_end=10GiB state=present'
ansible server3 -m parted -a 'device=/dev/sdb number=3 state=absent'

# 21. filesystem 格式化

[root@server1 ansible]# ansible server3 -m filesystem -a 'device=/dev/sdb3 fstype=xfs'
server3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true
}

  • 如果要更换文件系统需要加 --force
root@server1 ansible]# ansible server3 -m filesystem -a 'device=/dev/sdb3 fstype=ext4 force=yes'
server3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true
}

# 22. mount


ansible server3 -m mount -a 'src=/dev/sdb3 path=/xx fstype=ext4 state=mounted'
ansible server3 -m mount -a 'src=/dev/sdb3 path=/xx fstype=ext4 state=unmounted'
ansible server3 -m mount -a 'src=/dev/sdb3 path=/xx fstype=ext4 state=present'
ansible server3 -m mount -a 'src=/dev/sdb3 path=/xx fstype=ext4 state=absent'

state 参数解释

  1. mounted:挂载并写入fstab
  2. umounted:只卸载
  3. present:只写入fstab
  4. absent:卸载并删除fstab

# 23. lvg

  • 创建VG
ansible server3 -m lvg -a 'vg=vg1 pvs=/dev/sdb1,/dev/sdb2,/dev/sdb3  state=present'
ansible server3 -m lvg -a 'vg=vg1 pvs=/dev/sdb1,/dev/sdb2,/dev/sdb3  state=absent'
ansible server3 -m lvg -a 'vg=vg1 pvs=/dev/sdb1,/dev/sdb2,/dev/sdb3 pesize=8 state=absent'
ansible server3 -m lvg -a 'vg=vg1 pvs=/dev/sdb1,/dev/sdb2,/dev/sdb3 pesize=8 state=present'

# 24. lvol

  • 创建删除lv
ansible server3 -m lvol -a 'vg=vg1 lv=lv0 size=300M state=present'

ansible server3 -m lvol -a 'vg=vg1 lv=lv0 state=absent force=yes'
最后修改时间: 12/31/2022, 12:00:03 PM