Ansible之inventory和常用模塊介紹

一敦锌、inventory介紹

前面我們介紹過(guò)ansible的hosts文件是存放被管理主機(jī)的盒发,被管理主機(jī)比較少的情況下橄碾,直接在hosts中定義即可,但是以后很定會(huì)管理多臺(tái)主機(jī)级及,而ansible可管理的主機(jī)集合就叫做inventory乒疏。在ansible中,描述你主機(jī)的默認(rèn)方法是將它們列在一個(gè)文本文件中,這個(gè)文件叫inventory文件饮焦。
一個(gè)簡(jiǎn)單的inventory文件可能只包含一組主機(jī)名的列表怕吴,如下:

ftp.testansible.com
samba.testansible.com
mail.testansible.com
  1. inventory的行為參數(shù)
    有時(shí)候我們需要在ansible inventory文件中描述我們的主機(jī),我們需要定義主機(jī)名县踢,以及ansible的ssh客戶(hù)端可以連接到的端口(22,2222,22300)等转绷,那么ansible將這些變量命名為inventory的行為參數(shù),如下:
    名稱(chēng)                            默認(rèn)值                                描述
    ansible_ssh_host               主機(jī)的名字                             SSH目的主機(jī)名或IP
    ansible_ssh_port               22                                   SSH目的端口
    ansible_ssh_user               root                                 SSH登錄使用的用戶(hù)名
    ansible_ssh_pass               none                                 SSH認(rèn)證所使用的密碼
    ansible_connection             smart                                ansible使用何種連接模式連接到主機(jī)
    ansible_ssh_private_key_file   none                                 SSH認(rèn)證所使用的私鑰
    ansible_shell_type             sh                                   命令所使用的shell
    ansible_python_interpreter     /usr/bin/python                      主機(jī)上的python解釋器
    
    ansible默認(rèn)的inventory文件是/etc/ansible/hosts
    可以自定義動(dòng)態(tài)的inventory文件硼啤,(--inventory-file等同于-i path)如下
    #ansible --inventory-file=/root/iptables/iptableshosts iptables -m script -a '/root/iptables/check_iptables.sh'
    
    如果有多臺(tái)服務(wù)器的話(huà)议经,想并發(fā)運(yùn)行,可以使用-f參數(shù)谴返,默認(rèn)是并發(fā)5
    #ansible --inventory-file=/root/iptables/iptableshosts iptables -f 6 -m script -a '/root/iptables/check_iptables.sh'
    
  2. 主機(jī)和主機(jī)組定義方式:
    直接定義一臺(tái)或者2臺(tái)server
    #vim /etc/ansible/hosts 
    192.168.100.10          
    192.168.100.11
    
    定義一個(gè)組,可以是ip也可以是解析好的域名
    [web]
    192.168.100.10
    192.168.100.11
    [httpd]
    192.168.100.12
    192.168.100.13
    
    嵌套定義組
    [apache]
    http1.test.com
    http2.test.com
    [nginx]
    nginx1.test.com
    nginx2.test.com
    [webservers:children]
    apache
    nginx
    
  3. 主機(jī)變量和組變量
    主機(jī)變量:針對(duì)單主機(jī)的特性化要求煞肾,通過(guò)內(nèi)置變量實(shí)現(xiàn),如下:
    [webservers]
    web1.test.com http_port=80 ansible_ssh_port=12345
    
    群組變量
    語(yǔ)法:[<group name>:vars] 在inventory中指定群組變量亏镰,如下:
    [all:vars]
    ntp_server=ntp.centos.com
     
    [production]
    test1
    test2
    test3
    [production:vars]
    db_primary_port=22
     
    [groupservers]
    web1.test.com
    web2.test.com
    [groupservers:vars]
    ntp_server=ntp.test.com
    admin_user=tom
    
  4. 嵌套組和組變量
    [apache]
    http1.test.com
    http2.test.com
     
    [nginx]
    nginx1.test.com
    nginx2.test.com
     
    [webservers:children]
    apache
    nginx
     
    [webservers:vars]
    ntp_server=ntp.test.com
    
  5. 變量分離
    變量除了可以和inventory一起存儲(chǔ)在INI配置文件中扯旷,也可以獨(dú)立出來(lái)。
    當(dāng)我們要為非常多的主機(jī)和主機(jī)組分別設(shè)置不同的變量時(shí)索抓,用如上的方式就顯得比較笨拙了钧忽,就需要用到group_vars和host_vars 變量了。Ansible在運(yùn)行任何yml文件之前逼肯,都會(huì)去搜索與Hosts文件同一個(gè)目錄下的兩個(gè)用于定義變量的目錄group_vars和host_vars耸黑,所以,我們可以在這兩個(gè)目錄下放一些使用YAML語(yǔ)法編輯的定義變量的文件篮幢,并以對(duì)應(yīng)的主機(jī)名和主機(jī)組名來(lái)命名這些文件大刊,這樣在運(yùn)行ansible時(shí)
    ansible會(huì)自動(dòng)去這兩個(gè)目錄下讀取針對(duì)不同主機(jī)和主機(jī)組的變量定義
    比如對(duì)主機(jī)組group設(shè)置變量:
    File: /etc/ansible/group_vars/group
    admin_user: tom
    
    對(duì)主機(jī)host1設(shè)置變量
    File: /etc/ansible/host_vars/host1
    admin_user: john
    
    除此之外,我們還可以在group_vars和host_vars兩個(gè)文件夾下定義all文件來(lái)一次性地為所有的主機(jī)組和主機(jī)定義變量三椿。如何巧妙使用主機(jī)變量和組變量有些時(shí)候缺菌,我們?cè)谶\(yùn)行ansible任務(wù)時(shí),可能需要從一臺(tái)遠(yuǎn)程主機(jī)上面獲取另一臺(tái)遠(yuǎn)程主機(jī)的變量信息搜锰,這時(shí)一個(gè)神奇的變量hostvars可以幫我們實(shí)現(xiàn)這一個(gè)需求伴郁。變量hostvars包含了指定主機(jī)上面所定義的所有變量。
    比如我們想獲取host1上面的變量admin_user的內(nèi)容蛋叼,在任意主機(jī)上直接使用如下代碼即可:
    {{ hostvars['host1']['admin_user'] }}
    Ansible提供了一些非常有用的內(nèi)置變量焊傅,這里我們列舉幾個(gè)常用的:
    a剂陡、groups: 包含了所有Hosts文件里面主機(jī)組的一個(gè)列表
    b、group_names: 包含了當(dāng)前主機(jī)所在的所有主機(jī)組名的一個(gè)列表
    c狐胎、inventory_hostname: 通過(guò)Hosts文件定義主機(jī)的主機(jī)名和ansible_home不一定相同
    d鸭栖、play_hosts: 將會(huì)執(zhí)行當(dāng)前任務(wù)的所有主機(jī)
  6. yml文件中使用變量的一個(gè)例子:
    ---
    - hosts: all
      user: root
      vars:
        GETURL:"http://192.168.24.14/sa"
        TARFILE:"sa"
        TMPPATCH:"/tmp"
        SHFILE:"os.sh" 
      tasks:
        - name: Download `TARFILE`.tar.gz package
          get_url: url="`GETURL`/`TARFILE`.tar.gz" dest=`TMPPATCH` sha256sum=b6f482b3c26422299f06524086d1f087e1d93f2748be18542945bca4c2df1569
          tags:
            -downsa 
        - name: tarzxvf `TARFILE`.tar.gz file
          shell: tar zxvf "`TMPPATCH`/`TARFILE`.tar.gz" -C `TMPPATCH`
          tags:
            -tarxsa
        - name: Run`SHFILE` script
          shell: "`TMPPATCH`/`TARFILE`/`SHFILE`"
          tags:
            -runsa
    

二、ansible常用模塊介紹:

ansible的每個(gè)模塊用法可以使用#ansible-doc MOD 來(lái)查看握巢,如下范例:

#ansible-doc copy
less 436
Copyright (C) 1984-2009 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
> COPY
 
  The [copy] module copies a file on the local box to remote locations. Use the [fetch] module to copy files from remote locations to the local box. If you need
  variable interpolation in copied files, use the [template] module.
 
Options (= is mandatory):
 
- backup
……………………還有很多可以顯示晕鹊,此處省略

查看所支持的模塊,可以使用ansible-doc -l 查看镜粤,如下:

#ansible-doc -l
less 436
Copyright (C) 1984-2009 Mark Nudelman
 
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
a10_server                    Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                                                                                                       
a10_service_group             Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                                                                                                       
a10_virtual_server            Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                                                                                                       
acl                           Sets and retrieves file ACL information.                                                                                                                                     
add_host                      add a host (and alternatively a group) to the ansible-playbook in-memory inventory                                                                                           
airbrake_deployment           Notify airbrake about app deployments                                                                                                                                        
alternatives                  Manages alternative programs for common commands                                                                                                                             
apache2_module                enables/disables a module of the Apache2 webserver                                                                                                                           
apt                           Manages apt-packages     
……………………還有很多模塊可以顯示捏题,這里省略
  1. 遠(yuǎn)程命令模塊
    command、script 肉渴、shell
    Examples:
    # Example from Ansible Playbooks
    - script: /some/local/script.sh --some-arguments 1234
    例如:

    #ansible host1 -m command -a "free -m"   #可以簡(jiǎn)寫(xiě)為ansible host1 -a "free -m"
    #ansible host1 -m script -a "/home/test.sh 12 34"
    #ansible host1 -m shell -a "/home/test.sh"
    

    比如在服務(wù)端執(zhí)行:

    #ansible web -m shell -a "/root/test.sh 3 4 "
    10.0.90.25 | success | rc=0 >>
    7
    20151119-171933
    10.0.90.24 | success | rc=0 >>
    7
    20151119-171933
    

    注:test.sh 在客戶(hù)端服務(wù)器/root目錄公荧,內(nèi)容是前兩個(gè)位置變量相加,并打印出當(dāng)前時(shí)間同规。

    一個(gè)簡(jiǎn)單的創(chuàng)建目錄的例子循狰,創(chuàng)建/usr/local/src/data/log 目錄,如下:

    #cat test1.sh 
    #!/bin/bash
    if [ -z $1 ] || [ -z $2 ];then
       echo "Wrong,Please input two args"
       echo "Usage `basename $0` arguments arguments"
       exit 6
    fi
    mkdir -pv /usr/local/src/$1/$2
    #cat createdir.yml 
    ---
    - hosts: "{{ host }}"
      user: "{{ user }}"
      gather_facts: True
      tasks:
        - name: Create Dir in client server
          script: /etc/ansible/test1.sh data log
    

    執(zhí)行:
    ansible-playbook createdir.yml -e "host=web user=root"

    一個(gè)批量修改root密碼的例子:

    shell腳本
    #cat alter.sh 
    #!/bin/bash
    ##modify passwd##
    echo 'root:1234567890' |chpasswd
    if [ $? -eq 0 ]
    then
      echo "Change password for root OK!!!"
    else
      echo "Change password for root failure!!!"
    fi
    ansible的yml文件
    #cat modify_all_password.yml 
    ---
    - hosts: all
      user: root
      gather_facts: True
      tasks:
        - name: Modify root passwd in all client
          script: /etc/ansible/roles/alter.sh
    

    然后執(zhí)行:
    ansible-playbook modify_all_password.yml

    ansible-playbook可以跟很多參數(shù)券勺,可以使用--help查看

    #ansible-playbook --help
    Usage: ansible-playbook playbook.yml
     
    Options:
      --ask-become-pass     ask for privilege escalation password
      -k, --ask-pass        ask for connection password
      --ask-su-pass         ask for su password (deprecated, use become)
      -K, --ask-sudo-pass   ask for sudo password (deprecated, use become)
      --ask-vault-pass      ask for vault password
      -b, --become          run operations with become (nopasswd implied)
      --become-method=BECOME_METHOD
                            privilege escalation method to use (default=sudo),
                            valid choices: [ sudo | su | pbrun | pfexec | runas |
                            doas ]
     ……………………    還有很多绪钥,此處省略。
     這里介紹一些常用的
    --inventory=PATH (-i PATH):  指定inventory文件关炼,默認(rèn)文件是/etc/ansible/hosts
    --verbose(-v):               顯示詳細(xì)輸出程腹,也可以使用-vvvv顯示精確到每分鐘的輸出
    --extra-vars=VARS(-e VARS):  定義在playbook使用的變量,格式為:"key=value,key=value"
    --forks=NUM ( -f NUM):       指定并發(fā)執(zhí)行的任務(wù)數(shù)儒拂,默認(rèn)為5寸潦,根據(jù)服務(wù)器性能,調(diào)大這個(gè)值可提高ansible執(zhí)行效率
    --connection=TYPE ( -c TYPE):指定連接遠(yuǎn)程主機(jī)的方式社痛,默認(rèn)為ssh见转,設(shè)為local時(shí),剛只在本地執(zhí)行playbook蒜哀,建議不做修改
    --check:                     檢測(cè)模式斩箫,playbook中定義的所有任務(wù)將在每臺(tái)遠(yuǎn)程主機(jī)上進(jìn)行檢測(cè),但并不直正執(zhí)行
    
  2. copy哪於快
    實(shí)現(xiàn)服務(wù)端向目標(biāo)主機(jī)拷貝文件乘客,類(lèi)似于scp功能:-m copy -a "command"
    例如:

    #ansible host1 -m copy -a "src=/root/php-5.5.24-1.ele.el6.x86_64.rpm dest=/usr/local/src owner=root group=root mode=0755"
    查看客戶(hù)端文件是否存在
    #ansible host1 -m shell -a "ls -l /usr/local/src"
    172.16.29.193 | success | rc=0 >>
    total 10264
    -rw-r--r--. 1 root root 10507544 May 30 02:40 php-5.5.24-1.ele.el6.x86_64.rpm
    
  3. stat模塊:
    獲取遠(yuǎn)程文件狀態(tài)信息,包括atime淀歇,ctime寨典,mtime,md5房匆,uid,gid等信息

    # ansible 10.0.90.25 -m stat -a "path=/etc/sysctl.conf"
    10.0.90.25 | SUCCESS => {
        "changed": false, 
        "stat": {
            "atime": 1459270210.5650001, 
            "checksum": "a27c7ce2e6002c37f3cb537ad997c6da7fd76480", 
            "ctime": 1441217442.5749998, 
            "dev": 2051, 
            "exists": true, 
            "gid": 0, 
            "gr_name": "root", 
            "inode": 1181554, 
            "isblk": false, 
            "ischr": false, 
            "isdir": false, 
            "isfifo": false, 
            "isgid": false, 
            "islnk": false, 
            "isreg": true, 
            "issock": false, 
            "isuid": false, 
            "md5": "c97839af771c8447b9fc23090b4e8d0f", 
            "mode": "0644", 
            "mtime": 1413471211.0, 
            "nlink": 1, 
            "path": "/etc/sysctl.conf", 
            "pw_name": "root", 
            "rgrp": true, 
            "roth": true, 
            "rusr": true, 
            "size": 1150, 
            "uid": 0, 
            "wgrp": false, 
            "woth": false, 
            "wusr": true, 
            "xgrp": false, 
            "xoth": false, 
            "xusr": false
        }
    }
    

    ansible web -m setup ##顯示所有的ansible默認(rèn)變量信息

  4. get_url 模塊
    實(shí)現(xiàn)在遠(yuǎn)程主機(jī)下載指定URL到本地,支持sha256sum文件校驗(yàn)
    例如:

    #ansible host1 -m get_url -a "url=http://www.baidu.com dest=/tmp/index.html mode=0440 force=yes"
    172.16.29.193 | success >> {
        "changed": true,
        "checksum": "8bc43056c39fbb882cf5d7b0391d70b6e84096c6",
        "dest": "/tmp/index.html",
        "gid": 0,
        "group": "root",
        "md5sum": "324aa881293b385d2c0b355cf752cff9",
        "mode": "0440",
        "msg": "OK (unknown bytes)",
        "owner": "root",
        "secontext": "unconfined_u:object_r:user_tmp_t:s0",
        "sha256sum": "",
        "size": 93299,
        "src": "/tmp/tmp3WI5fE",
        "state": "file",
        "uid": 0,
        "url": "http://www.baidu.com"
    }
    
  5. yum 模塊
    linux 平臺(tái)軟件包管理操作浴鸿,常見(jiàn)的有yum井氢,apt
    例如:

    #ansible host1 -m yum -a "name=vsftpd state=latest"     
    Ubuntu系列:
    #ansible host1 -m apt -a "pkg=vsftpd state=latest"
    yum 模塊的一些用法:
    - name: install the latest version of Apache
      yum: name=httpd state=latest
    - name: remove the Apache package
      yum: name=httpd state=absent
    - name: install the latest version of Apache from the testing repo
      yum: name=httpd enablerepo=testing state=present
    - name: install one specific version of Apache
      yum: name=httpd-2.2.29-1.4.amzn1 state=present
    - name: upgrade all packages
      yum: name=* state=latest
    - name: install the nginx rpm from a remote repo
      yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
    - name: install nginx rpm from a local file
      yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
    - name: install the 'Development tools' package group
      yum: name="@Development tools" state=present
    - name: install the 'Gnome desktop' environment group
      yum: name="@^gnome-desktop-environment" state=present
    
  6. cron 模塊
    遠(yuǎn)程主機(jī)crontab 配置,如下:

    #ansible host1 -m cron -a "name='crontab test' minute=0 hour=5,2 job='ls -alh > /dev/null'"
    172.16.29.193 | success >> {
        "changed": true,
        "jobs": [
            "crontab test"
        ]
    }
    效果如下:
    #Ansible: crontab test
    0 5,2 * * * ls -alh > /dev/null
    

    一個(gè)簡(jiǎn)單的yml例子添加cron:

    #cat add_cron.yml
    ---
    -  hosts: web_crontab
       remote_user: root
       gather_facts: True
       tasks:
       - name: add ntp server cron job
         cron: name="local network ntpserver" minute="*/12" hour="*" job="/usr/sbin/ntpdate 10.0.18.1 > /root/ntp.log"
    

    執(zhí)行:
    ansible-playbook add_cron.yml

    移除一個(gè)cron任務(wù):

    #cat del_cron.yml 
    ---
    - hosts: web
      remote_user: root
      gather_facts: false
      tasks:
       - name: del an old crontab job
         cron: name="local network ntpserver" state=absent
    

    執(zhí)行:
    ansible-playbook del_cron.yml
    小案例: 假如有一個(gè)db備份腳本岳链,需要推到所有db服務(wù)器上花竞,并加入crontab,每隔1分鐘執(zhí)行一次掸哑,需要定義playbook結(jié)構(gòu)的yml文件

    #tree cronjob/
    cronjob/
    └── tasks
        ├── crontest.yml
        └── main.yml
    yml文件如下:
    #cat test-cron.yml
    ---
    - name: cron jobs test
      hosts: "{{ host }}"
      remote_user: "{{ user }}"
      gather_facts: True
      roles:
        - cronjob
    tasks目錄中的crontest.yml 
    #cat crontest.yml
    #copy cron job to client server
     - copy: src=/tmp/test_time.sh dest=/usr/local/src/test_time.sh owner=root group=root mode=0755
    #add cron job
     - cron: name="test time jobs" minute="*/1" hour="*" job="/usr/local/src/test_time.sh >> /tmp/time.log"
    tasks目錄中的main.yml
    #cat main.yml
     - include: crontest.yml 
    

    執(zhí)行:
    ansible-playbook test-cron.yml --extra-vars "host=172.16.29.193 user=root" --單臺(tái)執(zhí)行
    客戶(hù)端crontab效果如下:

    #Ansible: test time jobs
    */1 * * * * /usr/local/src/test_time.sh >> /tmp/time.log
    

    以上有點(diǎn)復(fù)雜约急,整合進(jìn)一個(gè)簡(jiǎn)單的yml文件:

    #cat test-cron.yml
    ---
    - hosts: host1
      remote_user: root
      gather_facts: True
      tasks:
       - name: copy cron job file to client server
         copy: src=/tmp/test_time.sh dest=/usr/local/src/test_time.sh owner=root group=root mode=0755
       - name: add cron job
         cron: name="test time jobs" minute="*/2" hour="*" job="/usr/local/src/test_time.sh >> /tmp/time.log"    
    

    執(zhí)行:
    ansible-playbook test-cron.yml
    效果:

    #Ansible: test time jobs
    */2 * * * * /usr/local/src/test_time.sh >> /tmp/time.log
    

    啟用10個(gè)并行進(jìn)程數(shù)執(zhí)行playbook:

    #ansible-playbook host1 nginx.yml -f 10
    
  7. file模塊
    設(shè)置文件的屬性,一個(gè)很常用的模塊
    相關(guān)選項(xiàng)如下:

    force:需要在兩種情況下強(qiáng)制創(chuàng)建軟鏈接苗分,一種是源文件不存在厌蔽,但之后會(huì)建立的情況下;另一種是目標(biāo)軟鏈接已存在摔癣,需要先取消之前的軟鏈奴饮,然后創(chuàng)建新的軟鏈,有兩個(gè)選項(xiàng):yes|no
    group:定義文件/目錄的屬組
    mode: 定義文件/目錄的權(quán)限
    owner:定義文件/目錄的屬主
    path: 必選項(xiàng)择浊,定義文件/目錄的路徑
    recurse:遞歸設(shè)置文件的屬性戴卜,只對(duì)目錄有效
    src:被鏈接的源文件路徑,只應(yīng)用于state=link的情況
    dest:被鏈接到的路徑琢岩,只應(yīng)用于state=link的情況
    state:
        directory:如果目錄不存在投剥,就創(chuàng)建目錄
        file:即使文件不存在,也不會(huì)被創(chuàng)建
        link:創(chuàng)建軟鏈接
        hard:創(chuàng)建硬鏈接
        touch:如果文件不存在担孔,則會(huì)創(chuàng)建一個(gè)新的文件江锨,如果文件或目錄已存在,則更新其最后修改時(shí)間
        absent:刪除目錄攒磨、文件或者取消鏈接文件
    

    比如:

    - file: src=/tmp/test1 dest=/home/test2 state=link
    - file: path=/root/test.txt state=touch
    - file: path=/root/tomcat state=directory owner=root group=root mode=0755
    
  8. mount 模塊:遠(yuǎn)程主機(jī)分區(qū)掛載

    #ansible host1 -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present"
    
  9. service 模塊:遠(yuǎn)程主機(jī)系統(tǒng)服務(wù)管理

    #ansible host1 -m service -a "name=httpd stete=restarted"
    
  10. sysctl 模塊:遠(yuǎn)程linux主機(jī)sysctl配置

    sysctl: name=kernel.panic value=3 sysctl_file=/etc/sysctl.conf checks=before reload=yes
    以下是定義在yml格式文件中的例子:
    - sysctl: name=net.ipv4.tcp_rmem 'value=4096        87380   16777216' state=present
    - sysctl: name=net.ipv4.tcp_wmem 'value=4096        65536   16777216' state=present
    - sysctl: name=net.ipv6.conf.lo.disable_ipv6 value=1 state=present
    
  11. lineinfile模塊
    Ensure a particular line is in a file, or replace an existing line using a back-referenced regular expression 確保特定的行在文件中泳桦,或使用反向引用正則表達(dá)式替換現(xiàn)有的行
    用法:Examples

    - lineinfile: dest=/etc/selinux/config regexp=^SELINUX= line=SELINUX=enforcing
    - lineinfile: dest=/etc/sudoers state=absent regexp="^%wheel"
    - lineinfile: dest=/etc/hosts regexp='^127\.0\.0\.1' line='127.0.0.1 localhost' owner=root group=root mode=0644
    - lineinfile: dest=/etc/httpd/conf/httpd.conf regexp="^Listen " insertafter="^#Listen " line="Listen 8080"
    - lineinfile: dest=/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: dest=/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: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'"
    - lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.*)$' line='\1Xms${xms}m\3' backrefs=yes
    # Validate the sudoers file before saving
    - lineinfile: dest=/etc/sudoers state=present regexp='^%ADMIN ALL\=' line='%ADMIN ALL=(ALL) NOPASSWD:ALL' validate='visudo -cf %s'
    

    一個(gè)例子:

    #cat linetest.yml 
    ---
    - hosts: web
      user: root
      gather_facts: flase
      tasks:
        - name: change /etc/hosts
          lineinfile: 
              dest=/etc/hosts
              line='test line 1\ntest line 2\ntest line 3\ntest line 4'
    

    上面的例子是在/etc/hosts中添加4行,如果你只需要添加一行娩缰,line='test line 1'即可灸撰!

  12. blockinfile模塊 Insert/update/remove a text block surrounded by marker lines
    注意:dest后面的路徑和文件名一定要存在,否則會(huì)報(bào)錯(cuò)拼坎。

    Examples:
    Insert/update/remove a text block surrounded by marker lines
    - name: insert/update "Match User" configuation block in /etc/ssh/sshd_config
      blockinfile:
        dest: /etc/ssh/sshd_config
        block: |
          Match User ansible-agent
          PasswordAuthentication no
    - name: insert/update eth0 configuration stanza in /etc/network/interfaces
            (it might be better to copy files into /etc/network/interfaces.d/)
      blockinfile:
        dest: /etc/network/interfaces
        block: |
          iface eth0 inet static
              address 192.168.0.1
              netmask 255.255.255.0
    - name: insert/update HTML surrounded by custom markers after <body> line
      blockinfile:
        dest: /var/www/html/index.html
        marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
        insertafter: "<body>"
        content: |
          <h1>Welcome to `ansible_hostname`</h1>
          <p>Last updated on `ansible_date_time`.`iso8601`</p>
    - name: remove HTML as well as surrounding markers      ##此文件實(shí)現(xiàn)將上面添加的內(nèi)容刪除
      blockinfile:
        dest: /var/www/html/index.html
        marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
        content: ""
    - name: insert/update "Match User" configuation block in /etc/ssh/sshd_config
      blockinfile:
        dest: /etc/hosts
        block: |
          `item`.`name` `item`.`ip`
        marker: "# {mark} ANSIBLE MANAGED BLOCK `item`.`name`"
      with_items:
          - { name: host1, ip: 10.10.1.10 }
          - { name: host2, ip: 10.10.1.11 }
          - { name: host3, ip: 10.10.1.12 }
    

    第一個(gè)例子:在/etc/hosts文件中添加3行

    #cat blockinfile.yml 
    ---
    - hosts: web
      user: root
      tasks:
        - name: this is test blockinfile module
          blockinfile:
             dest: /etc/hosts
             block: |
               this is a test line 1 
               this is a test line 2 
               this is a test line 3
    

    結(jié)果:

    #cat /etc/hosts
    # BEGIN ANSIBLE MANAGED BLOCK
    this is a test line 1
    this is a test line 2
    this is a test line 3
    # END ANSIBLE MANAGED BLOCK
    

    第二個(gè)例子:創(chuàng)建一個(gè)index.html文件浮毯,并寫(xiě)入html格式內(nèi)容

    #cat blockinfile.yml 
    ---
    - hosts: web
      user: root
      tasks:
        - name: create a test file
          file: path=/root/index.html state=touch
        - name: this is test blockinfile module
          blockinfile:
             dest: /root/index.html
             marker: "<!-- {mark} ansible managed block -->"
             insertafter: "<body>"
             content: |
                 <h1>welcome to `ansible_hostname`</h1>
                 <p>Last updated on `ansible_date_time`.`iso8601`</p>
    

    結(jié)果:

    #cat index.html 
    <!-- BEGIN ansible managed block -->
    <h1>welcome to http</h1>
    <p>Last updated on 2016-05-19T03:17:35Z</p>
    <!-- END ansible managed block -->
    

    注意:上面yml文件中ansible_hostname和ansible_date_time.iso8601變量是ansible默認(rèn)的系統(tǒng)變量,這個(gè)變量可以通過(guò)-m setup查看到泰鸡!
    所以上面的ansible_date_time.iso8601可以改為iso8601_basic_short(人類(lèi)可讀)
    結(jié)果就變成了如下:因?yàn)楫?dāng)前時(shí)間就是#Thu May 19 11:33:29 CST 2016
    <p>Last updated on 20160519T113219</p>
    第三個(gè)例子:index.html已經(jīng)存在债蓝,并且內(nèi)容如下:

    #cat index.html
    <!DOCTYPE html>
    <html>
    <head>
    <title>Welcome to nginx!</title>
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
    </head>
    <body>
    <h1>Welcome to nginx!</h1>
    <p>If you see this page, the nginx web server is successfully installed and
    working. Further configuration is required.</p>
    <p>For online documentation and support please refer to
    <a >nginx.org</a>.<br/>
    Commercial support is available at
    <a >nginx.com</a>.</p>
    <p><em>Thank you for using nginx.</em></p>
    </body>
    </html>
    

    創(chuàng)建ansible的playbook文件如下:

    #cat blockinfile.yml 
    ---
    - hosts: 10.0.90.25
      user: root
      gather_facts: True
      tasks:
        - name: this is test blockinfile module
          blockinfile:
             dest: /root/index.html
             marker: "<!-- {mark} ansible managed block -->"
             insertafter: "<body>"
             content: |
                 <h1>welcome to `ansible_hostname`</h1>
                 <p>Last updated on `ansible_date_time`.`iso8601_basic_short`</p>
    

    執(zhí)行之后,再查看index.html

    #cat index.html
    <!DOCTYPE html>
    <html>
    <head>
    <title>Welcome to nginx!</title>
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
    </head>
    <body>
    <!-- BEGIN ansible managed block -->            ###從這里開(kāi)始
    <h1>welcome to http</h1>
    <p>Last updated on 20160519T115013</p>
    <!-- END ansible managed block -->              ###在這里結(jié)束
    <h1>Welcome to nginx!</h1>
    <p>If you see this page, the nginx web server is successfully installed and
    working. Further configuration is required.</p>
     
    <p>For online documentation and support please refer to
    <a >nginx.org</a>.<br/>
    Commercial support is available at
    <a >nginx.com</a>.</p>
     
    <p><em>Thank you for using nginx.</em></p>
    </body>
    </html>
    

    第四個(gè)例子:使用變量

    #cat blockinfile.yml
    ---
    - hosts: 10.0.90.25
      user: root
      gather_facts: True
      tasks:
        - name: this is test blockinfile module
          blockinfile:
             dest: /etc/hosts
             block: |
                `item`.`name` `item`.`ip`
             marker: "# {mark} ansible managed block `item`.`name`"
          with_items:
             - { name: host1, ip: 10.10.1.10}
             - { name: host2, ip: 10.10.1.11}
             - { name: host3, ip: 10.10.1.12}
    

    執(zhí)行后盛龄,結(jié)果如下:

    #cat /etc/hosts
    # BEGIN ansible managed block host1
    host1 10.10.1.10
    # END ansible managed block host1
    # BEGIN ansible managed block host2
    host2 10.10.1.11
    # END ansible managed block host2
    # BEGIN ansible managed block host3
    host3 10.10.1.12
    # END ansible managed block host3
    

    不足之處饰迹,請(qǐng)多多指出芳誓!

    原文鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市啊鸭,隨后出現(xiàn)的幾起案子锹淌,更是在濱河造成了極大的恐慌,老刑警劉巖赠制,帶你破解...
    沈念sama閱讀 206,968評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赂摆,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡钟些,警方通過(guò)查閱死者的電腦和手機(jī)烟号,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)政恍,“玉大人汪拥,你說(shuō)我怎么就攤上這事「Ю” “怎么了喷楣?”我有些...
    開(kāi)封第一講書(shū)人閱讀 153,220評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀(guān)的道長(zhǎng)鹤树。 經(jīng)常有香客問(wèn)我铣焊,道長(zhǎng),這世上最難降的妖魔是什么罕伯? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,416評(píng)論 1 279
  • 正文 為了忘掉前任曲伊,我火速辦了婚禮,結(jié)果婚禮上追他,老公的妹妹穿的比我還像新娘坟募。我一直安慰自己,他們只是感情好邑狸,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,425評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布懈糯。 她就那樣靜靜地躺著,像睡著了一般单雾。 火紅的嫁衣襯著肌膚如雪赚哗。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,144評(píng)論 1 285
  • 那天硅堆,我揣著相機(jī)與錄音屿储,去河邊找鬼。 笑死渐逃,一個(gè)胖子當(dāng)著我的面吹牛够掠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播茄菊,決...
    沈念sama閱讀 38,432評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼疯潭,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼赊堪!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起竖哩,我...
    開(kāi)封第一講書(shū)人閱讀 37,088評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤雹食,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后期丰,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,586評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡吃挑,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,028評(píng)論 2 325
  • 正文 我和宋清朗相戀三年钝荡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片舶衬。...
    茶點(diǎn)故事閱讀 38,137評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡埠通,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出逛犹,到底是詐尸還是另有隱情端辱,我是刑警寧澤,帶...
    沈念sama閱讀 33,783評(píng)論 4 324
  • 正文 年R本政府宣布虽画,位于F島的核電站舞蔽,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏码撰。R本人自食惡果不足惜渗柿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,343評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望脖岛。 院中可真熱鬧朵栖,春花似錦、人聲如沸柴梆。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,333評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)绍在。三九已至门扇,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間揣苏,已是汗流浹背悯嗓。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,559評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留卸察,地道東北人脯厨。 一個(gè)月前我還...
    沈念sama閱讀 45,595評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像坑质,于是被迫代替她去往敵國(guó)和親合武。 傳聞我的和親對(duì)象是個(gè)殘疾皇子临梗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,901評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容