ansible 模塊學習

Ansible通過模塊的方式來完成一些遠程的管理工作。可以通過ansible-doc -l查看所有模塊,可以使用ansible-doc -s module來查看某個模塊的參數,也可以使用ansible-doc help module來查看該模塊更詳細的信息。默認的模塊位置在/usr/share/ansible。下面列出一些常用的模塊:


1. setup

可以用來查看遠程主機的一些基本信息:

ansible -i /etc/ansible/hosts test -m setup


2.ping

可以用來測試遠程主機的運行狀態:

ansible test -m ping


3.file

設置文件的屬性

file模塊包含如下選項:

    force:需要在兩種情況下強制創建軟鏈接,一種是源文件不存在但之後會建立的情況下;另一種是目標軟鏈接已存在,需要先取消之前的軟鏈,然後創建新的軟鏈,有兩個選項:yes|no

    group:定義文件/目錄的屬組

    mode:定義文件/目錄的權限

    owner:定義文件/目錄的屬主

    path:必選項,定義文件/目錄的路徑

    recurse:遞歸的設置文件的屬性,只對目錄有效

    src:要被鏈接的源文件的路徑,只應用於state=link的情況

    dest:被鏈接到的路徑,只應用於state=link的情況

    state:

            directory:如果目錄不存在,創建目錄

            file:即使文件不存在,也不會被創建

            link:創建軟鏈接

            hard:創建硬鏈接

            touch:如果文件不存在,則會創建一個新的文件,如果文件或目錄已存在,則更新其最後修改時間

            absent:刪除目錄、文件或者取消鏈接文件

ansible -i /root/hosts all  -m setup   查看遠程主機的信息

ansible -i hosts  all  -m file -a "path=/tmp/test state=touch"  遠程創建/tmp/test文件

ansible -i hosts  all  -m file -a "src=/etc/fstab dest=/tmp/fstab state=link"  在遠程主機上建立軟連接。/etc/fstab---------->/tmp/fstab

lrwxrwxrwx. 1 root   root     10 Oct 16 15:28 fstab -> /etc/fstab

ansible -i hosts all  -m file -a "path=/tmp/fstab state=absent"   刪除目錄  文件 或者取消鏈接

192.168.1.60 | success >> {

    "changed": true, 

    "path": "/tmp/fstab", 

    "state": "absent"

}


192.168.1.63 | success >> {

    "changed": true, 

    "path": "/tmp/fstab", 

    "state": "absent"  

4.copy

複製文件到遠程主機

copy模塊包含如下選項:

    backup:在覆蓋之前將原文件備份,備份文件包含時間信息。有兩個選項:yes|no

    content:用於替代"src",可以直接設定指定文件的值

    dest:必選項。要將源文件複製到的遠程主機的絕對路徑,如果源文件是一個目錄,那麼該路徑也必須是個目錄

    directory_mode:遞歸的設定目錄的權限,默認爲系統默認權限

    force:如果目標主機包含該文件,但內容不同,如果設置爲yes,則強制覆蓋,如果爲no,則只有當目標主機的目標位置不存在該文件時,才複製。默認爲yes

    others:所有的file模塊裏的選項都可以在這裏使用

    src:要複製到遠程主機的文件在本地的地址,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,它將遞歸複製。在這種情況下,如果路徑使用"/"來結尾,則只複製目錄裏的內容,如果沒有使用"/"來結尾,則包含目錄在內的整個內容全部複製,類似於rsync。

[root@ha book]# cat copy.yml 

- hosts: test1

  tasks:

  - name: copy the file

    copy: src=/root/purge_relay_logs.sh   dest=/root  owner=root group=root mode=755

[root@ha book]# ansible-playbook  -i /root/ansible/host/test  copy.yml 


PLAY [test1] ****************************************************************** 


GATHERING FACTS *************************************************************** 

ok: [192.168.1.63]

ok: [192.168.1.76]


TASK: [copy the file] ********************************************************* 

changed: [192.168.1.63]

changed: [192.168.1.76]


PLAY RECAP ******************************************************************** 

192.168.1.63               : ok=2    changed=1    unreachable=0    failed=0   

192.168.1.76               : ok=2    changed=1    unreachable=0    failed=0  

5.command

在遠程主機上執行命令

command模塊包含如下選項:

    creates:一個文件名,當該文件存在,則該命令不執行

    free_form:要執行的linux指令

    chdir:在執行指令之前,先切換到該指定的目錄

    removes:一個文件名,當該文件不存在,則該選項不執行

    executable:切換shell來執行指令,該執行路徑必須是一個絕對路徑

示例:

    ansible test -a "/sbin/reboot"


6.shell

切換到某個shell執行指定的指令,參數與command相同。

示例:

    ansible test -m shell -a "somescript.sh >> somelog.txt"


7.service

用於管理服務

該模塊包含如下選項:

    arguments:給命令行提供一些選項

    enabled:是否開機啓動  yes|no

    name:必選項,服務名稱

    pattern:定義一個模式,如果通過status指令來查看服務的狀態時,沒有響應,就會通過ps指令在進程中根據該模式進行查找,如果匹配到,則認爲該服務依然在運行

    runlevel:運行級別

    sleep:如果執行了restarted,在則stop和start之間沉睡幾秒鐘

    state:對當前服務執行啓動,停止、重啓、重新加載等操作(started,stopped,restarted,reloaded)

示例:

    ansible test -m service -a "name=httpd state=started enabled=yes"

    ansible test -m service -a "name=foo pattern=/usr/bin/foo state=started"

    ansible test -m service -a "name=network state=restarted args=eth0"


8.cron

用於管理計劃任務

包含如下選項:

    backup:對遠程主機上的原任務計劃內容修改之前做備份

    cron_file:如果指定該選項,則用該文件替換遠程主機上的cron.d目錄下的用戶的任務計劃

    day:日(1-31,*,*/2,……)

    hour:小時(0-23,*,*/2,……)

    minute:分鐘(0-59,*,*/2,……)

    month:月(1-12,*,*/2,……)

    weekday:周(0-7,*,……)

    job:要執行的任務,依賴於state=present

    name:該任務的描述

    special_time:指定什麼時候執行,參數:reboot,yearly,annually,monthly,weekly,daily,hourly

    state:確認該任務計劃是創建還是刪除

    user:以哪個用戶的身份執行

示例:

    ansible test -m cron -a 'name="check dirs" hour="5,2" job="ls -alh > /dev/null"'

    ansible test -m cron -a 'name="a job for reboot" special_time=reboot job="/some/job.sh"'

    ansible test -m cron -a 'name="yum autoupdate" weekday="2" minute=0 hour=12 user="root" job="YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate" cron_file=ansible_yum-autoupdate'

    ansilbe test -m cron -a 'cron_file=ansible_yum-autoupdate state=absent'

ansible -i hosts  all -m cron -a 'name="sync time for ntp server"   minute='*/3' job="/usr/sbin/ntpdate cn.pool.ntp.org"'

192.168.1.60 | success >> {

    "changed": true, 

    "jobs": [

        "sync time for ntp server"

    ]

}


192.168.1.63 | success >> {

    "changed": true, 

    "jobs": [

        "sync time for ntp server"

    ]

}

 crontab  -l 

#Ansible: sync time for ntp server

*/3 * * * * /usr/sbin/ntpdate cn.pool.ntp.org

ansible -i hosts all  -a 'crontab -l'

192.168.1.60 | success | rc=0 >>

#Ansible: sync time for ntp server

*/3 * * * * /usr/sbin/ntpdate cn.pool.ntp.org


192.168.1.63 | success | rc=0 >>

#Ansible: sync time for ntp server

*/3 * * * * /usr/sbin/ntpdate cn.pool.ntp.org


9.filesystem

在塊設備上創建文件系統

選項:

    dev:目標塊設備

    force:在一個已有文件系統的設備上強制創建

    fstype:文件系統的類型

    opts:傳遞給mkfs命令的選項


10.yum

使用yum包管理器來管理軟件包

選項:

    config_file:yum的配置文件

    disable_gpg_check:關閉gpg_check

    disablerepo:不啓用某個源

    enablerepo:啓用某個源

    list

    name:要進行操作的軟件包的名字,也可以傳遞一個url或者一個本地的rpm包的路徑

    state:狀態(present,absent,latest)

示例:

    ansible test -m yum -a 'name=httpd state=latest'

    ansible test -m yum -a 'name="@Development tools" state=present'

    ansible test -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'

     

11.user

管理用戶

    home:

    groups:

    uid

    password:

    name:

    createhome:

    system:

    remove:

    state:

    shell:

[root@localhost ymal]# cat user.yml 

- name: create user for test group

  hosts: test

  user: root

  gather_facts: false



  vars:(引入變量)

  - user: "toy" (變量名稱)



  tasks:

  - name: create `user` on test

    user: name="`user`"

gather_facts 的作用是蒐集遠端機器的相關信息

ansible-playbook  -i /root/hosts  user.yml 


PLAY [create user for test group] ********************************************* 


TASK: [create toy on vps] ***************************************************** 

changed: [192.168.1.60]

changed: [192.168.1.63]


PLAY RECAP ******************************************************************** 

192.168.1.60               : ok=1    changed=1    unreachable=0    failed=0   

192.168.1.63               : ok=1    changed=1    unreachable=0    failed=0 


12.group

管理組


13.synchronize

使用rsync同步文件

    archive

    checksum

    delete

    dest

    src

    dest_port

    existing_only: skip createing new files on receiver

    links

    owner

    mode:(push, pull)

    recursive

    rsync_path

    times:Preserve modification times

示例:

    src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync"

    src=some/relative/path dest=/some/absolute/path archive=no links=yes

    src=some/relative/path dest=/some/absolute/path checksum=yes times=no

    src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull


14.mount

配置掛載點

選項:

    dump

    fstype:必選項,掛載文件的類型

    name:必選項,掛載點

    opts:傳遞給mount命令的參數

    passno

    src:必選項,要掛載的文件

    state:必選項

            present:只處理fstab中的配置

            absent:刪除掛載點

            mounted:自動創建掛載點並掛載之

            umounted:卸載

示例:

    name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present

    name=/srv/disk src='LABEL=SOME_LABEL' state=present

    name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077' opts=noatime state=present


    ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024'

    ansible test -a 'losetup /dev/loop0 /disk.img'

    ansible test -m filesystem 'fstype=ext4 force=yes opts=-F dev=/dev/loop0'

    ansible test -m mount 'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'


15.raw

類似command,但可以傳遞管道

[root@localhost ~]# ansible  -i ~/hosts all -m raw -a "rpm -qa |grep xinetd"(使用raw模塊查看遠程服務器上是否安裝了xinetd服務,說明沒有安裝)

192.168.1.61 | FAILED | rc=1 >>

b


[root@localhost ~]# ansible -i ~/hosts all  -m yum -a "name=xinetd state=latest"(使用yum模塊進行安裝yum源裏最新版的xinetd軟件)

192.168.1.61 | success >> {

    "changed": true, 

    "msg": "", 

    "rc": 0, 

    "results": [

        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.skyshe.cn\n * extras: mirrors.pubyun.com\n * updates: mirrors.pubyun.com\nSetting up Install Process\nResolving Dependencies\n--> Running transaction check\n---> Package xinetd.x86_64 2:2.3.14-39.el6_4 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch            Version                    Repository     Size\n================================================================================\nInstalling:\n xinetd          x86_64          2:2.3.14-39.el6_4          base          121 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 121 k\nInstalled size: 259 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : 2:xinetd-2.3.14-39.el6_4.x86_64                              1/1 \n\r  Verifying  : 2:xinetd-2.3.14-39.el6_4.x86_64                              1/1 \n\nInstalled:\n  xinetd.x86_64 2:2.3.14-39.el6_4                                               \n\nComplete!\n"

    ]

}


[root@localhost ~]# ansible  -i ~/hosts all -m raw -a "rpm -qa |grep xinetd" (再次使用raw模塊查看xinetd是否安裝)

192.168.1.61 | success | rc=0 >>

xinetd-2.3.14-39.el6_4.x86_6

ansible  -i ~/hosts all -m shell -a "service xinetd restart"(使用shell模塊啓動xinetd服務)

192.168.1.61 | success | rc=0 >>

Stopping xinetd: [FAILED]

Starting xinetd: [  OK  ]

[root@localhost ~]# ansible  -i ~/hosts all -m service -a "name=xinetd state=restarted" (同樣你也可以使用service模塊進行服務的啓動,關閉和重啓) 

192.168.1.61 | success >> {

    "changed": true, 

    "name": "xinetd", 

    "state": "started"

}

ansible all -m raw -a 'yum -y install python-simplejson'  批量安裝軟件

ansible -i /root/hosts all -m copy -a  "src=/root/test.sh dest=/tmp"

ansible -i /root/ansible/host/test all  -m copy -a "src=/root/app  dest=/tmp"   copy整個目錄 遠端服務器會生成app的目錄

192.168.1.61 | FAILED >> {

    "failed": true, 

    "md5sum": "5d0cb5573fa5ead11bfcc701a2bb0551", 

    "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"

}


192.168.1.60 | FAILED >> {

    "failed": true, 

    "md5sum": "5d0cb5573fa5ead11bfcc701a2bb0551", 

    "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"

}


192.168.1.63 | FAILED >> {

    "failed": true, 

    "md5sum": "5d0cb5573fa5ead11bfcc701a2bb0551", 

    "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"

}

[root@localhost ~]# ansible -i hosts all -m script -a "/tmp/test.sh" 這個是因爲本地沒有test.sh這個腳本 這條命令的意思是  在遠程機器上執行本地的腳本

192.168.1.60 | FAILED => file or module does not exist: /tmp/test.sh

192.168.1.63 | FAILED => file or module does not exist: /tmp/test.sh

[root@dbmaster ymal]# ansible -i /root/host/hosts all  -m shell -a "/root/test.sh"  用shell是在遠程機器上執行遠程機器上的腳本

192.168.1.66 | FAILED | rc=127 >>

/bin/sh: /root/test.sh: No such file or directory


192.168.1.60 | success | rc=0 >>

2014-10-29 script testing success!


192.168.1.63 | FAILED | rc=127 >>

/bin/sh: /root/test.sh: No such file or directory


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章