ansible应用合集

ansible 脚手架-2-常用命令操作

2016-12-28  本文已影响359人  DE8UG

查看一下主机组名称

这里我们查到了test的主机组,官方的称呼是:Host Inventory

[root@master ~/ansible-note]# tail /etc/ansible/hosts 
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com

[test]
10.129.204.250

查看网络通信是否正常

我们直接使用的ping模块,并对root用户,和假设的masternobody用户进行的测试,当然,只有root可以ping

[root@master ~/ansible-note]# ansible test -m ping -u root
10.129.204.250 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@master ~/ansible-note]# ansible test -m ping -u master
10.129.204.250 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", 
    "unreachable": true
}
[root@master ~/ansible-note]# ansible test -m ping -u nobody
10.129.204.250 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", 
    "unreachable": true
}

启动服务

使用模块:service

[root@master ~/ansible-note]# ansible test -m service -a "name=httpd state=started"
10.129.204.250 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started"
}
[root@master ~/ansible-note]# ansible test -m service -a "name=nginx state=started"
10.129.204.250 | FAILED! => {
    "changed": false, 
    "failed": true, 
    "msg": "nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)\nnginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)\nnginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)\nnginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)\nnginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)\nnginx: [emerg] still could not bind()\n"
}

运行一般命令

使用模块:command,默认可省略。

注意: 这里只是运行的一般命令,带有管道符是行不通的,后面会有例子说明。

上面我们先启用了httpd,然后又要启动nginx,导致错误提示80端口冲突了,所以查看一下:

[root@master ~/ansible-note]# ansible test -a "lsof -i :80"
10.129.204.250 | SUCCESS | rc=0 >>
COMMAND    PID   USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
httpd   119860   root    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119889 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119890 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119891 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119893 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119894 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119895 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119897 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)
httpd   119899 apache    5u  IPv6 42203204      0t0  TCP *:http (LISTEN)

查看帮助并停止服务

如果我们想停止刚才的httpd,启动Nginx,但是又忘记用哪个参数,当然是提前查一下:

[root@master ~/ansible-note]# ansible-doc -s service
- name: Manage services.
  action: service
      arguments              # Additional arguments provided on the command line
      enabled                # Whether the service should start on boot. *At least one of state and enabled are required.*
      name=                  # Name of the service.
      pattern                # If the service does not respond to the status command, name a substring to look for as would be found in the output of the `ps' command as a stand-in for a
                               status result.  If the string is found, the service will be assumed to be running.
      runlevel               # For OpenRC init scripts (ex: Gentoo) only.  The runlevel that this service belongs to.
      sleep                  # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to workaround badly behaving init scripts
                               that exit immediately after signaling a process to stop.
      state                  # `started'/`stopped' are idempotent actions that will not run commands unless necessary.  `restarted' will always bounce the service.  `reloaded' will always
                               reload. *At least one of state and enabled are required.*
[root@master ~/ansible-note]# ansible test -m service -a "name=httpd state=stopped"
10.129.204.250 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "stopped"
}
[root@master ~/ansible-note]# ansible test -m service -a "name=nginx state=started"
10.129.204.250 | SUCCESS => {
    "changed": true, 
    "name": "nginx", 
    "state": "started"
}

运行shell复杂命令

前面我们直接用-a运行了一下命令,查看端口,但是如果我们用ps配合管道符查看nginx进程呢?

[root@master ~/ansible-note]# ansible test -a "ps aux |grep nginx"
10.129.204.250 | FAILED | rc=1 >>
ERROR: Garbage option.
********* simple selection *********  ********* selection by list *********
-A all processes                      -C by command name
-N negate selection                   -G by real group ID (supports names)
-a all w/ tty except session leaders  -U by real user ID (supports names)
-d all except session leaders         -g by session OR by effective group name
-e all processes                      -p by process ID
                                      -q by process ID (unsorted & quick)
T  all processes on this terminal     -s processes in the sessions given
a  all w/ tty, including other users  -t by tty
g  OBSOLETE -- DO NOT USE             -u by effective user ID (supports names)
r  only running processes             U  processes for specified users
x  processes w/o controlling ttys     t  by tty
*********** output format **********  *********** long options ***********
-o,o user-defined  -f full            --Group --User --pid --cols --ppid
-j,j job control   s  signal          --group --user --sid --rows --info
-O,O preloaded -o  v  virtual memory  --cumulative --format --deselect
-l,l long          u  user-oriented   --sort --tty --forest --version
-F   extra full    X  registers       --heading --no-heading --context
                                      --quick-pid
                    ********* misc options *********
-V,V  show version      L  list format codes  f  ASCII art forest
-m,m,-L,-T,H  threads   S  children in sum    -y change -l format
-M,Z  security data     c  true command name  -c scheduling class
-w,w  wide output       n  numeric WCHAN,UID  -H process hierarchy

报错了!原因很简单,这是个复杂的shell命令,需要用shell模块来完成。正确做法如下:


[root@master ~/ansible-note]# ansible test -m shell -a "ps aux |grep nginx"
10.129.204.250 | SUCCESS | rc=0 >>
root     122507  0.0  0.0 626588   904 ?        Ss   15:30   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody   122508  3.5  2.2 647800 22400 ?        S    15:30   0:01 nginx: worker process                                          
nobody   122509  0.0  0.1 626736  1444 ?        S    15:30   0:00 nginx: cache manager process                                   
nobody   122510  0.0  0.1 626736  1308 ?        S    15:30   0:00 nginx: cache loader process                                    
root     122849  0.0  0.1 106072  1264 pts/2    S+   15:30   0:00 /bin/sh -c ps aux |grep nginx
root     122851  0.0  0.0 103312   876 pts/2    S+   15:30   0:00 grep nginx

同理,还可以查看其它进程或者看看能安装哪些包


[root@master ~/ansible-note]# ansible test -m shell -a "rpm -qa |grep php"
10.129.204.250 | SUCCESS | rc=0 >>
php-common-5.3.3-47.el6.x86_64
php-cli-5.3.3-47.el6.x86_64

[root@master ~/ansible-note]# ansible test -m shell -a "rpm -qa |grep memcache"
10.129.204.250 | FAILED | rc=1 >>


[root@master ~/ansible-note]# ansible test -m shell -a "yum list |grep memcache"
10.129.204.250 | SUCCESS | rc=0 >>
dmlite-plugins-memcache.x86_64                 0.8.5-1.el6               epel   
memcached.x86_64                               1.4.4-3.el6_8.1           updates
memcached-devel.i686                           1.4.4-3.el6_8.1           updates
memcached-devel.x86_64                         1.4.4-3.el6_8.1           updates
pcp-pmda-memcache.x86_64                       3.10.9-6.el6              base   
php-ZendFramework-Cache-Backend-Libmemcached.noarch
php-pecl-memcache.x86_64                       3.0.5-4.el6               base   
php-pecl-memcached.x86_64                      1.0.0-1.el6               epel   
php54-php-pecl-memcache.x86_64                 3.0.8-3.el6               rhel-6.7-rhel-x86_64-server-6-rhscl-1
php55-php-pecl-memcache.x86_64                 3.0.8-3.el6               rhel-6.7-rhel-x86_64-server-6-rhscl-1
python-memcached.noarch                        1.43-6.el6                base   

拷贝文件与安装程序包

使用模块: copy,yum

下面的例子一开始想拷贝一个文件,但是提示说缺少程序包,于是先用yum的模块安装,再进行拷贝,具体过程如下:

[root@master ~/ansible-note]# ll /root/ansible-note/ls.yml
-rw-r--r-- 1 root root 95 Dec 15 15:21 /root/ansible-note/ls.yml
[root@master ~/ansible-note]# ansible test -m copy -a "src=/root/ansible-note/ls.yml dest=/tmp/"
10.129.204.250 | FAILED! => {
    "changed": false, 
    "checksum": "d1f8398d9df763643fbb5416d70f88fb69dbd85b", 
    "failed": true, 
    "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"
}
[root@master ~/ansible-note]# ansible test -m yum -a "name=libselinux-python state=present"
10.129.204.250 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\n * base: mirrors.btte.net\n * epel: mirrors.tuna.tsinghua.edu.cn\n * extras: mirrors.neusoft.edu.cn\n * updates: mirrors.yun-idc.com\nResolving Dependencies\n--> Running transaction check\n---> Package libselinux-python.x86_64 0:2.0.94-7.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package                  Arch          Version               Repository   Size\n================================================================================\nInstalling:\n libselinux-python        x86_64        2.0.94-7.el6          base        203 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 203 k\nInstalled size: 657 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : libselinux-python-2.0.94-7.el6.x86_64                        1/1 \n\r  Verifying  : libselinux-python-2.0.94-7.el6.x86_64                        1/1 \n\nInstalled:\n  libselinux-python.x86_64 0:2.0.94-7.el6                                       \n\nComplete!\n"
    ]
}
[root@master ~/ansible-note]# ansible test -m copy -a "src=/root/ansible-note/ls.yml dest=/tmp/"
10.129.204.250 | SUCCESS => {
    "changed": true, 
    "checksum": "d1f8398d9df763643fbb5416d70f88fb69dbd85b", 
    "dest": "/tmp/ls.yml", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d1dec858ae7c42a2c86268e5dd2b7448", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 95, 
    "src": "/root/.ansible/tmp/ansible-tmp-1482911046.02-198188393706996/source", 
    "state": "file", 
    "uid": 0
}
[root@master ~/ansible-note]# ansible test -a "ll /tmp" # 注意,这里 ll 别名是不支持的!
10.129.204.250 | FAILED | rc=2 >>
[Errno 2] No such file or directory

[root@master ~/ansible-note]# ansible test -a "ll /tmp/"
10.129.204.250 | FAILED | rc=2 >>
[Errno 2] No such file or directory

[root@master ~/ansible-note]# ansible test -a "ls -l  /tmp/"
10.129.204.250 | SUCCESS | rc=0 >>
total 12
drwx------. 2 root root 4096 Dec 28 15:43 ansible_eIMlYR
drwxr-xr-x. 2 root root 4096 Nov 16 15:23 hsperfdata_root
-rw-r--r--. 1 root root   95 Dec 28 15:43 ls.yml

参考:

https://ansible-book.gitbooks.io/ansible-first-book/content/ansibleyong_ming_ling_guan_li_zhu_ji.html

上一篇下一篇

猜你喜欢

热点阅读