運維自動化-Ansible ( 二 )

此章節的版本信息以下:html

ansible 2.4.2.0
python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

ping

功能:嘗試鏈接到主機,驗證並返回pong成功。node

-對於Windows目標,請改用win_ping模塊
-不使用icmp協議,使用ssh協議。
例子:
#ansible db -m ping
7-db-3.hunk.tech | SUCCESS => {
    "changed": false, 
    "ping": "pong"                > 返回pong代表成功通信
}

command

功能:在遠程節點上執行命令python

-變量 和操做符號 "<", ">", "|", ";" and "&" 不能正常工做。若是須要使用,請使用shell模塊
-Ansible默認不指定模塊時,將使用此模塊。
- chdir
        命令運行前先切換到此目錄

- creates
        條件判斷,若是文件存在,將不執行後面的命令。
        #ansible web -m command -a 'creates=/app echo /app not found'
        6-web-1.hunk.tech | SUCCESS | rc=0 >>
        skipped, since /app exists

= free_form
        The command module takes a free form command to run.  There is no parameter actually named 'free form'. See the
        examples!

- removes
        條件判斷,若是文件不存在,將不執行後面的命令。
        #ansible web -m command -a 'removes=/app echo /app not found'
        6-web-1.hunk.tech | SUCCESS | rc=0 >>
        /app not found

- stdin
        將命令的stdin直接設置爲指定的值

- warn
       若是 ansible.cfg 設置了開啓警報, 將不會對這一行進行警報

shell

功能:在遠程節點上執行命令。與command模快使用一致,可是,變量 和操做符號 "<", ">", "|", ";" and "&" 能正常工做linux

下面2個例子對比能清晰的表示出不一樣的地方

#ansible db -m command -a 'echo $RANDOM'
7-db-3.hunk.tech | SUCCESS | rc=0 >>
$RANDOM

#ansible db -m shell -a 'echo $RANDOM'
7-db-3.hunk.tech | SUCCESS | rc=0 >>
5159

這些複雜命令,即便使用shell也可能會失敗,解決辦法:寫到腳本時,
copy到遠程,執行,再把須要的結果拉回執行命令的機器
#ansible web -m shell -a df | awk '{print $5}'

script

功能:把腳本複製到遠程節點後,在遠程節點本地運行腳本nginx

給定的腳本將經過遠程節點上的shell環境進行處理。
這個模塊在遠程系統上不須要python,就像原始腳本同樣。
#ansible web -m script -a './shell.sh'

6-web-1.hunk.tech | SUCCESS => {
        "Wed Jan 31 23:17:17 CST 2018", 
        "/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
}

copy

功能:複製文件或目錄到遠程節點。默認會覆蓋目標文件git

backup:在覆蓋以前將原文件備份,備份文件包含時間信息。有兩個選項:yes|no 
content:用於替代"src",能夠直接設定指定文件的內容,至關於echo 重定向內容到文件
dest:必選項。要將源文件複製到的遠程主機的絕對路徑,若是源文件是一個目錄,那麼該路徑也必須是個目錄 
directory_mode:遞歸的設定目錄的權限,默認爲系統默認權限
force:若是目標主機包含該文件,但內容不一樣,若是設置爲yes,則強制覆蓋,若是爲no,則只有當目標主機的目標位置不存在該文件時,才複製。默認爲yes
others:全部的file模塊裏的選項均可以在這裏使用
src:要複製到遠程主機的文件在本地的地址,能夠是絕對路徑,也能夠是相對路徑。若是路徑是一個目錄,它將遞歸複製。在這種狀況下,若是路徑使用"/"來結尾,則只複製目錄裏的內容,若是沒有使用"/"來結尾,則包含目錄在內的整個內容所有複製,相似於rsync。

#ansible dns -m copy -a 'src=/tmp/abc.txt  dest=/app backup=yes'

複製目錄時,斜線不要寫
#ansible dns -m copy -a 'src=/tmp/dir1  dest=/app'

根據內容生成文件,至關於echo abc123 > /app/123.txt
#ansible dns -m copy -a 'content="abc123"  dest=/app/123.txt'

fetch

功能:從遠程節點獲取文件(只能是文件)到本地目錄。默認會以主機清單中的主機名爲目錄存放獲取到的文件github

#ansible all -m fetch -a 'src=/var/log/messages dest=/app'
#tree -L 1 /app
/app
├── 6-dns-1.hunk.tech
├── 6-web-1.hunk.tech
├── 7-db-3.hunk.tech
├── 7-web-0.hunk.tech
└── 7-web-2.hunk.tech

注意,src=/var/log/mess*   這種通配符語法是不支持的

file

功能:設置遠程節點的文件的文件屬性web

force:須要在兩種狀況下強制建立軟連接,一種是源文件不存在但以後會創建的狀況下;另外一種是目標軟連接已存在,須要先取消以前的軟鏈,而後建立新的軟鏈,有兩個選項:yes|no 
group:定義文件/目錄的屬組 
mode:定義文件/目錄的權限
owner:定義文件/目錄的屬主
path:必選項,定義文件/目錄的路徑
recurse:遞歸的設置文件的屬性,只對目錄有效
src:要被連接的源文件的路徑,只應用於state=link的狀況
dest:被連接到的路徑,只應用於state=link的狀況 
state:  操做方法
    directory:若是目錄不存在,建立目錄
    file:即便文件不存在,也不會被建立
    link:建立軟連接
    hard:建立硬連接
    touch:若是文件不存在,則會建立一個新的文件,若是文件或目錄已存在,則更新其最後修改時間
    absent:刪除目錄、文件或者取消連接文件。至關於rm -rf

建立空文件,相似於touch    
#ansible dns -m file -a 'path=/app/dir2/abc.txt state=touch mode=0666 owner=ftp'    

建立空目錄, 相似於mkdir -p
#ansible dns -m file -a 'path=/app/dir2/dir3/dir4 state=directory mode=0666 owner=ftp'

├ dir2
│ └── dir3
│     └── dir4

建立軟連接
#ansible dns -m file -a 'path=/app/abc.txt state=link src=/app/dir2/abc.txt'
lrwxrwxrwx  1 root root   17 Feb  1 00:58 abc.txt -> /app/dir2/abc.txt

hostname

功能:設置遠程節點主機名正則表達式

#ansible dns -m hostname -a 'name=6-dns-1.hunk.tech'

cron

功能:管理計劃任務shell

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 dns -m cron -a 'name="test cron job" minute=*/2 job="/usr/bin/wall hello world"'

禁用某個計劃任務

#Ansible: test cron job
*/2 * * * * /usr/bin/wall hello world

正確的寫法:必須完整的寫完,包括name等屬性
#ansible dns -m cron -a 'disabled=yes name=None minute=*/3 job="/usr/bin/wall hello world"'

#ansible dns -m cron -a 'disabled=yes job="/usr/bin/wall hello world"'   > 這種寫法是不對的,它會建立一條如下記錄並禁用它
#Ansible: None
#* * * * * /usr/bin/wall hello world

刪除計劃任務
#ansible dns -m cron -a 'state=absent name=None'

yum

功能:使用yum包管理器來管理軟件包

config_file:yum的配置文件 
disable_gpg_check:關閉gpg_check 
disablerepo:不啓用某個源 
enablerepo:啓用某個源
name:要進行操做的軟件包的名字,也能夠傳遞一個url或者一個本地的rpm包的路徑 
state:Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package.
        (可選值: present, installed, latest, absent, removed) [Default: present]

#ansible all -m yum -a 'name=tree state=present'

#ansible all -a 'rpm -q tree' -o
6-web-1.hunk.tech | SUCCESS | rc=0 | (stdout) tree-1.5.3-3.el6.x86_64
6-dns-1.hunk.tech | SUCCESS | rc=0 | (stdout) tree-1.5.3-3.el6.x86_64
7-web-0.hunk.tech | SUCCESS | rc=0 | (stdout) tree-1.6.0-10.el7.x86_64
7-web-2.hunk.tech | SUCCESS | rc=0 | (stdout) tree-1.6.0-10.el7.x86_64
7-db-3.hunk.tech | SUCCESS | rc=0 | (stdout) tree-1.6.0-10.el7.x86_64

yum_repository

功能:配置管理yum源

reposdir: repo文件存放目錄
file:      repo文件名,默認爲name的值
name:       惟一的repository ID
gpgkey:設置gpgkey
gpgcheck:設置gpg檢查
enabled:設置開啓關閉
bandwidth:控制帶寬,0爲無限
state:狀態(present,absent
description:描述

#ansible dns -m yum_repository -a 'state=present name=epel enabled=yes gpgcheck=yes description="Aliyun EPEL" baseurl="http://mirrors.aliyun.com/epel/6/$basearch,http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/" gpgkey="https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-6Server"'

service

功能:配置管理服務

arguments:給命令行提供一些選項 。可使用別名 args
enabled:是否開機啓動 yes|no
name:必選項,服務名稱 
pattern:定義一個模式,若是經過status指令來查看服務的狀態時,沒有響應,就會經過ps指令在進程中根據該模式進行查找,若是匹配到,則認爲該服務依然在運行
runlevel:運行級別
sleep:若是執行了restarted,在則stop和start之間沉睡幾秒鐘
state:對當前服務執行啓動,中止、重啓、從新加載等操做(started,stopped,restarted,reloaded)

#ansible db -m service -a 'name=httpd state=started'  > 一次只能操做一個服務

setup

功能:收集關於遠程主機的信息。

在playbooks裏常常會用到的一個參數gather_facts就與該模塊相關

--tree :將全部主機的輸出信息保存到/tmp/目錄下,以/etc/ansible/hosts裏的主機名爲文件名
ansible all -m setup -a 'filter=ansible_distribution_version' --tree /tmp/

filter :過濾關鍵字
#ansible db -m setup -a 'filter=ansible_distribution_version'

gather_subset:按子集收集信息,值有all, min, hardware, network, virtual, ohai, facter。不包含請使用!號,如,!network
關鍵字 說明 返回值例子
ansible_nodename 節點名 "6-dns-1.hunk.tech"
ansible_fqdn FQDN名 "6-dns-1.hunk.tech"
ansible_hostname 主機短名稱 "6-dns-1"
ansible_domain 主機域名後綴 "hunk.teh"
ansible_memtotal_mb 總物理內存 "ansible_memtotal_mb": 222
ansible_swaptotal_mb SWAP總大小 "1023"
ansible_processor CPU信息 Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz
ansible_processor_cores CPU核心數量 4
ansible_processor_vcpus CPU邏輯核心數量 2
ansible_all_ipv4_addresses 有所IPV4地址 192.168.0.200
ansible_all_ipv6_addresses 全部IPV6地址
ansible_default_ipv4 默認網關的網卡配置信息
ansible_eth2 具體某張網卡信息 不一樣系統名稱須要變化
ansible_dns DNS設置信
ansible_architecture 系統架構 x86_64
ansible_machine 主機類型 x86_64
ansible_kernel 內核版本 "2.6.32-696.el6.x86_64"
ansible_distribution 發行版本 "CentOS"
ansible_distribution_major_version 操做系統主版本號 "6"
ansible_distribution_release 發行版名稱 "Final"
ansible_distribution_version 完整版本號 "7.4.1708"
ansible_pkg_mgr 軟件包管理方式 "yum"
ansible_service_mgr 進行服務方式 "systemd"
ansible_os_family 家族系列 "RedHat"
ansible_cmdline 內核啓動參數
ansible_selinux SElinux狀態 "disabled"
ansible_env 當前環境變量參數
ansible_date_time 時間相關
ansible_python_version python版本 "2.6.6"
ansible_lvm LVM卷相關信息
ansible_mounts 全部掛載點
ansible_device_links 全部掛載的設備的UUID和卷標名
ansible_devices 全部/dev/下的正在使用的設備的信息
ansible_user_dir 執行用戶的家目錄 "/root"
ansible_user_gecos 執行用戶的描述信息 "The root "
ansible_user_gid 執行用戶的的GID 0
ansible_user_id 執行用戶的的用戶名 "root"
ansible_user_shell 執行用戶的shell類型 "/bin/bash"
ansible_user_uid 執行用戶的UID 0

user

功能:管理用戶帳號

選項太多,與useradd這類系統命令差很少
http://docs.ansible.com/ansible/latest/user_module.html

name:用戶名,可使用別名user
#ansible db -m user -a 'name=hunk4 shell=/sbin/nologin system=yes comment="name is hunk"'
7-db-3.hunk.tech | SUCCESS => {
    "changed": true, 
    "comment": "name is hunk", 
    "createhome": true, 
    "group": 996, 
    "home": "/home/hunk4", 
    "name": "hunk4", 
    "shell": "/sbin/nologin", 
    "state": "present", 
    "system": true, 
    "uid": 998
}

刪除用戶
#ansible db -m user -a 'name=hunk4 state=absent'
7-db-3.hunk.tech | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "hunk4", 
    "remove": false, 
    "state": "absent"
}

修改用戶指定信息
#ansible db -m user -a 'name=hunk4 state=present comment=" hunk is my"'

remove:刪除用戶時一併刪除用戶家目錄,須要與state=absent一塊兒使用

#ansible db -m user -a 'name=hunk3 state=absent remove=yes'
7-db-3.hunk.tech | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "hunk3", 
    "remove": true, 
    "state": "absent"
}

state:操做方法。(present , absent)

groups: 添加輔助組
group: 指定用戶的主組

如下這個例子注意看,group和groups所表明的含義不一樣。
    - name: add user
      user: name={{ username }} group=ftp groups={{ groupname }}

group

功能:添加組或刪除組

group模塊請求的是groupadd, groupdel, groupmod 三個指令.
用法都是差很少的。

get_url

功能:從 HTTP, HTTPS, or FTP 下載文件

checksum:下載完成後進行checksum;格式: e.g. checksum="sha256:D98291AC[...]B6DC7B97".值有sha1, sha224, sha384, sha256, sha512, md5
timeout:下載超時時間,默認10s
url:下載的URL
url_password、url_username:主要用於須要用戶名密碼進行驗證的狀況
use_proxy:是事使用代理,代理需事先在環境變動中定義
force:yes目標存在時是否下載,no目標文件不存在時下載
backup:建立一個包含時間戳信息的備份文件

#ansible dns -m get_url -a 'dest=/app/ url="https://github.com/bennojoy/nginx/archive/master.zip"'

#ansible dns -m get_url -a 'dest=/app/ELS.txt checksum=sha1:8c9e20bd25525c3ed04ebaa407097fe875f02b2c url="ftp://172.18.0.1/pub/Files/ELS.txt" force=yes'
6-dns-1.hunk.tech | SUCCESS => {
    "changed": false, 
    "checksum_dest": "8c9e20bd25525c3ed04ebaa407097fe875f02b2c", 
    "checksum_src": "8c9e20bd25525c3ed04ebaa407097fe875f02b2c",

fail

功能:自定義消息失敗

- fail:
    msg: "The system may not be provisioned according to the CMDB status."
  when: cmdb_status != "to-be-staged"

默認返回 'Failed as requested from task'

lineinfile

功能:替換一個文件中特定的行,或者使用一個反引用的正則表達式替換一個現有的行。

只有找到的最後一行將被替換
backup:建立一個包含時間戳信息的備份文件
backrefs:  爲no時,若是沒有匹配,則添加一行line。若是匹配了,則把匹配內容替被換爲line內容。
            爲yes時,若是沒有匹配,則文件保持不變。若是匹配了,把匹配內容替被換爲line內容。
insertafter:配合state=present。該行將在指定正則表達式的最後一個匹配以後插入。一個特殊的價值是在EOF; EOF用於在文件的末尾插入行。若是指定的正則表達式沒有匹配,則將使用EOF
insertBefore:state=present。該行將在指定正則表達式的最後一個匹配以前插入。 BOF用於在文件的開頭插入行。若是指定的正則表達式不匹配,則該行將被插入到文件的末尾。不能使用backrefs
valiate:在保存sudoers文件前,驗證語法,若是有錯,執行時,會報出來,從新編輯playbook
regexp: 正則表達式
# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- lineinfile:
    path: /etc/selinux/config
    regexp: '^SELINUX='
    line: 'SELINUX=enforcing'

- lineinfile:
    path: /etc/sudoers
    state: absent
    regexp: '^%wheel'

- lineinfile:
    path: /etc/hosts
    regexp: '^127\.0\.0\.1'
    line: '127.0.0.1 localhost'
    owner: root
    group: root
    mode: 0644

- lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: '^Listen '
    insertafter: '^#Listen '
    line: 'Listen 8080'

- lineinfile:
    path: /etc/services
    regexp: '^# port for http'
    insertbefore: '^www.*80/tcp'
    line: '# port for http by default'

# Add a line to a file if it does not exist, without passing regexp
- lineinfile:
    path: /tmp/testfile
    line: '192.168.1.99 foo.lab.net foo'

# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%wheel\s'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'

# Yaml requires escaping backslashes in double quotes but not in single quotes
- lineinfile:
    path: /opt/jboss-as/bin/standalone.conf
    regexp: '^(.*)Xms(\\d+)m(.*)$'
    line: '\1Xms${xms}m\3'
    backrefs: yes

# Validate the sudoers file before saving
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%ADMIN ALL='
    line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
    validate: '/usr/sbin/visudo -cf %s'

replace

功能:替換一個文件中符合匹配的全部行,或者使用一個反引用的正則表達式替換全部的行。

- replace:
        path: /etc/selinux/config
        regexp: '^SELINUX=.*'
        replace: 'SELINUX=disabled'

# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- replace:
    path: /etc/hosts
    regexp: '(\s+)old\.host\.name(\s+.*)?$'
    replace: '\1new.host.name\2'
    backup: yes

# Replace after the expression till the end of the file (requires >=2.4)
- replace:
    path: /etc/hosts
    regexp: '(\s+)old\.host\.name(\s+.*)?$'
    replace: '\1new.host.name\2'
    after: 'Start after line.*'
    backup: yes

# Replace before the expression till the begin of the file (requires >=2.4)
- replace:
    path: /etc/hosts
    regexp: '(\s+)old\.host\.name(\s+.*)?$'
    replace: '\1new.host.name\2'
    before: 'Start before line.*'
    backup: yes

# Replace between the expressions (requires >=2.4)
- replace:
    path: /etc/hosts
    regexp: '(\s+)old\.host\.name(\s+.*)?$'
    replace: '\1new.host.name\2'
    after: 'Start after line.*'
    before: 'Start before line.*'
    backup: yes

- replace:
    path: /home/jdoe/.ssh/known_hosts
    regexp: '^old\.host\.name[^\n]*\n'
    owner: jdoe
    group: jdoe
    mode: 0644

- replace:
    path: /etc/apache/ports
    regexp: '^(NameVirtualHost|Listen)\s+80\s*$'
    replace: '\1 127.0.0.1:8080'
    validate: '/usr/sbin/apache2ctl -f %s -t'

- name: short form task (in ansible 2+) necessitates backslash-escaped sequences
  replace: dest=/etc/hosts regexp='\\b(localhost)(\\d*)\\b' replace='\\1\\2.localdomain\\2 \\1\\2'

- name: long form task does not
  replace:
    dest: /etc/hosts
    regexp: '\b(localhost)(\d*)\b'
    replace: '\1\2.localdomain\2 \1\2'

模塊太多了,這裏僅僅是列出範例用法。

請使用ansible-doc或者去官網吧。http://docs.ansible.com/

相關文章
相關標籤/搜索