ansible安裝及常用模塊

Ansible中文權威指南:http://www.ansible.com.cn/

一、ansible介紹

Ansible是一種自動化的運維工具,基於Python開發,它集合了衆多運維工具(比如puppet、chef、func等)的優點,能夠實現批量操作。但其實Ansible是基於模塊工作的,本身沒有批量部署的能力。真正具有批量部署的是ansible所運行的模塊,Ansible只是提供一種框架。

Ansible 是一個模型驅動的配置管理器,支持多節點發布、遠程任務執行。默認使用 SSH 進行遠程連接。無需在被管理節點上安裝附加軟件,可使用各種編程語言進行擴展。

二、Ansible特性

  • 模塊化,調用特定的模塊來完成特定任務 ,本身是核心組件,短小精悍 ;
  • 基於Python語言實現的,由Paramiko (python 的一個可併發連接 ssh 主機功能庫 ) , PyYAML和Jinja2 ( 模板化 ) 三個關鍵模塊實現;
  • agentless 無客戶端工具;
  • 以主從模式工作;
  • 支持自定義模塊;
  • 支持playbook,連續任務按先後設置順序完成;
  • 期望每個命令具有冪等性:

1.管理端支持local 、ssh、zeromq 三種方式連接被管理端,默認使用基於ssh的連接

2.可以按應用類型等方式進行Host Inventory(主機羣)分類,管理節點通過各類模塊實現相應的操作---單個模塊,單條命令的批量執行,我們可以稱之爲ad-hoc;

3.管理節點可以通過playbooks 實現多個task的集合實現一類功能,如web服務的安裝部署、數據庫服務器的批量備份等。playbooks我們可以簡單的理解爲,系統通過組合多條ad-hoc操作的配置文件 。

# ansible的配置文件:

/etc/ansible/ansible.cfg 主配置文件,配置ansible工作特性
/etc/ansible/hosts 主機清單
/etc/ansible/roles/ 存放角色的目錄

三、ansible安裝

3.1 ansible安裝前準備

3.1.1 對管理主機的要求

目前,只要機器上安裝了 Python 2.6 或 Python 2.7 (windows系統不可以做控制主機),都可以運行Ansible.

主機的系統可以是 Red Hat, Debian, CentOS, OS X, BSD的各種版本,等等.

自2.0版本開始,ansible使用了更多句柄來管理它的子進程,對於OS X系統,你需要增加ulimit值才能使用15個以上子進程,方法 sudo launchctl limit maxfiles 1024 2048,否則你可能會看見”Too many open file”的錯誤提示.

3.1.2 對託管節點的要求

通常我們使用 ssh 與託管節點通信,默認使用 sftp.如果 sftp 不可用,可在 ansible.cfg 配置文件中配置成 scp 的方式. 在託管節點上也需要安裝 Python 2.4 或以上的版本.如果版本低於 Python 2.5 ,還需要額外安裝一個模塊:python-simplejson

3.1.3 託管節點注意點

(1)沒安裝python-simplejson:也可以使用Ansible的”raw”模塊和script模塊,因此從技術上講,可以通過Ansible的”raw”模塊安裝python-simplejson,之後就可以使用Ansible的所有功能了.

(2)如果託管節點上開啓了SElinux,需要安裝libselinux-python,這樣纔可使用Ansible中與copy/file/template相關的函數.可以通過Ansible的yum模塊在需要的託管節點上安裝libselinux-python.

如果沒有默認安裝 Python 2.X 解釋器.需要安裝一個 Python 2.X 解釋器,並在 inventory中設置 ‘ansible_python_interpreter’ 變量指向的 2.X Python.可以使用 ‘raw’ 模塊在託管節點上遠程安裝Python 2.X.
例如:

ansible myhost --sudo -m raw -a "yum install -y python2 python-simplejson"

這條命令可以通過遠程方式在託管節點上安裝 Python 2.X 和 simplejson 模塊.

3.2 CentOS 7 安裝ansible

3.2.1 安裝ansible

(1)方法一:使用yum安裝ansible

sudo yum install -y epel-release
sudo yum install -y ansible

[root@localhost ~]# yum info ansible
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * epel: hkg.mirror.rackspace.com
Installed Packages
Name        : ansible
Arch        : noarch
Version     : 2.9.6
Release     : 1.el7
Size        : 104 M
Repo        : installed
From repo   : epel
Summary     : SSH-based configuration management, deployment, and
            : task execution system
URL         : http://ansible.com
License     : GPLv3+
Description : Ansible is a radically simple model-driven
            : configuration management, multi-node deployment, and
            : remote task execution system. Ansible works over SSH
            : and does not require any software or daemons to be
            : installed on remote nodes. Extension modules can be
            : written in any language and are transferred to managed
            : machines automatically.

(2)方法二:使用pip安裝ansible

yum install python-pip
pip install ansible
3.2.2 修改ansible配置和主機列表hosts:
#關閉第一次使用ansible連接客戶端時輸入命令提示
sed -i "s@\#host_key_checking = False@host_key_checking = False@g" /etc/ansible/ansible.cfg

#指定日誌路徑:
sed -i "s@\#log_path = \/var\/log\/ansible.log@log_path = \/var\/log\/ansible.log@g" /etc/ansible/ansible.cfg

[root@localhost ~]# grep -v "^#" /etc/ansible/ansible.cfg | grep -v "^$"
[defaults]
host_key_checking = False
log_path = /var/log/ansible.log
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]

3.2.3 將所有主機ip加入到/etc/ansible/hosts文件中
[root@localhost ~]# cat /etc/ansible/hosts
[app]
192.168.75.128

#默認ssh的端口爲22端口,如果爲其他端口號,可在主機名後面加上端口號,如 192.168.75.128:9604 ,也可以修改配置文件中的remote_port變量值

#也可以定義一個主機範圍,如192.168.75.[100:200] ,表示192.168.75.100 - 192.168.75.200 的主機
3.2.4 創建和配置 SSH 公鑰認證(免密碼登錄)
[root@localhost ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
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:
6b:1c:34:84:6e:61:23:90:75:49:f2:41:2e:9c:8c:e1 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|  o+oo=o.        |
| ..=.**o         |
|  E =+ooo        |
|     .o. .       |
|     .  S        |
|       . o       |
|        +        |
|       .         |
|                 |
+-----------------+
3.2.5 通過ansible將公鑰分發至各主機上
ansible all -m authorized_key -a "user=root key='{{ lookup('file', '/root/.ssh/id_rsa.pub') }}' path=/root/.ssh/authorized_keys manage_dir=no" --ask-pass -c paramiko

#需要輸入主機的密碼,若是有的主機密碼不一致,那麼該主機會分發失敗,此時只需再執行一遍命令輸入該主機密碼即可。或者先將密碼相同的主機進行分組,然後依次指定主機組執行命令分批分發公鑰。

#此命令是通過追加的方式來推送公鑰至authorized_keys,所以不用擔心原來的文件內容會被覆蓋。

到任意一臺主機上查看,可以看到公鑰已成功推送:

[root@localhost ~]# cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCiVwMCS/RSSuBVxNF8RMZ3WPxgdvxghC/UumhfMPPx/W2XsNZtJo3ioi73D8ZOnVWsCuhwHxE1FT1rhPiI61K33RAdrZuamlLYftcpzaOuHMpThxaIO7d1hu4ddmrOtfYQ8UMEPf4Wd8se2pTLr1W+hEwakm6UIbyezMUSDchLo2CuB5WFj8yaB7UlLjq7sTR2zbRqn2P3CPSlmDvkzCua8w2POsvI74sasvayhxka7pejzpvj49KniHaep7s1FpA2WsHJ/At8XWFqwtihO8jHffXIyc8nRH/iCf79baPmViNvVXdoGdcXprjVZmuxmNUmEN0G1QNZLR3P+dtlf58D [email protected]
PS:ansible免密登錄命令另一方法
ssh-keygen -t rsa -P ""      #生成祕鑰/root/.ssh/id_rsa.pub
ssh-copy-id -i ./.ssh/id_rsa.pub [email protected]   #將公鑰傳到192.168.75.128上,其中192.168.75.128是要被監控的機器

#如果出現報錯:-bash: ssh-copy-id: command not found
#則需要安裝一個包:yum -y install openssh-clientsansible
3.2.6 修改ansible配置,指定私鑰文件路徑
sed -i "s@\#private_key_file = \/path\/to\/file@private_key_file = \/root\/.ssh\/id_rsa@g" /etc/ansible/ansible.cfg
3.2.7 測試
[root@localhost ~]# ansible all -m ping --list-hosts
  hosts (1):
    192.168.75.128
    
[root@localhost ~]# ansible all -m ping
192.168.75.128 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
# 可以在命令後面加上-vvvv參數查看詳細的輸出結果,尤其是在命令執行失敗需要排錯的時候非常有用

四、ansible命令及常用模塊

4.1 ansible命令

通過ssh實現配置管理、應用部署、任務執行等功能

建議配置ansible端能基於密鑰認證的方式聯繫各被管理節點

【格式】ansible [-m module_name] [-a args]

的匹配規則:

#ALL 表示列表中的所有主機 ,ping進行主機連通性測試
例:ansible all -m ping 

#匹配所有主機 * 支持通配符     
例: ansible "*" -m ping 

#匹配所有主機         
ansible 192.168.1.* -m ping 

#匹配IP地址以192.168.1開頭的主機         
ansible “*app” -m ping # 匹配分組名 以 app結尾的主機 

#邏輯或:只要存在web或app組中的主機
例: ansible “web:app” -m ping         ansible “192.168.75.10:192.168.75.20” -m ping 

#邏輯與:同時在web組和db組中的主機     
ansible “web:&db” -m ping 

#邏輯非:在web組,但不在db組中的主機  
ansible ‘web:!db’ -m ping 

#綜合邏輯:
ansible ‘web:db:&app:!ftp’ -m -ping 

#正則表達式:
ansible “websrvs:&dbsrvs” -m ping ansible “~(web|db).*\.testcan\.com” -m ping
Ansible執行命令過程:
  • 加載自己的配置文件
  • 默認/etc/ansible/ansible.cfg
  • 加載自己對應的模塊文件,如command
  • 通過ansible將模塊或命令生成對應的臨時py文件,並將該文件傳輸至遠程服務器的對應執行用戶
  • $HOME/.ansible/tmp/ansible-tmp-數字/XXX.PY文件
  • 給文件+x執行
  • 執行並返回結果
  • 刪除臨時py文件,sleep 0退出
[root@localhost ~]# ansible --help
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
               [--become-user BECOME_USER] [-K] # 提示輸入 sudo 密碼,當不是 NOPASSWD 模式時使用
               [-i INVENTORY] # 指定hosts文件路徑默認 default =/etc/ansible/hosts
               [--list-hosts] # 只打印有哪些主機會執行這個 playbook 文件:不是實際執行該 playbook
               [-l SUBSET] # 指定一個 pattern,對<host_pattern>已經匹配的主機中再過濾一次
               [-P POLL_INTERVAL] #set the poll interval if using
               [-B SECONDS] [-o] # 壓縮輸出,摘要輸出
               [-t TREE] # 日誌輸出到該目錄,日誌文件名會以主機名命名
               [-k] #提示輸入 ssh 登錄密碼,當使用密碼驗證登錄的時候用 
               [--private-key PRIVATE_KEY_FILE]  #私鑰路徑
               [-u REMOTE_USER] #連接的用戶名,默認用 root,ansible.cfg 中可以配置
               [-c CONNECTION] #連接類型(default=smart)
               [-T TIMEOUT] # ssh 連接超時時間,默認 10 秒
               [--ssh-common-args SSH_COMMON_ARGS]
               [--sftp-extra-args SFTP_EXTRA_ARGS]
               [--scp-extra-args SCP_EXTRA_ARGS]
               [--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
               [-e EXTRA_VARS] [--vault-id VAULT_IDS]
               [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
               [-f FORKS]  #fork 多少個進程併發處理,默認 5
               [-M MODULE_PATH] #要執行的模塊的路徑,默認爲/usr/share/ansible/ [--playbook-dir BASEDIR]
               [-a MODULE_ARGS]  #模塊的參數
               [-m MODULE_NAME]  #要執行的模塊,默認爲 command 
               pattern

Define and run a single task 'playbook' against a set of hosts

positional arguments:
  pattern               host pattern

optional arguments:
  --ask-vault-pass      ask for vault password
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  --playbook-dir BASEDIR
                        Since this tool does not use playbooks, use this as a
                        substitute playbook directory.This sets the relative
                        path for many features including roles/ group_vars/
                        etc.
  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it
  --vault-id VAULT_IDS  the vault identity to use
  --vault-password-file VAULT_PASSWORD_FILES
                        vault password file
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit
  -B SECONDS, --background SECONDS
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           # 只是測試一下會改變什麼內容,不會真正去執行
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library (def
                        ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
                        gins/modules)
  -P POLL_INTERVAL, --poll POLL_INTERVAL
                        set the poll interval if using -B (default=15)
  -a MODULE_ARGS, --args MODULE_ARGS
                        module arguments
  -e EXTRA_VARS, --extra-vars EXTRA_VARS
                        set additional variables as key=value or YAML/JSON, if
                        filename prepend with @
  -f FORKS, --forks FORKS
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY
                        specify inventory host path or comma separated host
                        list. --inventory-file is deprecated
  -l SUBSET, --limit SUBSET
                        further limit selected hosts to an additional pattern
  -m MODULE_NAME, --module-name MODULE_NAME
                        module name to execute (default=command)
  -o, --one-line        condense output
  -t TREE, --tree TREE  log output to this directory
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)

Privilege Escalation Options:
  control how and which user you become as on target hosts

  --become-method BECOME_METHOD
                        privilege escalation method to use (default=sudo), use
                        `ansible-doc -t become -l` to list valid choices.
  --become-user BECOME_USER
                        run operations as this user (default=root)
  -K, --ask-become-pass
                        ask for privilege escalation password
  -b, --become          run operations with become (does not imply password
                        prompting)

Connection Options:
  control as whom and how to connect to hosts

  --private-key PRIVATE_KEY_FILE, --key-file PRIVATE_KEY_FILE
                        use this file to authenticate the connection
  --scp-extra-args SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
  --sftp-extra-args SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f,
                        -l)
  --ssh-common-args SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g.
                        ProxyCommand)
  --ssh-extra-args SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)
  -T TIMEOUT, --timeout TIMEOUT
                        override the connection timeout in seconds
                        (default=10)
  -c CONNECTION, --connection CONNECTION
                        connection type to use (default=smart)
  -k, --ask-pass        ask for connection password
  -u REMOTE_USER, --user REMOTE_USER
                        connect as this user (default=None)

Some modules do not make sense in Ad-Hoc (include, meta, etc)
Ansible命令工具
ansible主程序,臨時命令執行工具
ansible-doc 查看配置文檔,模塊功能查看工具
ansible-galaxy 下載/上傳優秀代碼或Roles模塊的官網平臺
ansible-playbook 定製自動化任務,編排劇本工具
ansible-pull 遠程執行命令的工具
ansible-vault 文件加密工具
ansible-console 基於Console界面與用戶交互的執行工具

4.2 ansible-doc

模塊(也被稱爲 “task plugins” 或 “library plugins”)是在 Ansible 中實際在執行的.它們就 是在每個 playbook 任務中被執行的.你也可以僅僅通過 ‘ansible’ 命令來運行它們.

每個模塊都能接收參數. 幾乎所有的模塊都接受鍵值對(key=value)參數,空格分隔.一些模塊 不接收參數,只需在命令行輸入相關的命令就能調用.

#查看模塊說明
[root@localhost ~]# ansible-doc -s command

#列出所有已安裝的模塊文檔
[root@localhost ~]# ansible-doc -l 

4.3 group模塊(添加用戶組)

#創建用戶組
[root@localhost ~]# ansible all -m group -a "gid=3000 name=mygrp state=present system=no" 
[root@128 ~]# tail -1 /etc/group
mygrp:x:3000:

#移除用戶組
[root@localhost ~]# ansible all -m group -a "gid=3000 name=mygrp state=absent system=no"

#創建nginx組(system=yes表示創建的組是系統組) 
ansible all -m group -a 'name=nginx system=yes gid=80' 

參數說明:
- gid=  #設置組的GID號
- name=  #指定組的名稱
- state=  #指定組的狀態,默認爲創建,設置值爲absent爲刪除
- system=  #設置值爲yes,表示創建爲系統組

4.4 user模塊(添加用戶)

#添加用戶testuser,指定uid、家目錄、屬組、指定用戶的shell環境
[root@localhost ~]# ansible all -m user -a "uid=5000 name=testuser state=present home=/home/testuser groups=mygrp shell=/bin/tcsh"
[root@128 ~]# id testuser
uid=5000(testuser) gid=5000(testuser) groups=5000(testuser),3000(mygrp)
[root@128 ~]# tail -1 /etc/passwd
testuser:x:5000:5000::/home/testuser:/bin/tcsh

#添加一個系統用戶: 
ansible all -m user -a 'name=sysuser1 system=yes home=/home/sysuser1' 

#刪除用戶(當state=absent時,remove=yes則表示連同家目錄一起刪除,等價於userdel -r)
ansible all -m user -a 'name=sysuser1 state=absent remove=yes' 

#添加一個nginx用戶: 
ansible all -m user -a 'name=nginx shell=/sbin/nologin system=yes home=/var/nginx groups=root,bin uid=80 comment="nginx service"' 
[root@128 ~]# id nginx
uid=80(nginx) gid=80(nginx) groups=80(nginx),0(root),1(bin)

參數說明:
- comment  # 用戶的描述信息
- createhome  # 是否創建家目錄
force  # 在使用state=absent時, 行爲與userdel –force一致.
- group  # 指定基本組
- groups  # 指定附加組,如果指定爲(groups=)表示刪除所有組
- home  # 指定用戶家目錄
- move_home  # 如果設置爲home=時, 試圖將用戶主目錄移動到指定的目錄
- name  # 指定用戶名
- non_unique  # 該選項允許改變非唯一的用戶ID值
- password  # 指定用戶密碼
- remove  # 在使用state=absent時, 行爲是與userdel –remove一致
- shell  # 指定默認shell
- state  # 設置帳號狀態,不指定爲創建,指定值爲absent表示刪除
- system  # 當創建一個用戶,設置這個用戶是系統用戶。這個設置不能更改現有用戶
- uid  # 指定用戶的uid

4.5 copy模塊

#複製文件,指定權限爲600(默認權限是644),如目標存在先備份(默認覆蓋)
[root@localhost ~]# ansible all -m copy -a "src=/etc/fstab dest=/tmp/fstab.ansible mode=600 backup=yes" 
[root@128 ~]# ls -lh /tmp/
total 4.0K
drwx------ 2 root root  40 Mar 27 18:01 ansible_command_payload_dIGLu7
-rw------- 1 root root 465 Mar 30 11:24 fstab.ansible

#複製目錄
[root@localhost ~]# ansible all -m copy -a "src=/etc/pam.d/ dest=/tmp/" 

#寫內容直接生成文件,默認不換行
[root@localhost ~]# ansible all -m copy -a "content='hello 20200330\n' dest=/tmp/hi.txt owner=testuser group=mygrp" 
[root@128 ~]# ll /tmp/hi.txt 
-rw-r--r-- 1 testuser mygrp 15 Mar 30 11:29 /tmp/hi.txt

參數說明:
- src    #被複制到遠程主機的本地文件。可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,則會遞歸複製,用法類似於"rsync"
- content   #用於替換"src",可以直接指定文件的值
- dest    #必選項,將源文件複製到的遠程主機的絕對路徑
- backup   #當文件內容發生改變後,在覆蓋之前把源文件備份,備份文件包含時間信息
- directory_mode    #遞歸設定目錄的權限,默認爲系統默認權限
- force    #當目標主機包含該文件,但內容不同時,設爲"yes",表示強制覆蓋;設爲"no",表示目標主機的目標位置不存在該文件才複製。默認爲"yes"
- others    #所有的 file 模塊中的選項可以在這裏使用

4.6 command模塊

在遠程主機上運行命令(無法執行管道)

[root@localhost ~]# ansible all -m command  -a "hostname"
192.168.75.128 | CHANGED | rc=0 >>
128
[root@localhost ~]# ansible all -m command  -a "echo testuser | passwd --stdin testuser"
192.168.75.128 | CHANGED | rc=0 >>
testuser | passwd --stdin testuser

相關說明:
- 使用 command 模塊在遠程主機中執行命令時,不會經過遠程主機的 shell 處理。
- 在使用 command 模塊時,如果需要執行的命令中含有重定向、管道符等操作時,這些符號也會失效,比如 "<" , ">", "|", ";" 和 "&"這些符號,如果你需要這些功能,可使用 shell 模塊。
- 如果遠程節點是 windows 操作系統,則需要使用 win_command 模塊

4.7 shell模塊

在遠程主機shell進程下運行命令,支持shell特性,如管道、重定向等。與 command 模塊不同的是,shell 模塊在遠程主機中執行命令時,會經過遠程主機上的 /bin/sh 處理。

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

4.8 file模塊

#創建文件,指定屬主testuser,指定屬組mygrp,權限755(touch如果文件不存在,則會創建一個新的文件,如果文件或目錄已存在,則更新其最後修改時間)
ansible all -m file -a 'name=/tmp/file1 owner=testuser group=mygrp mode=755 state=touch'
[root@128 ~]# ll /tmp | grep file1
-rwxr-xr-x 1 testuser mygrp    0 Mar 30 17:38 file1

#刪除文件
ansible all -m file -a 'name=/tmp/file1 state=absent'

#創建目錄(如果目錄不存在,創建目錄)
ansible all -m file -a "path=/var/tmp/hello.dir state=directory" 

#刪除目錄
ansible all -m file -a "path=/var/tmp/hello.dir state=absent"

#創建軟鏈接
ansible all -m file -a "src=/tmp/hi.txt path=/var/tmp/hi.link state=link"
[root@128 ~]# ll /var/tmp/hi.link 
lrwxrwxrwx 1 root root 11 Mar 30 14:55 /var/tmp/hi.link -> /tmp/hi.txt

ansible all -m file -a 'src=/etc/fstab dest=/tmp/fstab.link state=link'
[root@128 ~]# ll /tmp/fstab.link
lrwxrwxrwx 1 root root 10 Mar 30 17:32 /tmp/fstab.link -> /etc/fstab

#刪除軟鏈接
ansible all -m file -a 'dest=/tmp/fstab.link state=absent'

參數說明:
- force  #需要在兩種情況下強制創建軟鏈接,一種是源文件不存在,但之後會建立的情況下;另一種是目標軟鏈接已存在,需要先取消之前的軟鏈,然後創建新的軟鏈,有兩個選項:yes|no
- group  #定義文件/目錄的屬組。後面可以加上mode:定義文件/目錄的權限
- owner  #定義文件/目錄的屬主。後面必須跟上path:定義文件/目錄的路徑
- recurse  #遞歸設置文件的屬性,只對目錄有效,後面跟上src:被鏈接的源文件路徑,只應用於state=link的情況
- dest  #被鏈接到的路徑,只應用於state=link的情況
- state  #狀態,有以下選項:
   directory:如果目錄不存在,就創建目錄
   file:即使文件不存在,也不會被創建
   link:創建軟鏈接
   hard:創建硬鏈接
   touch:如果文件不存在,則會創建一個新的文件,如果文件或目錄已存在,則更新其最後修改時間
   absent:刪除目錄、文件或者取消鏈接文件

4.9 cron模塊

設置定時任務,支持時間:minute,hour,day,month,weekday

#每週1,3,5,每3分鐘執行,任務名稱爲updatentp
ansible all -m cron -a "minute=* weekday=1,3,5 job='/usr/sbin/update ntp1.aliyun.com &> /dev/null' name=updatentp" 
[root@128 ~]# crontab -l
#Ansible: updatentp
* * * * 1,3,5 /usr/sbin/update ntp1.aliyun.com &> /dev/null

#註釋cronname=updatentp的計劃任務: 
ansible all -m cron -a "disabled=true job='/usr/sbin/update ntp1.aliyun.com &> /dev/null' name=updatentp"

#給cronname=updatentp的計劃任務去掉註釋
ansible all -m cron -a "disabled=false job='/usr/sbin/update ntp1.aliyun.com &> /dev/null' name=updatentp" 

#刪除定時任務
ansible all -m cron -a 'state=absent name=updatentp' 

參數說明:
- day= #日應該運行的工作( 1-31, *, */2, )
- hour= # 小時 ( 0-23, *, */2, )
- minute= #分鐘( 0-59, *, */2, )
- month= # 月( 1-12, *, /2, )
- weekday= # 周 ( 0-6 for Sunday-Saturday,, )
- job= #指明運行的命令是什麼
- name= #定時任務描述
- reboot # 任務在重啓時運行,不建議使用,建議使用special_time
- special_time #特殊的時間範圍,參數:reboot(重啓時),annually(每年),monthly(每月),weekly(每週),daily(每天),hourly(每小時)
- state #指定狀態,present表示添加定時任務,也是默認設置,absent表示刪除定時任務
- user # 以哪個用戶的身份執行

4.10 yum模塊

使用yum安裝程序包,安裝多個包用逗號隔開,前提是已配置好yum源

# ansible-doc -s yum  #查看yum模塊相關使用說明

# 安裝ntp模塊
ansible all -m yum -a "name=ntp state=installed"  
[root@128 ~]# rpm -q ntp
ntp-4.2.6p5-29.el7.centos.x86_64
[root@128 ~]# ps -ef | grep ntp
ntp       16810      1  0 15:21 ?        00:00:00 /usr/sbin/ntpd -untp:ntp -g
root      16824   9683  0 15:21 pts/1    00:00:00 grep --color=autontp

# 卸載vsftpd包: 
ansible all -m yum -a 'name=vsftpd state=removed'
# 安裝已下載好的rpm包:
ansible all -m yum -a 'name=/data/zlib-devel-1.2.7-18.el7.x86_64.rpm' 
#更新緩存: 
ansible srv -m yum -a 'update_cache=yes' 
#更新緩存同時安裝dstat包 
ansible srv -m yum -a 'name=dstat update_cache=yes'

參數說明:
- name=  #所安裝的包的名稱
- state=  #present--->安裝, latest--->安裝最新的, absent---> 卸載軟件。
- update_cache  #強制更新yum的緩存
- conf_file  #指定遠程yum安裝時所依賴的配置文件(安裝本地已有的包)。
- disable_pgp_check  #是否禁止GPG checking,只用於presentor latest。
- disablerepo  #臨時禁止使用yum庫。 只用於安裝或更新時。
- enablerepo  #臨時使用的yum庫。只用於安裝或更新時。

4.11 service模塊

#啓動服務
ansible all -m service -a "name=ntpd state=started"

#停止服務
ansible all -m service -a "name=ntpd state=stopped"

#重新加載httpd服務: 
ansible srv -m service -a 'name=httpd state=reloaded’
#重啓httpd服務: 
ansible srv -m service -a 'name=httpd state=restarted’
#開啓ftp服務,同時設置開機自動啓動: 
ansible srv -m service -a 'name=vsftpd state=started enabled=yes’ 

參數說明:
- runlevel:開機啓動的級別,一般不用指定
- sleep:如果執行了restarted,在則stop和start之間沉睡幾秒鐘
- arguments #命令行提供額外的參數
- enabled #設置開機啓動。
- name= #服務名稱
- state #有四種狀態,分別爲:started--->啓動服務, stopped--->停止服務, restarted--->重啓服務,reloaded--->重載配置

4.12 script模塊

在遠程主機上執行 ansible 管理主機上的腳本。腳本一直存在於 ansible 管理主機本地,不需要手動拷貝到遠程主機後再執行。

[root@localhost ~]# cat /tmp/test.sh
#!/bin/bash
echo "ansible script test" > /tmp/ansible.txt
[root@localhost ~]# ansible all -m script -a "/tmp/test.sh"
192.168.75.128 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.75.128 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.75.128 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

4.13 template模塊

基於模板方式生成一個文件複製到遠程主機(template使用Jinjia2格式作爲文件模版,進行文檔內變量的替換的模塊。它的每次使用都會被ansible標記爲”changed”狀態。)

參數說明:
- backup: 如果原目標文件存在,則先備份目標文件
- src:在ansible控制器上的Jinja2格式化模板的路徑。 這可以是相對或絕對的路徑。
- dest:將模板渲染到遠程機器上的位置。
- force:是否強制覆蓋,默認爲yes
- owner:目標文件屬主
- group:目標文件屬組
- mode:目標文件的權限模式,模式可以被指定爲符號模式(例如,u + rwx或u = rw,g = r,o = r)。

4.14 setup模塊

收集指定服務器的信息,每個被管理節點在接收並運行管理命令之前,會將自己主機相關信息,如操作系統版本、IP地址等報告給遠程的ansbile主機。在playbooks裏經常會用到的一個參數gather_facts就與該模塊相關。

[root@localhost ~]# ansible all -m setup -a "filter=ansible_os_family"
192.168.75.128 | SUCCESS => {
    "ansible_facts": {
        "ansible_os_family": "RedHat", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

參數說明:
ansible_all_ipv4_addresses:僅顯示ipv4的信息
ansible_devices:僅顯示磁盤設備信息
ansible_distribution:顯示是什麼系統,例:centos,suse等
ansible_distribution_major_version:顯示是系統主版本
ansible_distribution_version:僅顯示系統版本
ansible_machine:顯示系統類型,例:32位,還是64位
ansible_eth0:僅顯示eth0的信息
ansible_hostname:僅顯示主機名
ansible_kernel:僅顯示內核版本
ansible_lvm:顯示lvm相關信息
ansible_memtotal_mb:顯示系統總內存
ansible_memfree_mb:顯示可用系統內存
ansible_memory_mb:詳細顯示內存情況
ansible_swaptotal_mb:顯示總的swap內存
ansible_swapfree_mb:顯示swap內存的可用內存
ansible_mounts:顯示系統磁盤掛載情況
ansible_processor:顯示cpu個數(具體顯示每個cpu的型號)
ansible_processor_vcpus:顯示cpu個數(只顯示總的個數)
ansible_python_version:顯示python版本

4.15 fetch模塊

從遠程某主機獲取(複製)文件到本地

#打包 /var/log 下所有日誌文件並遠程抓取
ansible all -m shell -a 'tar Jcf log.tar.xz /var/log/*.log'
ansible all -m fetch -a 'src=/root/log.tar.xz dest=/tmp'

參數說明:
- src:遠程系統上要獲取的文件。 這必須是一個文件,而不是一個目錄。 後續版本可能會支持遞歸提取。
-dest:保存文件的目錄。 例如,如果dest目錄是/backup,在主機host.example.com上命名爲/ etc/profile的src文件將被保存到/backup/host.example.com/etc/profile。
- flat:允許您覆蓋將目標文件添加到主機名/ path / to / file的默認行爲。

4.16 apt模塊

# 在安裝foo軟件包前更新然後安裝foo 
ansible all -m apt -a 'name=foo update_cache=yes'
# 移除foo軟件包
ansible all -m apt -a 'name=foo state=absent'
# 安裝foo軟件包
ansible all -m apt -a 'name=foo state=present'
# 安裝foo 1.0軟件包
ansible all -m apt -a 'name=foo=1.00 state=present'
# 安裝nginx最新的名字爲squeeze-backport發佈包,並且安裝前執行更新
ansible all -m apt -a 'name=nginx state=latest default_release=squeeze-backports update_cache=yes'
# 只下載openjdk-6-jdk最新的軟件包,不安裝
ansible all -m apt -a 'name=openjdk-6-jdk state=latest install_recommends=no'
# 安裝所有軟件包到最新版本
ansible all -m apt -a 'upgrade=dist'
# 更新apt-get的list
ansible all -m apt -a 'update_cache=yes'
# 3600秒後停止update_cache
ansible all -m apt -a 'update_cache=yes cache_valid_time=3600'
# 安裝遠程節點上的/tmp/mypackage.deb軟件包
ansible all -m apt -a 'deb=/tmp/mypackage.deb'

參數說明:
- deb: 用於安裝遠程機器上的.deb後綴的軟件包(optional)
- install_recommends:這個參數可以控制遠程電腦上是否只是下載軟件包,還是下載後安裝,默認參數爲true,設置爲false的時候只下載軟件包,不安裝
- update_cache: 當這個參數爲yes的時候等於apt-get update(optional)
- name: apt要下載的軟件包名字,支持name=git=1.6 這種制定版本的模式
- state:狀態(present,absent,latest),表示是安裝還卸載
   present:默認的,表示爲安裝
   lastest: 安裝爲最新的版本
   absent:表示刪除
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章