ansible放置位置:node
ansible的安裝:
配置好epel源,直接經過yum安裝python
~]# yum -y install ansible
ansible的配置文件:/etc/ansible/ansible.cfg
ansible的主機清單:/etc/ansible/hosts
ansible的主程序:ansible、ansible-playbos、ansible-docnginx
[root@nfs ~]# ansible -h Usage: ansible <host-pattern> [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS module arguments -C, --check don't make any changes; instead, try to predict some of the changes that may occur -h, --help show this help message and exit -m MODULE_NAME, --module-name=MODULE_NAME module name to execute (default=command) --syntax-check perform a syntax check on the playbook, but do not execute it -f FORKS, --forks=FORKS specify number of parallel processes to use (default=5) -u REMOTE_USER, --user=REMOTE_USER connect as this user (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart)
示例1. 經過直接指定主機名或IP地址定義主機列表。git
# Ex 1: Ungrouped hosts, specify before any group headers. ## green.example.com ## blue.example.com ## 192.168.100.1 ## 192.168.100.10
示例2. 先定義組名,再在組下填入主機名或IP地址github
# Ex 2: A collection of hosts belonging to the 'webservers' group ## [webservers] ## alpha.example.org ## beta.example.org ## 192.168.1.100 ## 192.168.1.110 # If you have multiple hosts following a pattern you can specify # them like this: # 若是有多個連續主機,也可用以下方法指定主機。 ## www[001:006].example.com
示例3.web
# Ex 3: A collection of database servers in the 'dbservers' group ## [dbservers] ## ## db01.intranet.mydomain.net ## db02.intranet.mydomain.net ## 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 ## 以上寫法可擴展爲以下主機: ## db-99-nod.example.com ## db-100-nod.example.com ## db-101-nod.example.com
定義主機列表示例:redis
[root@nfs ~]# tail -2 /etc/ansible/hosts np[1:2].lxk.com nfs.lxk.com
獲取主機列表:shell
[root@nfs ~]# ansible all --list-hosts hosts (3): np1.lxk.com np2.lxk.com nfs.lxk.com
獲取模塊幫助信息:npm
[root@nfs ~]# ansible-doc --help Usage: ansible-doc [-l|-F|-s] [options] [plugin] plugin documentation tool Options: -a, --all **For internal testing only** Show documentation for all plugins. #內測使用 -h, --help show this help message and exit -l, --list List available plugins 顯示可用插件 -s, --snippet Show playbook snippet for specified plugin(s) ## 顯示指定插件用法
獲取模塊列表:centos
~]# ansible-doc -l
[root@nfs ~]# ansible-doc -s ping - name: Try to connect to host, verify a usable python and return `pong' on success # 嘗試鏈接主機,若目標主機可用,就回應一個'pong' ping: data: # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.
示例1:向全部可控主機發起ping操做
[root@nfs ~]# ansible all -m ping np2.lxk.com | SUCCESS => { "changed": false, "ping": "pong" } nfs.lxk.com | SUCCESS => { "changed": false, "ping": "pong" } np1.lxk.com | SUCCESS => { "changed": false, "ping": "pong" }
示例2:data自定義回顯內容爲abc
[root@nfs ~]# ansible all -m ping -a data='abc' np1.lxk.com | SUCCESS => { "changed": false, "ping": "abc" } np2.lxk.com | SUCCESS => { "changed": false, "ping": "abc" } nfs.lxk.com | SUCCESS => { "changed": false, "ping": "abc" }
*示例3:data爲crash時,顯示結果爲false
[root@nfs ~]# ansible all -m ping -a data='crash' np1.lxk.com | FAILED! => { "changed": false, "module_stderr": "Shared connection to np1.lxk.com closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n", "msg": "MODULE FAILURE", "rc": 1 } nfs.lxk.com | FAILED! => { "changed": false, "module_stderr": "Shared connection to nfs.lxk.com closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n", "msg": "MODULE FAILURE", "rc": 1 } np2.lxk.com | FAILED! => { "changed": false, "module_stderr": "Shared connection to np2.lxk.com closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n", "msg": "MODULE FAILURE", "rc": 1 }
模塊用法:
對於command來講,要使用哪一個命令,使用-a選項,直接給出命令自己便可。
例1:建立臨時文件
[root@nfs ~]# ansible all -m command -a "mktemp /tmp/abc.XXXX" nfs.lxk.com | SUCCESS | rc=0 >> /tmp/abc.Xyz7 np2.lxk.com | SUCCESS | rc=0 >> /tmp/abc.lwqo np1.lxk.com | SUCCESS | rc=0 >> /tmp/abc.jjHW
例2:建立用戶
[root@nfs ~]# ansible all -m command -a "useradd user1" # 第一次建立成功 nfs.lxk.com | SUCCESS | rc=0 >> np1.lxk.com | SUCCESS | rc=0 >> np2.lxk.com | SUCCESS | rc=0 >> [root@nfs ~]# ansible all -m command -a "useradd user1" #第二次建立相同用戶失敗 nfs.lxk.com | FAILED | rc=9 >> useradd: user 'user1' already existsnon-zero return code np1.lxk.com | FAILED | rc=9 >> useradd: user 'user1' already existsnon-zero return code np2.lxk.com | FAILED | rc=9 >> useradd: user 'user1' already existsnon-zero return code
用加條件判斷建立用戶失敗,因||是直接發給目標主機內核運行,不是經由shell運行,而||是shell的內置命令。
[root@nfs ~]# ansible all -m command -a "id user1 || useradd user1" nfs.lxk.com | FAILED | rc=1 >> id: extra operand ‘||’ Try 'id --help' for more information.non-zero return code np1.lxk.com | FAILED | rc=1 >> id: extra operand ‘||’ Try 'id --help' for more information.non-zero return code np2.lxk.com | FAILED | rc=1 >> id: extra operand ‘||’ Try 'id --help' for more information.non-zero return code
與command模塊很類似,所不一樣處是它是在shell下運行的。還可以使用executable切換至指定node下運行命令。
例:加條件判斷建立用戶
[root@nfs ~]# ansible all -m shell -a "id user1 || useradd user1" np2.lxk.com | SUCCESS | rc=0 >> uid=1001(user1) gid=1001(user1) groups=1001(user1) nfs.lxk.com | SUCCESS | rc=0 >> uid=1000(user1) gid=1000(user1) groups=1000(user1) np1.lxk.com | SUCCESS | rc=0 >> uid=1000(user1) gid=1000(user1) groups=1000(user1)
group模塊用法:
[root@nfs ~]# ansible-doc -s group - name: Add or remove groups group: gid: # Optional `GID' to set for the group.是否使用自定義的id號 name: # (required) Name of the group to manage. 要管理的組名,必需要定義的。 state: # Whether the group should be present or not on the remote host. 狀態信息,決定是刪除仍是添加。建立:present,刪除:absent system: # If `yes', indicates that the group created is a system group. 是否建立系統用戶
示例:建立一個系統組
[root@nfs ~]# ansible np1.lxk.com -m group -a 'name=mygrp gid=200 system=yes' np1.lxk.com | SUCCESS => { "changed": true, #變動:成功 "gid": 200, #自定義組ID:200 "name": "mygrp", #組名:mygrp "state": "present", #狀態:添加 "system": true #是否爲系統用戶:是 }
示例:刪除組
[root@nfs ~]# ansible np1.lxk.com -m group -a 'name=mygrp state=absent' np1.lxk.com | SUCCESS => { "changed": true, "name": "mygrp", "state": "absent" }
上面命令重複執行時,changed狀態爲false。
[root@nfs ~]# ansible np1.lxk.com -m group -a 'name=mygrp state=absent' np1.lxk.com | SUCCESS => { "changed": false, "name": "mygrp", "state": "absent" }
模塊內置命令一堆,請自行查看,基本見名知意。
示例:建立一個用戶,名字爲tom,用戶ID爲2000,組名爲mygrp,shell類型爲/bin/bash,狀態爲添加。
[root@nfs ~]# ansible np1.lxk.com -m user -a 'name=tom state=present uid=2000 groups=mygrp shell=/bin/bash' np1.lxk.com | SUCCESS => { "changed": true, "comment": "", "create_home": true, "group": 2000, "groups": "mygrp", "home": "/home/tom", "name": "tom", "shell": "/bin/bash", "state": "present", "system": false, "uid": 2000 }
示例:修改tom用戶的ID爲2020,shell類型爲/bin/tcsh
[root@nfs ~]# ansible np1.lxk.com -m user -a 'name=tom state=present uid=2020 groups=mygrp shell=/bin/tcsh' np1.lxk.com | SUCCESS => { "append": false, "changed": true, "comment": "", "group": 2000, "groups": "mygrp", "home": "/home/tom", "move_home": false, "name": "tom", "shell": "/bin/tcsh", "state": "present", "uid": 2020 }
用法:
[root@nfs ~]# ansible-doc -s copy - name: Copies files to remote locations #複製一個或多個文件至遠程主機 copy: dest: # (required) Remote absolute path where the file should be copied to. If `src' is a directory, this must be a directory too. If `dest' is a nonexistent path and if either `dest' ends with "/" or `src' is a directory, `dest' is created. If `src' and `dest' are files, the parent directory of `dest' isn't created: the task fails if it doesn't already exist. #複製指定文件至目標遠程須要是絕對路徑。若是src是目錄,dest也必須是目錄。若是dest是一個不存在的路徑,而且dest不以/結尾或者src是個目錄,dest會自動建立。若是src和dest都是多個文件,dest的父目錄沒建立,複製就會失敗。 src: # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavior is similar to Rsync. #本地須要複製到遠程主機的文件的路徑。能夠是絕對路徑,也能夠是相對路徑。若是路徑是個目錄,則遞歸複製。若是路徑以/結尾,只複製目錄下的文件至目標路徑。若是不以/結尾,則會把目錄以及其下的內容都複製至目標主機。這種行爲相似於rsync。 content: # When used instead of `src', sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the template module. #若是不使用src而使用content,把文件內容直接指定爲content所指定的內容。而後剩下的懶得翻譯了。 owner: # Name of the user that should own the file/directory, as would be fed to `chown'. mode: # Mode the file or directory should be. group: # Name of the group that should own the file/directory, as would be fed to `chown'.
示例1:經過content指定文件內容並複製至目標主機(若不帶\n,不會自動換行)
[root@nfs ~]# ansible np2.lxk.com -m copy -a 'dest=/tmp/textfile.txt content="hello,brother!\n"' np2.lxk.com | SUCCESS => { "changed": true, "checksum": "8634ff795ad950aa9c762c45cc8b07137248002a", "dest": "/tmp/textfile.txt", "gid": 0, "group": "root", "md5sum": "2252b10979e37d2884855832666fd811", "mode": "0644", "owner": "root", "size": 15, "src": "~None/.ansible/tmp/ansible-tmp-1528471338.21-89043902941123/source", #ansible會把給定的源生成一個臨時源當作源文件複製至目標位置。 "state": "file", "uid": 0 }
目標主機查看文件內容:
[root@np2 ~]# cat /tmp/textfile.txt hello,brother!
示例2:複製本地/etc/fstab至np1.lxk.com的/tmp目錄下,更名爲fstab.txt,屬主改成user2,權限0600.(user2需先建立)
[root@nfs ~]# np1.lxk.com all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.txt owner=user2 mode=0600' np1.lxk.com | SUCCESS => { "changed": true, "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "dest": "/tmp/fstab.txt", "gid": 0, "group": "root", "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", "mode": "0600", "owner": "user2", "size": 595, "src": "~None/.ansible/tmp/ansible-tmp-1528518314.71-128514426299583/source", "state": "file", "uid": 1024 }
查看目標主機上的文件:
[root@np1 ~]# ll /tmp total 4 -rw------- 1 user2 root 595 Jun 9 12:25 fstab.txt
[root@nfs ~]# ansible-doc -s fetch - name: Fetches a file from remote nodes #從遠程主機取來文件 fetch: dest: # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.example.com', would be saved into `/backup/host.example.com/etc/profile' #(必須項)要保存文件的目錄。如指定的目錄爲/backup,遠程主機host.example.com上的/etc/profile文件會保存在本地/backup/host.example.com/etc/profile src: # (required) The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may be supported in a later release. #遠程主機須要fetch的文件,必須是文件,不能是目錄。之後可能會支持目錄。
示例1:從遠程主機np1.lxk.com上覆制/etc/fstab至本地/tmp目錄下
[root@nfs ~]# ansible np1.lxk.com -m fetch -a 'src=/etc/fstab dest=/tmp/' np1.lxk.com | SUCCESS => { "changed": true, "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "dest": "/tmp/np1.lxk.com/etc/fstab", "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", "remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "remote_md5sum": null }
示例2:從全部可控的遠程主機上覆制/etc/fstab至本地/tmp目錄下
[root@nfs ~]# ansible all -m fetch -a 'src=/etc/fstab dest=/tmp/' np1.lxk.com | SUCCESS => { "changed": false, "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "dest": "/tmp/np1.lxk.com/etc/fstab", "file": "/etc/fstab", "md5sum": "5aee64ae648da49b3b16e2b9ea70d279" } np2.lxk.com | SUCCESS => { "changed": true, "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "dest": "/tmp/np2.lxk.com/etc/fstab", "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", "remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "remote_md5sum": null } nfs.lxk.com | SUCCESS => { "changed": true, "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "dest": "/tmp/nfs.lxk.com/etc/fstab", "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", "remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "remote_md5sum": null }
查看本地目錄:
[root@nfs ~]# tree /tmp /tmp ├── issue.txt ├── nfs.lxk.com │ └── etc │ └── fstab ├── np1.lxk.com │ └── etc │ └── fstab └── np2.lxk.com └── etc └── fstab 6 directories, 4 files
[root@nfs ~]# ansible-doc -s file - name: Sets attributes of files file: force: # force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the "path" file and create symlink to the "src" file in place of it). #在兩種狀況下強制建立連接:源文件不存在(隨後會出現)或目標存在且是文件(將會取消path指定的文件並建立連接) group: # Name of the group that should own the file/directory, as would be fed to `chown'. #改變文件的屬組 mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). #改變文件或目錄的權限 owner: # Name of the user that should own the file/directory, as would be fed to `chown'. #改變文件的屬主 path: # (required) path to the file being managed. Aliases: `dest', `name' #必須項。要修改的文件的路徑 recurse: # recursively set the specified file attributes (applies only to directories) #遞歸地設置文件屬性 src: # path of the file to link to (applies only to `state=link' and `state=hard'). Will accept absolute, relative and nonexisting paths. Relative paths are not expanded. #要連接到的文件路徑(只適用於「state=link」和「state=hard」)。將接受絕對路徑、相對路徑和不存在路徑。相對路徑沒有展開。 state: # If `directory', all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. If `file', the file will NOT be created if it does not exist; see the `touch' value or the [copy] or [template] module if you want that behavior. If `link', the symbolic link will be created or changed. Use `hard' for hardlinks. If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. Note that `absent' will not cause `file' to fail if the `path' does not exist as the state did not change. If `touch' (new in 1.4), an empty file will be created if the `path' does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way `touch` works from the command line). 若是是目錄,父目錄不存在時會自動建立。 若是是文件,文件不存在時不會建立。 若是是連接,將會建立或者改變。 若是是absent,目錄將會被遞歸刪除,文件或連接會被取消連接。 若是是touch,不存在的文件將會被建立。目錄將會更改訪問時間和改變時間。
示例1:修改np1.lxk.com主機/tmp/fstab.txt的屬主爲mygrp,權限爲660
[root@nfs ~]# ansible np1.lxk.com -m file -a 'path=/tmp/fstab.txt group=mygrp mode=0660' np1.lxk.com | SUCCESS => { "changed": true, "gid": 200, "group": "mygrp", "mode": "0660", "owner": "user2", "path": "/tmp/fstab.txt", "size": 595, "state": "file", "uid": 1024 }
查看目標主機文件屬性:
[root@np1 ~]# ll -d /tmp/fstab.txt -rw-rw---- 1 user2 mygrp 595 Jun 9 12:25 /tmp/fstab.txt
示例2:爲np1.lxk.com主機的/tmp/fstab.txt建立軟連接/tmp/fstab.link
[root@nfs ~]# ansible np1.lxk.com -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.txt state=link' np1.lxk.com | SUCCESS => { "changed": true, "dest": "/tmp/fstab.link", "gid": 0, "group": "root", "mode": "0777", "owner": "root", "size": 14, "src": "/tmp/fstab.txt", "state": "link", "uid": 0 }
示例3:在np1.lxk.com的/tmp目錄下建立目錄file.dir,權限爲770
[root@nfs ~]# ansible np1.lxk.com -m file -a 'path=/tmp/file.dir mode=0770 state=directory' np1.lxk.com | SUCCESS => { "changed": true, "gid": 0, "group": "root", "mode": "0770", "owner": "root", "path": "/tmp/file.dir", "size": 4096, "state": "directory", "uid": 0 }
示例:下載一個文件至np1.lxk.com的/tmp目錄下
[root@nfs ~]# ansible np1.lxk.com -m get_url -a 'dest=/tmp/ url=https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm' np1.lxk.com | SUCCESS => { "changed": true, "checksum_dest": null, "checksum_src": "c566cb3df854f4551da1ab7f642e96889b77439c", "dest": "/tmp/jq-devel-1.5-1.el7.x86_64.rpm", "gid": 0, "group": "root", "md5sum": "43f5092eadb4855fb780e67244d997df", "mode": "0644", "msg": "OK (6472 bytes)", "owner": "root", "size": 6472, "src": "/tmp/tmpwix52V", "state": "file", "status_code": 200, "uid": 0, "url": "https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm" }
查看目標主機/tmp下的文件:
[root@np1 ~]# ls /tmp file.dir fstab.link fstab.txt jq-devel-1.5-1.el7.x86_64.rpm
示例1:建立一個時間同步的任務,每5分鐘運行一次。
[root@nfs ~]# ansible np1.lxk.com -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 192.168.200.254 &> /dev/null' name=timesync" np1.lxk.com | SUCCESS => { "changed": true, "envs": [], "jobs": [ "timesync" ] }
目標主機上查看任務:
[root@np1 ~]# crontab -l #Ansible: timesync #註明是由ansible生成的,標識名爲timesync */5 * * * * /usr/sbin/ntpdate 192.168.200.254 &> /dev/null
示例2:刪除剛纔建立的計劃任務
ansible刪除計劃任務是根據name所定義的名字來標識的。
[root@nfs ~]# ansible np1.lxk.com -m cron -a "state=absent name=timesync" np1.lxk.com | SUCCESS => { "changed": true, "envs": [], "jobs": [] }
查看目標主機計劃任務列表爲空。
[root@nfs ~]# ansible-doc -s yum - name: Manages packages with the `yum' package manager yum: conf_file: # The remote yum configuration file to use for the transaction. #指明當前事務使用哪一個repo文件 state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. #安裝選項:presetn、installed、latest #卸載選項:absent、removed name: # (required) A package name , or package specifier with version, like `name-1.0'. #必須項。指定軟件名 skip_broken: # Resolve depsolve problems by removing packages that are causing problems from the transaction. #跳過錯誤信息 update_only: # When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest' #只升級,若是軟件包未安裝則不安裝。
示例1:安裝或者查看nginx軟件是否已安裝
[root@nfs ~]# ansible all -m yum -a "name=nginx state=installed" nfs.lxk.com | SUCCESS => { "changed": false, "msg": "", "rc": 0, "results": [ "1:nginx-1.12.2-2.el7.x86_64 providing nginx is already installed" ] } np1.lxk.com | SUCCESS => { "changed": false, "msg": "", "rc": 0, "results": [ "1:nginx-1.12.2-2.el7.x86_64 providing nginx is already installed" ] } np2.lxk.com | SUCCESS => { "changed": false, "msg": "", "rc": 0, "results": [ "1:nginx-1.12.2-2.el7.x86_64 providing nginx is already installed" ] }
示例2:卸載nginx
[root@nfs ~]# ansible all -m yum -a "name=nginx state=absent" nfs.lxk.com | SUCCESS => { "changed": true, "msg": "", "rc": 0, ………… 太長,不貼了。在命令返回中能夠看到Erasing字樣, …………
示例3:使用np1.lxk.com主機的/etc/yum.repos.d/repobak/base.repo安裝httpd軟件
[root@nfs ~]# ansible np1.lxk.com -m yum -a "name=httpd state=installed conf_file=/etc/yum.repos.d/repobak/base.repo" np1.lxk.com | SUCCESS => { "changed": true, "msg": "", "rc": 0, "results": [ "Resolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-80.el7.centos base 2.7 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : httpd-2.4.6-80.el7.centos.x86_64 1/1 \n Verifying : httpd-2.4.6-80.el7.centos.x86_64 1/1 \n\nInstalled:\n httpd.x86_64 0:2.4.6-80.el7.centos \n\nComplete!\n" ] } 實際顯示效果就是這樣。有點醜。可是安裝成功了。
示例4:更新緩存並安裝httpd
[root@nfs ~]# ansible np2.lxk.com -m yum -a "name=httpd state=installed update_cache=yes" np2.lxk.com | SUCCESS => { "changed": false, "msg": "", "rc": 0, "results": [ "httpd-2.4.6-80.el7.centos.x86_64 providing httpd is already installed" ] }
[root@nfs ~]# ansible-doc -s hostname - name: Manage hostname hostname: name: # (required) Name of the host
示例:
[root@nfs ~]# ansible np1.lxk.com -m hostname -a "name=np1" np1.lxk.com | SUCCESS => { "ansible_facts": { "ansible_domain": "lxk.com", "ansible_fqdn": "np1.lxk.com", "ansible_hostname": "np1", "ansible_nodename": "np1" }, "changed": true, "name": "np1" }
[root@nfs ~]# ansible-doc -s git - name: Deploy software (or files) from git checkouts git: clone: # If `no', do not clone the repository if it does not exist locally dest: # (required) The path of where the repository should be checked out. This parameter is required, unless `clone' is set to `no'. repo: # (required) git, SSH, or HTTP(S) protocol address of the git repository version: # What version of the repository to check out. #指定要clone的版本,若是不指,默認爲最新版本。
示例: 下載kubernetes至/tmp/kubernetes/
[root@nfs ~]# ansible np1.lxk.com -m git -a 'repo="https://github.com/kubernetes/kubernetes.git" dest=/tmp/kubernetes' #下載須要等待
查看目標主機下載狀況:
[root@np1 ~]# tree -a /tmp/kubernetes /tmp/kubernetes └── .git ├── branches ├── config ├── description ├── HEAD ├── hooks │ ├── applypatch-msg.sample │ ├── commit-msg.sample │ ├── post-update.sample │ ├── pre-applypatch.sample │ ├── pre-commit.sample │ ├── prepare-commit-msg.sample │ ├── pre-push.sample │ ├── pre-rebase.sample │ └── update.sample ├── info │ └── exclude ├── objects │ ├── info │ └── pack └── refs ├── heads └── tags 10 directories, 13 files [root@np1 ~]# du -sh /tmp/kubernetes 100K /tmp/kubernetes #可看到目錄已建立,因下載速度慢,文件仍是這麼小。
[root@nfs ~]# ansible-doc -s pip - name: Manages Python library dependencies pip: name: # The name of a Python library to install or the url of the remote package. As of 2.2 you can supply a list of names. #指定名稱,也能夠以URL指定。2.2版本後支持名稱列表。 state: # The state of module The 'forcereinstall' option is only available in Ansible 2.1 and above. #同yum的state version: # The version number to install of the Python library specified in the `name' parameter. #指定要安裝的版本
[root@nfs ~]# ansible-doc -s npm - name: Manage node.js packages with npm npm: name: # The name of a node.js library to install #要安裝的node.js名稱 path: # The base path where to install the node.js libraries #指明安裝源地址 state: # The state of the node.js library version: # The version to be installed
[root@nfs ~]# ansible-doc -s service - name: Manage services 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: # (required) 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.* Note that reloaded will start the service if it is not already started, even if your chosen init system wouldn't normally. #started:開啓服務 #stoped:關閉服務 #restarted:重啓服務 #reloaded:重載服務 #reloaded時,若是服務未啓動會啓動它。
示例:啓動httpd服務,並設置開機自啓
[root@nfs ~]# ansible all -m service -a "name=httpd state=started enabled=yes" nfs.lxk.com | SUCCESS => { "changed": true, "enabled": true, "name": "httpd", "state": "started", "status": { "ActiveEnterTimestampMonotonic": "0", "ActiveExitTimestampMonotonic": "0", "ActiveState": "inactive", "After": "remote-fs.target basic.target network.target nss-lookup.target tmp.mount system.slice -.mount systemd-journald.socket", "AllowIsolate": "no", "AmbientCapabilities": "0", ………… 太長,不復制了 …………
查看全部節點服務狀態:
[root@nfs ~]# ansible all -m shell -a "ss -tnlp | grep 80" np1.lxk.com | SUCCESS | rc=0 >> LISTEN 0 128 127.0.0.1:6379 *:* users:(("redis-server",pid=8077,fd=4)) LISTEN 0 128 :::80 :::* users:(("httpd",pid=14265,fd=4),("httpd",pid=14264,fd=4),("httpd",pid=14263,fd=4),("httpd",pid=14262,fd=4),("httpd",pid=14261,fd=4),("httpd",pid=14260,fd=4)) np2.lxk.com | SUCCESS | rc=0 >> LISTEN 0 128 :::80 :::* users:(("httpd",pid=14845,fd=4),("httpd",pid=14844,fd=4),("httpd",pid=14842,fd=4),("httpd",pid=14841,fd=4),("httpd",pid=14840,fd=4),("httpd",pid=14838,fd=4)) nfs.lxk.com | SUCCESS | rc=0 >> LISTEN 0 128 :::80 :::* users:(("httpd",pid=6953,fd=4),("httpd",pid=6952,fd=4),("httpd",pid=6951,fd=4),("httpd",pid=6950,fd=4),("httpd",pid=6949,fd=4),("httpd",pid=6948,fd=4)) [root@nfs ~]# ansible all -m shell -a "systemctl is-enabled httpd" np2.lxk.com | SUCCESS | rc=0 >> enabled np1.lxk.com | SUCCESS | rc=0 >> enabled nfs.lxk.com | SUCCESS | rc=0 >> enabled #全部節點httpd服務都是開機自啓