Ansible---命令行应用

ansible远程管理工具;

时间同步
名字解析

1、安装ansible;
Yum install ansible
=======================================================================================================================================================================
 Package                                                     Arch                           Version                                  Repository                   Size
=======================================================================================================================================================================
Installing:
 ansible                                                     noarch                         2.2.1.0-1.el7                            web                         4.6 M
Installing for dependencies:
 PyYAML                                                      x86_64                         3.10-11.el7                              dev                         153 k
 libtomcrypt                                                 x86_64                         1.17-23.el7                              web                         224 k
 libtommath                                                  x86_64                         0.42.0-4.el7                             web                          35 k
 libyaml                                                     x86_64                         0.1.4-11.el7_0                           dev                          55 k
 python-babel                                                noarch                         0.9.6-8.el7                              dev                         1.4 M
 python-backports                                            x86_64                         1.0-8.el7                                dev                         5.8 k
 python-backports-ssl_match_hostname                         noarch                         3.4.0.2-4.el7                            dev                          12 k
 python-httplib2                                             noarch                         0.7.7-3.el7                              web                          70 k
 python-jinja2                                               noarch                         2.7.2-2.el7                              dev                         515 k
 python-keyczar                                              noarch                         0.71c-2.el7                              web                         218 k
 python-markupsafe                                           x86_64                         0.11-10.el7                              dev                          25 k
 python-setuptools                                           noarch                         0.9.8-4.el7                              dev                         396 k
 python-six                                                  noarch                         1.9.0-2.el7                              dev                          29 k
 python2-crypto                                              x86_64                         2.6.1-13.el7                             web                         476 k
 python2-ecdsa                                               noarch                         0.13-4.el7                               web                          83 k
 python2-paramiko                                            noarch                         1.16.1-2.el7                             web                         258 k
 python2-pyasn1                                              noarch                         0.1.9-7.el7                              dev                         100 k
 sshpass                                                     x86_64                         1.06-1.el7                               web                          21 k

Transaction Summary
=======================================================================================================================================================================
Install  1 Package (+18 Dependent packages)


/etc/ansible     ---------------配置文件所在目录位置
/etc/ansible/ansible.cfg ---主配置文件
/etc/ansible/hosts----------主机清单
/etc/ansible/roles-----------角色目录
/usr/bin/ansible-------------主程序
/usr/bin/ansible-console
/usr/bin/ansible-doc
/usr/bin/ansible-galaxy
/usr/bin/ansible-playbook
/usr/bin/ansible-pull--------从客户端拉取工具
/usr/bin/ansible-vault


/etc/ansible/ansible.cfg ---主配置文件,关于自身的配置文件;

Ansible 一两种方式完成管理,命令行或剧本方式完成

命令行;
Ansible host-pattern  options
Ansible -a  -m   传递模块参数
Ansible -C          测试执行
Ansible -f        默认管控5个
ansible  -I       指明主机清单
Ansible  -l          列出主机
Ansible -t       将日志记录与指定的位置文件中

连接命令选项;

Ansible -c        指定以什么方式连接目标主机
Ansible -u        指明目标主机使用连接时的用户;默认为none;

权限升级方式;Privilege escalation options;

ansible     -s      切换sudo操作;
Ansible    -U      su到某个用户进行操作;
Ansible    -b      转变至某个用户操作;


秘钥认证;
#ssh-keygen -t rsa -P ""
将生成的蜜钥发送另两台主机;
#ssh-copy-id -I ~/.ssh/id_rsa.pub [email protected]
#ssh-copy-id -I ~/.ssh/id_rsa.pub [email protected]

[root@localhost ~]#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:
2f:3d:fc:15:67:32:4d:89:59:6b:05:2c:73:bb:fe:51 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|             ..o.|
|            o * +|
|             * =.|
|              oo |
|        S     +.E|
|         +    .*.|
|        . =  ... |
|         . o .. .|
|            .  ..|
+-----------------+

[root@localhost ~]#ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
The authenticity of host '172.16.88.2 (172.16.88.2)' can't be established.
ECDSA key fingerprint is 75:9e:e0:a9:31:ce:cb:73:ed:8a:17:d6:9d:3d:6a:2b.
Are you sure you want to continue connecting (yes/no)? yes
/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
[email protected]'s password: 

Number of key(s) added: 1

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

[root@localhost ~]#ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
The authenticity of host '172.16.88.1 (172.16.88.1)' can't be established.
ECDSA key fingerprint is ce:2d:bd:83:46:37:94:45:27:2d:65:b8:71:f3:32:93.
Are you sure you want to continue connecting (yes/no)? yes
/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
[email protected]'s password: 

Number of key(s) added: 1

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

设置名字解析;
[root@localhost ~]#scp /etc/hosts [email protected]:/etc/hosts
The authenticity of host '172.16.88.2 (172.16.88.2)' can't be established.
ECDSA key fingerprint is 75:9e:e0:a9:31:ce:cb:73:ed:8a:17:d6:9d:3d:6a:2b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.88.2' (ECDSA) to the list of known hosts.
[email protected]'s password: 
hosts                                                            
[root@localhost ~]#cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.16.88.1 node1.mageedu.com  node1
172.16.88.2 node2.mageedu.com  node2
172.16.88.3 node3.mageedu.com  node3
172.16.88.4 node4.mageedu.com  node4

定义管控的主机,编辑配置文件;
Vim /etc/ansible/hosts
[Websrvs]
172.16.88.2
172.16.88.3
[dbsrvs]
172.16.88.3

命令行;
列出控制的主机;
[root@localhost ansible]#ansible all -m ping --list-hosts
  hosts (2):
    172.16.88.1
    172.16.88.2
探测目标主机是否可频通;
[root@localhost ansible]#ansible all -m ping -C
172.16.88.1 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
172.16.88.2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"

[root@localhost ansible]#ansible-doc --help
Usage: ansible-doc [options] [module...]

Options:
  -h, --help            show this help message and exit
  -l, --list            List available modules
  -M MODULE_PATH, --module-path=MODULE_PATH
                        specify path(s) to module library (default=None)
  -s, --snippet         Show playbook snippet for specified module(s)
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

Ansible-doc -a  显示所有模块文档
Ansible-doc -l   列出所有可用模块
Ansible-doc -M
Ansible-doc -s  显示playbooks当中使用的选项;

    Ø group模块,查看定义组的选项;
[root@localhost ansible]#ansible-doc -s group
- name: Add or remove groups
  action: group
      gid                    # Optional `GID' to set for the group.
      name=                  # Name of the group to manage.
      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@localhost ansible]#

State---可以创建或删除

Ansible all -m group -a "gid=1012 name=mygrp state=present system=no"

[root@localhost ~]#tail -1 /etc/group
mygrp:x:1012:
 
Ansible all -m group -a "gid=1012 name=mygrp state=absent system=no"


    Ø user模块,查看创建用户选项;
#Ansible-doc -s 
Name= 
Comment---注释信息
Expires------过期时间
Group-------基本组
Groups------附加组
Home-------家目录
Password----密码
Shell---------shell类型
State --------创建,删除 persent,absent
System ---------是否为系统用户
Uid-----------用户id
Move home----当创建家目录是原有的文件是否移动过来,等于no时创建新的家目录,原有的文件不会移动过来
Generate_ssh_key---创建用户是自动生成一对蜜钥,原来有蜜钥不会覆盖,重新创建一对蜜钥

创建用户,添加附加组
[root@localhost ansible]#ansible all -m user -a "uid=5000 name=testuser state=present system=no groups=mygrp shell=/bin/tcsh"
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 5000, 
    "groups": "mygrp", 
    "home": "/home/testuser", 
    "name": "testuser", 
    "shell": "/bin/tcsh", 
    "state": "present", 
    "system": false, 
    "uid": 5000
}
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 5000, 
    "groups": "mygrp", 
    "home": "/home/testuser", 
    "name": "testuser", 
    "shell": "/bin/tcsh", 
    "state": "present", 
    "system": false, 
    "uid": 5000
}

    Ø copy模块
[root@localhost ~]#ansible-doc -s copy
Ansible ----dest= 目标路径,远程主机的绝对路径
Ansible--------Src-----源可以相对,也可以是绝对的,源文件以斜线结尾、/ 将目录中的内容复制过去,不带斜线,将整个目录递归复制过去。
Ansible-------Owner属主
Ansible-------group属组
Ansible----mode--------权限
Ansible------Remode src---从远程复制到远程
Ansible ------content ----指定内容生成目标文件生成的内容,不用指定src源文件;

拷贝内容到远程主机;
[root@localhost ansible]#ansible all -m copy -a  " src=/etc/fstab dest=/tmp/fstab.ansibled mode=600 "  
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "checksum": "38e9d94be631342601af30347dca5d61ae09172c", 
    "dest": "/tmp/fstab.ansibled", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b91107d726fc7502b6d74ffce58a6dd0", 
    "mode": "0600", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 541, 
    "src": "/root/.ansible/tmp/ansible-tmp-1505840510.12-83854192085881/source", 
    "state": "file", 
    "uid": 0
}
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "checksum": "38e9d94be631342601af30347dca5d61ae09172c", 
    "dest": "/tmp/fstab.ansibled", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b91107d726fc7502b6d74ffce58a6dd0", 
    "mode": "0600", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 541, 
    "src": "/root/.ansible/tmp/ansible-tmp-1505840510.12-83768663591640/source", 
    "state": "file", 
    "uid": 0
}

Ansible all -m copy -a "src=/etc/pam.d/ dest=/tmp/"
Ansible all -m copy -a "src=/etc/pam.d dest=/tmp/"
两种复制的区别在于,复制文件和复制目录

给定内容拷贝到远程主机;
[root@localhost ansible]#ansible all -m copy -a "content='hi there\n' dest=/tmp/hi.txt" 
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "checksum": "56170f5429b35dea081bb659b884b475ca9329a9", 
    "dest": "/tmp/hi.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "fd33e2e8ad3cb1bdd3ea8f5633fcf5c7", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 8, 
    "src": "/root/.ansible/tmp/ansible-tmp-1505841223.02-222568091857457/source", 
    "state": "file", 
    "uid": 0
}
将属主,属组改变为现有的testuser,mygrp
[root@localhost ansible]#ansible all -m copy -a "content='hi there\n' dest=/tmp/hi.txt owner=testuser group=mygrp"           
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "checksum": "279d9035886d4c0427549863c4c2101e4a63e041", 
    "dest": "/tmp/hi.txt", 
    "gid": 1032, 
    "group": "mygrp", 
    "mode": "0644", 
    "owner": "testuser", 
    "path": "/tmp/hi.txt", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 9, 
    "state": "file", 
    "uid": 5000
}
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "checksum": "279d9035886d4c0427549863c4c2101e4a63e041", 
    "dest": "/tmp/hi.txt", 
    "gid": 1032, 
    "group": "mygrp", 
    "mode": "0644", 
    "owner": "testuser", 
    "path": "/tmp/hi.txt", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 9, 
    "state": "file", 
    "uid": 5000
}
没有创建的用户和组时将会出现错误;

    Ø fetch模块;
从远程主机复制文件到本地;远程主机不能指定多个。
    Ø command模块;
Ansible-doc -s command
在远程主机执行命令,
Ansible -----chdir 切换目录执行;
Ansible ------executable执行程序,执行命令有shell发起,指定shell类型;
Ansible ----free from  自有格式执行;


[root@localhost ansible]#ansible all -m command -a "ifconfig"
172.16.88.1 | SUCCESS | rc=0 >>
ens33: flags=4163  mtu 1500
        inet 192.168.226.150  netmask 255.255.255.0  broadcast 192.168.226.255
        inet6 fe80::cf19:b710:2fcd:be00  prefixlen 64  scopeid 0x20
        ether 00:0c:29:f6:4b:b1  txqueuelen 1000  (Ethernet)
        RX packets 3699  bytes 386609 (377.5 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1201  bytes 197899 (193.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
172.16.88.2 | SUCCESS | rc=0 >>
ens33: flags=4163  mtu 1500
        inet 192.168.226.152  netmask 255.255.255.0  broadcast 192.168.226.255
        inet6 fe80::6f38:23ba:a34b:3a29  prefixlen 64  scopeid 0x20
        ether 00:0c:29:58:50:18  txqueuelen 1000  (Ethernet)
        RX packets 2593  bytes 258093 (252.0 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 450  bytes 68915 (67.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

切换目录并创建目录;
Ansible all -m command -a "chdir=/var/tmp  mkdir hi.dir"
[root@localhost ~]#ansible all -m command -a "chdir=/var/tmp/ mkdir hi.dir"
172.16.88.2 | SUCCESS | rc=0 >>


172.16.88.1 | SUCCESS | rc=0 >>

[root@localhost ~]#ansible all -m command -a "chdir=/var/tmp/ mkdir hi.dir"
172.16.88.1 | FAILED | rc=1 >>
mkdir: cannot create directory ‘hi.dir’: File exists

172.16.88.2 | FAILED | rc=1 >>
mkdir: cannot create directory ‘hi.dir’: File exists

不是幂等的,再次创建将会出现失败;

远程主机设置密码;
[root@localhost ~]#ansible all -m command -a "echo mageedu | password --stdin mageedu"
172.16.88.1 | SUCCESS | rc=0 >>
mageedu | password --stdin mageedu

172.16.88.2 | SUCCESS | rc=0 >>
mageedu | password --stdin mageedu

指定shell类型;
[root@localhost ~]#ansible all -m command -a "echo mageedu | password --stdin mageedu excutable=/bin/bash"
172.16.88.1 | SUCCESS | rc=0 >>
mageedu | password --stdin mageedu excutable=/bin/bash

172.16.88.2 | SUCCESS | rc=0 >>
mageedu | password --stdin mageedu excutable=/bin/bash

Command 无法解析|的功能,无法使用设置密码;

    Ø Ansible-doc -s shell
查看shell模块选项;


使用shell模块添加用户密码;
[root@localhost ~]#ansible all -m command -a "useradd mageedu"                                            
172.16.88.2 | SUCCESS | rc=0 >>


172.16.88.1 | SUCCESS | rc=0 >>


[root@localhost ~]#ansible all -m shell -a "echo mageedu | passwd --stdin mageedu"
172.16.88.2 | SUCCESS | rc=0 >>
Changing password for user mageedu.
passwd: all authentication tokens updated successfully.

172.16.88.1 | SUCCESS | rc=0 >>
Changing password for user mageedu.
passwd: all authentication tokens updated successfully.

    Ø Ansible-doc -s file

创建目录;
Ansible all -m file -a "path=/var/tmp/hello.dir state=directory"

[root@localhost ~]#ansible all -m file -a "path=/var/tmp/hello.dir state=directory"
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/var/tmp/hello.dir", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}

创建文件;
[root@localhost ~]#ansible all -m file -a "path=/var/tmp/hello.txt state=file"
172.16.88.1 | FAILED! => {
    "changed": false, 
    "failed": true, 
    "msg": "file (/var/tmp/hello.txt) is absent, cannot continue", 
    "path": "/var/tmp/hello.txt", 
    "state": "absent"
}
172.16.88.2 | FAILED! => {
    "changed": false, 
    "failed": true, 
    "msg": "file (/var/tmp/hello.txt) is absent, cannot continue", 
    "path": "/var/tmp/hello.txt", 
    "state": "absent"
}
创建空文件,不建议使用file模块,使用copy命令,countent 为空,即可拷贝空文件;

file模块可以创建符号链接;
复制一个文件,创建符号链接;
[root@localhost ~]#ansible all -m copy -a "src=/etc/fstab dest=/var/tmp/fstab.ansible"
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "checksum": "38e9d94be631342601af30347dca5d61ae09172c", 
    "dest": "/var/tmp/fstab.ansible", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b91107d726fc7502b6d74ffce58a6dd0", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 541, 
    "src": "/root/.ansible/tmp/ansible-tmp-1505911110.34-137908123845802/source", 
    "state": "file", 
    "uid": 0
}
创建符号链接;
[root@localhost ~]#ansible all -m file -a "src=/var/tmp/fstab.ansible dest=/var/tmp/fstab.link state=link"
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "dest": "/var/tmp/fstab.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 22, 
    "src": "/var/tmp/fstab.ansible", 
    "state": "link", 
    "uid": 0
}
[root@localhost tmp]#ll
总用量 4
-rw-r--r--. 1 root root 541 9月  20 20:38 fstab.ansible
lrwxrwxrwx. 1 root root  22 9月  20 20:41 fstab.link -> /var/tmp/fstab.ansible

指明目标符号链接,state=link

File 模块设定文件属性;
Group,mode,owner….

    Ø Ansible-doc -s cron 
cron模块---定义计划任务;
 
[root@localhost ~]#ansible all -m cron -a "minute=*/3 job='/usr/sbin/update 172.16.0.1 &> /dev/null' " 
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "None"
    ]
}

同步时间;
[root@localhost tmp]#crontab -l
#Ansible: None
*/3 * * * * /usr/sbin/update 172.16.0.1 &> /dev/null
在node1上查看信息;

删除设定的任务;
[root@localhost ~]#ansible all -m cron -a "minute=*/3 job='/usr/sbin/update 172.16.0.1 &> /dev/null' state=absent"
172.16.88.1 | SUCCESS => {
    "changed": false, 
    "envs": [], 
    "jobs": [
        "None"
    ]
}
需要指明名字;
[root@localhost ~]#ansible all -m cron -a "minute=*/3 job='/usr/sbin/update 172.16.0.1 &>/dev/null' name=None state=absent" 
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@localhost tmp]# crontab -l
[root@localhost tmp]#
删除设定任务成功;

    Ø Ansible-doc -s yum 
Yum 模块
State= 选项---install(present , installed , latest)
都表示安装;
remove(absent , removed)--都表示卸载;
Disbalerepo 禁用某个仓库
Enablerepo 启用没偶个仓库
Disable_gpg_check 禁用秘钥检测

两个主机各自安装一个nginx;
[root@localhost ~]#ansible all -m yum -a "name=nginx state=installed"
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
[root@localhost ~]#rpm -q nginx
nginx-1.10.2-1.el7.x86_64

    Ø Ansible-doc -s service
service模块;
[root@localhost ~]#ansible all -m service -a "name=nginx state=started  "           
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "name": "nginx", 
    "state": "started", 
[root@localhost ~]#ansible all -m service -a "name=nginx state=stopped  "     
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "name": "nginx", 
    "state": "stopped", 
查看剩余模块;
Ansible-doc -l|less


    Ø Ansible-doc -s script
script模块;
指定脚本路径,执行脚本
[root@localhost ~]#ansible all -m script -a "/tmp/test.sh"
172.16.88.1 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 172.16.88.1 closed.\r\n", 
    "stdout": "", 
    "stdout_lines": []
}
172.16.88.2 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 172.16.88.2 closed.\r\n", 
    "stdout": "", 
    "stdout_lines": []
}
[root@localhost tmp]#cat /tmp/ansible.txt 
ansible script
执行脚本在远程主机执行。

你可能感兴趣的:(Ansible---命令行应用)