ANSIBLE 模块(Group、User、Copy、File、Fetch、Cron、Command、Yum、Script、Setup、Service等)和 ANISIBLE 三种变量的综合示例

这篇博客详细介绍了如何使用Ansible进行组管理、用户创建、文件复制、命令执行等操作,并通过实例演示了各种模块的用法,包括Group、User、Copy、File、Cron、Command、Yum、Service等。同时,还涵盖了Ansible的变量使用,包括Hosts文件定义变量和命令中引用变量的示例。
摘要由CSDN通过智能技术生成

1、组网拓扑

在这里插入图片描述

2、进行 Ansible 基本配置(添加 hosts)

2.1 添加组名为 webservers ,并进行主机添加

[root@Tang ~]# yum install -y ansible      # 安装 ansible
[root@Tang ~]# ansible --version           # 确认 ansible 是否安装
ansible 2.8.5
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
[root@Tang ~]# ansible --help              # 查看命令帮助
[root@Tang ~]# cat /etc/ansible/hosts | grep testserver -A 2
[testserver]
172.16.141.209
172.16.141.253

2.2 创建密钥,用于免认证登陆 hosts 主机

[root@Tang ~]# ssh-keygen -t rsa -P ""                                 # 先创建密钥
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
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:YGLI/OM6g0BRdDgHaVcCcKTOg6t2nxDhZ9CWmCVipw0 root@Tang
The key's randomart image is:
+---[RSA 2048]----+
| E=X=+..         |
|.+O*Boo          |
| o***+o          |
|+..o+o .         |
|o+ ooo  S        |
|....+.           |
|o. ..            |
|o.oo. .          |
|o oo.o           |
+----[SHA256]-----+

2.3 添加主机 Tang-1(172.16.141.209),并进行登陆验证

[root@Tang ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.141.209    # 添加无密码认证登陆密钥
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@172.16.141.209's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@172.16.141.209'"
and check to make sure that only the key(s) you wanted were added.


[root@Tang ~]# ssh root@172.16.141.209                 # 验证无密码登陆
Last login: Wed Jan  1 09:09:38 2014 from 172.16.141.252
[root@Tang-1 ~]# ip addr list | grep enp1s0            # 可以成功登陆
2: enp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    inet 172.16.141.209/24 brd 172.16.141.255 scope global noprefixroute enp1s0

2.4 添加主机 Tang-2(172.16.141.253),并进行登陆验证

[root@Tang ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.141.253
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@172.16.141.253's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@172.16.141.253'"
and check to make sure that only the key(s) you wanted were added.

[root@Tang ~]# ssh root@172.16.141.253
Last login: Wed Oct 16 14:15:45 2019 from 172.16.141.99
[root@Tang-2 ~]# ifconfig enp1s0
enp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.16.141.253  netmask 255.255.255.0  broadcast 172.16.141.255

2.5 进行主机列表查看和 ping 测试

[root@Tang ~]# ansible all --list-hosts
  hosts (2):
    172.16.141.209
    172.16.141.253
[root@Tang ~]# ansible all -m ping -C        # 进行 dryrun ping 测试
172.16.141.253 | SUCCESS => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
172.16.141.209 | SUCCESS => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

3、查看所有模块

[root@Tang ~]# ansible-doc --help    # 查看 ansible 模块
[root@Tang ~]# ansible-doc -l        # 查看所有模块

4、各个 Ansible 模块示例讲解

4.1 Group

4.1.2 查看帮助和添加组

[root@Tang ~]# ansible-doc -s group  # 查看 group 模块的帮助
- name: Add or remove groups
  group:
      gid:                   # Optional `GID' to set for the group.
      local:                 # Forces the use of "local" command alternatives on platforms that implement it. This is useful in
                               environments that use centralized authentication when you want to
                               manipulate the local groups. (e.g. it uses `lgroupadd' instead of
                               `groupadd'). This requires that these commands exist on the targeted
                               host, otherwise it will be a fatal error.
      name:                  # (required) Name of the group to manage.
      non_unique:            # This option allows to change the group ID to a non-unique value. Requires `gid'. Not supported on
                               macOS or BusyBox distributions.
      state:                 # Whether the group should be present or not on the remote host.
      system:                # If `yes', indicates that the group created is a system group.

[root@Tang ~]# ansible all -m group -a "gid=3000 name=mygrp state=present  system=no"    # 创建组
172.16.141.253 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 3000, 
    "name": "mygrp", 
    "state": "present", 
    "system": false
}
172.16.141.209 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 3000, 
    "name": "mygrp", 
    "state": "present", 
    "system": false
}

4.1.2 进行验证并查看 LOG

[root@Tang-1 ~]# tail -1 /etc/group
mygrp:x:3000:
[root@Tang-1 ~]# tail -5 /var/log/messages 
Jan  1 10:05:17 Tang systemd-logind: Removed session 9.
Jan  1 10:08:30 Tang systemd-logind: New session 10 of user root.
Jan  1 10:08:30 Tang systemd: Started Session 10 of user root.
Jan  1 10:08:31 Tang ansible-group: Invoked with non_unique=False name=mygrp system=False state=present gid=3000 local=False
Jan  1 10:09:31 Tang systemd-logind: Removed session 10.
[root@Tang-2 ~]# tail -1 /etc/group
mygrp:x:3000:
[root@Tang-2 ~]# tail -5 /var/log/messages 
Oct 16 14:26:08 Tang-2 systemd: Started Cleanup of Temporary Directories.
Oct 16 14:27:30 Tang-2 systemd-logind: New session 5 of user root.
Oct 16 14:27:30 Tang-2 systemd: Started Session 5 of user root.
Oct 16 14:27:31 Tang-2 ansible-group: Invoked with non_unique=False name=mygrp system=False state=present gid=3000 local=False
Oct 16 14:28:31 Tang-2 systemd-logind: Removed session 5.

4.1.3 删除组

[root@Tang ~]# ansible all -m group -a "gid=3000 name=mygrp state=absent"        # 删除组

4.2 User

4.2.1 查看帮助和创建用户

[root@Tang ~]# ansible-doc -s user

[root@Tang ~]# ansible all -m user -a "uid=5000 name=testuser state=present groups=mygrp shell=/bin/tcsh"   # 创建用户
172.16.141.253 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 5000, 
    "groups": "mygrp", 
    "home": "/home/testuser", 
    "name": "testuser", 
    "shell": "/bin/tcsh", 
    "state": "present", 
    "system": false, 
    "uid": 5000
}
172.16.141.209 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 5000, 
    "groups": "mygrp", 
    "home": "/home/testuser", 
    "name": "testuser", 
    "shell": "/bin/tcsh", 
    "state": "present", 
    "system": false, 
    "uid": 5000
}

4.2.2 进行验证

[root@Tang-1 ~]# tail -1 /etc/passwd
testuser:x:5000:5000::/home/testuser:/bin/tcsh
[root@Tang-1 ~]# id testuser
uid=5000(testuser) gid=5000(testuser) groups=5000(testuser),3000(mygrp)
[root@Tang-1 ~]# tail -5 /var/log/messages 
Jan  1 10:09:31 Tang systemd-logind: Removed session 10.
Jan  1 10:13:21 Tang systemd-logind: New session 11 of user root.
Jan  1 10:13:21 Tang systemd: Started Session 11 of user root.
Jan  1 10:13:22 Tang ansible-user: Invoked with comment=None ssh_key_bits=0 update_password=always ssh_key_passphrase=NOT_LOGGING_PARAMETER force=False uid=5000 create_home=True password_lock=None non_unique=False home=None skeleton=None append=False ssh_key_type=rsa ssh_key_comment=ansible-generated on Tang-1 group=None system=False state=present role=None hidden=None local=None authorization=None profile=None shell=/bin/tcsh expires=None ssh_key_file=None groups=['mygrp'] move_home=False password=NOT_LOGGING_PARAMETER name=testuser seuser=None remove=False login_class=None generate_ssh_key=None
Jan  1 10:14:22 Tang systemd-logind: Removed session 11.
[root@Tang-2 ~]# tail -1 /etc/passwd
testuser:x:5000:5000::/home/testuser:/bin/tcsh
[root@Tang-2 ~]# id testuser
uid=5000(testuser) gid=5000(testuser) groups=5000(testuser),3000(mygrp)
[root@Tang-2 ~]# tail -5 /var/log/messages 
Oct 16 14:28:31 Tang-2 systemd-logind: Removed session 5.
Oct 16 14:32:21 Tang-2 systemd-logind: New session 6 of user root.
Oct 16 14:32:21 Tang-2 systemd: Started Session 6 of user root.
Oct 16 14:32:22 Tang-2 ansible-user: Invoked with comment=None ssh_key_bits=0 update_password=always ssh_key_passphrase=NOT_LOGGING_PARAMETER force=False uid=5000 create_home=True password_lock=None non_unique=False home=None skeleton=None append=False ssh_key_type=rsa ssh_key_comment=ansible-generated on Tang-2 group=None system=False state=present role=None hidden=None local=None authorization=None profile=None shell=/bin/tcsh expires=None ssh_key_file=None groups=['mygrp'] move_home=False password=NOT_LOGGING_PARAMETER name=testuser seuser=None remove=False login_class=None generate_ssh_key=None
Oct 16 14:33:23 Tang-2 systemd-logind: Removed session 6.

4.3 Copy

4.3.1 查看帮助和进行文件复制

[root@Tang ~]# ansible-doc -s copy

[root@Tang ~]# ansible all -m copy -a "src=/etc/fstab dest=/tmp/fstab.ansible mode=600"  # 复制文件并指定权限
172.16.141.253 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "ca8ccfb1d598e21f66df77b7d27645fc6fc67887", 
    "dest": "/tmp/fstab.ansible", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "e8ad2aac9b5606e9ae8fd8afb84d7ab8", 
    "mode": "0600", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 628, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571208787.5-53812580613725/source", 
    "state": "file", 
    "uid": 0
}
172.16.141.209 | CHANGED => {
   
    "ansible_facts": {
   
        "discovered_interpreter_pytho
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值