自動化運維工具ansible的基本應用

    在不少場景中咱們都須要在多個主機上執行相同的命令或者是作相同的配置工做,此時,爲了簡化操做,咱們能夠藉助一些自動化的工具來完成咱們的需求,這種工具咱們稱之爲自動化運維工具。ansible就是其中之一,下面咱們就來用ansible來實現一些簡單操做。html

    下面是ansible能夠實現不少工具的功能,框架圖以下所示:ansible不能實現操做系統的安裝node

wKioL1UrJbvCbfObAAHM9TFf2MA620.jpg

    ansible做者就是早期puppet和func的維護者之一,由於ansible充分吸收了puppet和func的優點,又力圖避免他們的劣勢。python

     OS Provisioning
       PXE,cobbler
       
    OS config
       cfengine,puppet,saltstack, chef
       
    Deployment
       func(ssl)
       fabric(ssh)
       ansible(既具備OS config的功能又具備Deployment功能)mysql

    如何指揮一臺主機上實現控制多臺主機運行相同的命令?要指揮其餘系統工做不只僅是非特權的操做,好比建立一個帳號,這一般都是和系統安全密切相關的。因此這種遠程指揮工具,必須使用一種很是安全的方式進行。如何實現呢?web

    1.基於ssl加密遠程鏈接;redis

    2.基於ssh遠程發送控制指令,讓對方接收指令並運行;  sql


    基於ssl來如何實現?都會事先要求被管理端安裝上一個應用程序,應用程序自己以特權方式運行,可以接收控制端兩者可以對接的應用程序所發來的指令,並接收到指令在本地運行,並把運行的結果反饋給指令發送端,須要一種專門的程序在被控制端上可以接收控制端所發來的各類指令而且將指令運行後的結果反饋給控制端的程序稱爲控制程序的agent。agent之間的通訊就是經過ssl加密,工做機制就是https協議,雖然使用https協議但其並非一個http服務器。
shell

    若是不指望也不須要依賴於被控制安裝一個agent的話,能夠基於ssh來實現,意味着被控制端都運行着ssh服務,而這裏所謂的遠程控制端則以ssh客戶端的方式向服務器端發起請求。服務器接收到請求後並運行。ssh鏈接每次都須要認證,ssh支持密鑰認證,也能夠都使用基於密鑰認證,就不用輸入密碼了。json

    運維工具
       基於agent:一般基於ssl實現,例如puppet, funct等
       基於agentless:一般基於ssh實現,例如fabric, ansible等

    這些工具都具備
     冪等性:(同一個操做執行多半獲得的結果是相同的)
     指望狀態:(只提供條件給ansible,至於實現過程由執行條件來自動完成,)

    Several Tools In One
     Conguration (cfengine, Chef, Puppet)
     
     Deployment (Capistrano, Fabric)

     Ad-Hoc Tasks (Func)

           Multi-tier Orchestration (Juju, sort of)

    ansible 特性        
      Minimal learning curve, auditability (學習曲線低)
      No bootstrapping
      No DAG ordering, Fails Fast
      No agents (other than sshd) – 0 resource consumptionwhen not in use
      No server
      No additional PKI
      Modules in any language
      YAML, not code
      SSH by default
      Strong multi-tier solutionbootstrap

    ansible是基於模塊工做的,他的每一種功能都依賴於模塊,ansible自身只是一個框架,它可以指揮着遠程主機作某些操做,可是每個特定操做都須要模塊來實現,好比依賴yum模塊,可讓遠程工具用yum源的方式安裝應用程序或者卸載應用程序,能夠基於command模塊讓遠程主機執行命令等。

    若是須要讓遠程主機同時運行多個任務,此時就須要多項配置,這多項配置能夠定義在一個文本文件中,讓ansible經過讀取這個文件一次性把任務都執行完,而此文件就叫playbook(劇本),playbook是yaml格式的,可是yaml只是所謂的文檔格式。   

    ansible的架構

wKioL1UrMIaAShvsAAIah00MZoE168.jpg

    ansible是經過指揮着多個遠程主機來完成運維工做,hostX是遠程主機(被指揮段),ansible鏈接每個被指揮端讓其可以工做時,是使用鏈接插件(Connection Plugins)向每個被控制端發起鏈接請求,這個鏈接請求是ssh的,ansible須要讀取配置文件,在配置文件中事先定義好有主機組,這些主機組都是分別作不一樣的功用的,就要依賴於(Host Inventory),這個文件能夠靜態的(手動編寫好)也能夠動態生成,這個文件中把主機事先分好組,然後使用ansible指揮操做時,ansible會自動讀取那個配置文件,去獲取指定組名下都有哪些主機然後僅去鏈接所指定的組名下的主機,在默認狀況ansible只控制5臺節點,5個完成後就接着去執行下面的5個,一批一批去執行,要改變其值能夠本身設定,ansible模塊有兩類:核心模塊、自定義模塊(可使用多種語言開發屬於本身的模塊),【工做過程:用戶指定主機,ansible讀取Inventory獲取主機,而後去鏈接主機,而且藉助模塊,經過Connection Plugins向主機發送指令,每個節點運行指令,並返回結果】,要使用其餘什麼功能均可以經過加載對應的插件來實現。

    ansible是基於Python研發的,官方站點:www.ansible.com/home,Linux下centos 6.6在epel源上提供了其rpm包,查看一下

    ansible.noarch                                      1.9.0.1-2.el6                    epel

    此處yum源爲阿里雲的配置以下:

[epel]
nama=epel package
baseurl=http://mirrors.aliyun.com/epel/6/x86_64/
gpgcheck=1
enabled=1
gpgkey=http://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-6

    使用ansible實現的簡單架構:

wKiom1UrON6Axw4oAAECYTGDPU4478.jpg

    這裏的實驗中nodeX和hostname是對應的

    在node1上安裝ansible

[root@node1 ~]# yum install ansible -y

Installed:  安裝的包
  ansible.noarch 0:1.9.0.1-2.el6                                                                     

Dependency Installed: 安裝依賴的包
  PyYAML.x86_64 0:3.10-3.1.el6                     libyaml.x86_64 0:0.1.3-4.el6_6                   
  python-babel.noarch 0:0.9.4-5.1.el6              python-crypto.x86_64 0:2.0.1-22.el6              
  python-crypto2.6.x86_64 0:2.6.1-2.el6            python-httplib2.noarch 0:0.7.7-1.el6             
  python-jinja2.x86_64 0:2.2.1-2.el6_5             python-keyczar.noarch 0:0.71c-1.el6              
  python-paramiko.noarch 0:1.7.5-2.1.el6           python-pyasn1.noarch 0:0.0.12a-1.el6             
  python-setuptools.noarch 0:0.6.10-3.el6          python-simplejson.x86_64 0:2.0.9-3.1.el6

    查看安裝ansible生成了哪些文件

[root@node1 ~]# rpm -ql ansible | less
/etc/ansible
/etc/ansible/ansible.cfg  主配置文件
/etc/ansible/hosts  主機分組定義的文件
/etc/ansible/roles
/usr/bin/ansible
/usr/bin/ansible-doc
/usr/bin/ansible-galaxy
/usr/bin/ansible-playbook  運行定義好的playbook程序
/usr/bin/ansible-pull   工做在推送模式
/usr/bin/ansible-vault  把playbook文件解密存放的

。。。。。

    查看ansible命令的使用

[root@node1 ~]# ansible -h
Usage: ansible <host-pattern> [options]

<hostpattern> 主機模式
host-pattern
   A name of a group in the inventory file, a shell-like glob selecting hosts in inventory file, or any combination of the two separated by semicolons.
-k, --ask-pass        ask for SSH password 提示用戶輸入密碼
-a 'ARGUMENTS', --args='ARGUMENTS'           The ARGUMENTS to pass to the module.

經常使用模塊:
              command  這裏不能執行管道
              user
              copy
              cron
              file
              filesystem
              group
              hostname
              ping
              yum
              service
              shell
              script

/etc/ansible/hosts 文件的說明必定要注意此文件的屬性

[root@node1 ~]# ls -l /etc/ansible/hosts
-rw-r--r-- 1 root root 965 Mar 26 10:25 /etc/ansible/hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments be=ginwith the '#' character
#   - Blank linesare ignored
#   - Groups of hosts are delimited by [header] elements
#   - You canenter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups
# Ex 1: Ungrouped hosts, specify before any group headers. 沒有分組的定義
# Ex 2: A collection of hosts belonging to the'webservers' group這裏是經過分組定義的
[webservers]
# If you have multiple hosts following a pattern you can specify  分組定義中的模式匹配
# them like this:
www[001:006].example.com  表示www.001.example.com到www.006.example.com是指定範文匹配的

    修改文件自定義,先備份文件,後刪除所有內容,添加以下
[constrol]
192.168.21.234
192.168.21.230

    同一個主機能夠在多個組中定義的

[root@node1 ~]# cp /etc/ansible/hosts /etc/ansible/hosts.bak   

[root@node1 ~]# vim /etc/ansible/hosts

# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.
[constrol]
192.168.21.234
192.168.21.230


#ansible <host pattern> [-m MODULE] -a 'MODULE_ARGS'

    鏈接執行date命令

[root@node1 ~]# ansible constrol -m command -a 'date'
The authenticity of host '192.168.21.230 (192.168.21.230)' can't be established.
RSA key fingerprint is 4f:33:a8:ce:34:20:2f:04:3b:ad:c9:26:f4:bd:d0:f5.
Are you sure you want to continue connecting (yes/no)? yes
192.168.21.230 | FAILED => SSH Error: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
    while connecting to 192.168.21.230:22
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.
The authenticity of host '192.168.21.234 (192.168.21.234)' can't be established.
RSA key fingerprint is 30:43:cb:45:98:67:51:e5:36:82:e6:62:03:5e:98:fc.
Are you sure you want to continue connecting (yes/no)? yes
192.168.21.234 | FAILED => SSH Error: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
    while connecting to 192.168.21.234:22
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

    SSH鏈接期間遇到了一個未知錯誤。咱們建議您使用-vvvv從新運行命令,這將使SSH調試輸出來幫助診斷問題
使用ansible constrol -m command -a 'date' –vvvv能夠查看詳細的幫助信息
    默認須要基於密鑰方式來認證,-k指定須要基於口令來進行認證

[root@node1 ~]# ansible constrol -m command -a 'date' -k
SSH password:
192.168.21.234 | FAILED => to use the 'ssh' connection type with passwords, you must install the sshpass program
192.168.21.230 | FAILED => to use the 'ssh' connection type with passwords, you must install the sshpass program

提示須要安裝sshpass,安裝sshpass,sshpass也是epel源提供的

[root@node1 ~]# yum install -y sshpass

[root@node1 ~]# ansible constrol -m command -a 'date' -k
SSH password:    注意由於此處兩端的口令同樣,因此只提示一次,不同的話會提示兩次
192.168.21.230 | success | rc=0 >>
Tue Apr  7 01:11:47 CST 2015

192.168.21.234 | success | rc=0 >>
Mon Apr 13 03:12:42 CST 2015

被控制節點ip  執行成功   成功碼顯示

    

    在主控節點上顯示被控制節點上磁盤使用狀況

[root@node1 ~]# ansible constrol -m command -a 'df -lhP' -k
SSH password:
192.168.21.234 | success | rc=0 >>
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/vg_lvm-lv1   20G  1.8G   17G  10% /
tmpfs                   491M     0  491M   0% /dev/shm
/dev/sda1               190M   27M  153M  16% /boot
/dev/mapper/vg_lvm-lv2  9.8G  112M  9.2G   2% /var

192.168.21.230 | success | rc=0 >>
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/vg_lvm-lv1   20G  814M   18G   5% /
tmpfs                   491M     0  491M   0% /dev/shm
/dev/sda1               190M   27M  153M  15% /boot
/dev/mapper/vg_lvm-lv2  9.8G  110M  9.2G   2% /var

    如今每次發送到被控節點上執行的指令都會提示說輸入口令,咱們把口令在配置文件中指定就不用每次都輸入了,修改/etc/ansible/hosts文件指定密碼選項  ansible_ssh_pass=password

咱們的密碼爲123456,因此修改後以下:

[root@node1 ~]# cat /etc/ansible/hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.
[constrol]
192.168.21.234 ansible_ssh_pass=123456
192.168.21.230 ansible_ssh_pass=123456

 此時不須要-k選項,不用輸入密碼了,使用指定用戶登陸能夠用選項ansible_ssh_user=xxx,使用指定非標準端口ansible_ssh_port=xxx,顯示各節點的date

[root@node1 ~]# ansible constrol -m command -a 'date'
192.168.21.234 | success | rc=0 >>
Mon Apr 13 03:21:15 CST 2015

192.168.21.230 | success | rc=0 >>
Tue Apr  7 01:20:20 CST 2015

     在理時間不一樣步,使用ntpdate同步一下時間,時間服務器能夠選擇網絡上的時間服務器,這裏咱們用的是time.windows.com

    node三、node4節點都使用# crontab -e  添加以下內容
1 * * * * /usr/sbin/ntpdate time.windows.com > /dev/null  每小時同步一下時間,並把輸出重定向到/dev/null上。


    在遠程主機上建立用戶

[root@node1 ~]# ansible control -m command -a 'useradd openstack'
No hosts matched  這裏若是hosts文件中不匹配也會提示的
[root@node1 ~]# ansible constrol -m command -a 'useradd openstack'
192.168.21.234 | success | rc=0 >>


192.168.21.230 | success | rc=0 >>   

    查看用戶是否建立成功

[root@node1 ~]# ansible constrol -m command -a 'tail -3 /etc/passwd'
192.168.21.230 | success | rc=0 >>
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
openstack:x:500:500::/home/openstack:/bin/bash

192.168.21.234 | success | rc=0 >>
tcpdump:x:72:72::/:/sbin/nologin
mysql:x:498:498::/home/mysql:/sbin/nologin
openstack:x:500:500::/home/openstack:/bin/bash  發現用戶已經成建立了

    給用戶指定密碼

[root@node1 ~]# ansible constrol -m command -a 'echo "puppet" | passwd --stdin openstack'
192.168.21.234 | success | rc=0 >>
puppet | passwd --stdin openstack

192.168.21.230 | success | rc=0 >>
puppet | passwd --stdin openstack

[root@node1 ~]# ansible constrol -m command -a 'tail -3 /etc/shadow'
192.168.21.230 | success | rc=0 >>
sshd:!!:16519::::::
tcpdump:!!:16519::::::
openstack:!!:16531:0:99999:7:::  發現此時遠程主機上沒有設置好密碼,上面命令只是顯示而已,其實建立用戶和密碼有專門的模塊實現的

192.168.21.234 | success | rc=0 >>
tcpdump:!!:16525::::::
mysql:!!:16525::::::
openstack:!!:16537:0:99999:7:::    


    獲取模塊幫助:

man ansible-doc -l

NAME
       ansible-doc - show documentation on Ansible modules

SYNOPSIS
       ansible-doc [-M module_path] [-l] [-s] [module...]

-l, --list=
           Produce a terse listing of modules and a short description of each.

-s, --snippet         Show playbook snippet for specified module(s)

[root@node1 ~]# ansible-doc -l

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-m...
airbrake_deployment           Notify airbrake about app deployments     

....................

ansible-doc MODULE_NAME回車後就會顯示對應模塊的使用幫助

[root@node1 ~]# ansible-doc command
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
> COMMAND

  The [command] module takes the command name followed by a list of
  space-delimited arguments. The given command will be executed on all
  selected nodes. It will not be processed through the shell, so
  variables like `$HOME' and operations like `"<"', `">"', `"|"', and
  `"&"' will not work (use the [shell] module if you need these
  features).

Options (= is mandatory):

- chdir
        cd into this directory before running the command [Default:
        None]

- creates
        a filename, when it already exists, this step will *not* be
        run. [Default: None]

。。。。。。。。。。

user模塊查看幫助

[root@node1 ~]# ansible-doc user
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
> USER

  Manage user accounts and user attributes.

Options (= is mandatory):

- append
        If `yes', will only add groups, not set them to just the list
        in `groups'. (Choices: yes, no) [Default: no]

- comment
        Optionally sets the description (aka `GECOS') of user account.

。。。。。。。。。。。。。。

後面還有實例

EXAMPLES:
# Add the user 'johnd' with a specific uid and a primary group of 'admin'
- user: name=johnd comment="John Doe" uid=1040 group=admin

# Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's
- user: name=james shell=/bin/bash groups=admins,developers append=yes

# Remove the user 'johnd'
- user: name=johnd state=absent remove=yes

# Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
- user: name=jsmith generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa

    用openssl生成隨機的salt

[root@node1 ~]# openssl rand -hex 4
98a4afbe

    生成加密後的密碼

[root@node1 ~]# openssl passwd -1 -salt `openssl rand -hex 4`
Password:
$1$653fbb05$asLazeKl3u0SNit6lZWOe.

    以密碼爲參數經過user模塊來傳遞過去

[root@node1 ~]# ansible constrol -m user -a 'name=openstack password=$1$653fbb05$asLazeKl3u0SNit6lZWOe.'
192.168.21.230 | success >> {
    "append": false,
    "changed": true,
    "comment": "",
    "group": 500,
    "home": "/home/openstack",
    "move_home": false,
    "name": "openstack",
    "password": "NOT_LOGGING_PASSWORD",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 500
}

192.168.21.234 | success >> {
    "append": false,
    "changed": true,
    "comment": "",
    "group": 500,
    "home": "/home/openstack",
    "move_home": false,
    "name": "openstack",
    "password": "NOT_LOGGING_PASSWORD",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 500
}
    查看發現密碼已經生成了
[root@node1 ~]# ansible constrol -m command -a 'tail -3 /etc/shadow'
192.168.21.234 | success | rc=0 >>
tcpdump:!!:16525::::::
mysql:!!:16525::::::
openstack:$1$653fbb05$asLazeKl3u0SNit6lZWOe.:16538:0:99999:7:::

192.168.21.230 | success | rc=0 >>
sshd:!!:16519::::::
tcpdump:!!:16519::::::
openstack:$1$653fbb05$asLazeKl3u0SNit6lZWOe.:16538:0:99999:7:::

    官網下ansible的全部模塊列表

http://docs.ansible.com/list_of_all_modules.html

    

    在hosts文件中指定用戶和密碼,修改後以下所示

[root@node1 ~]# cat /etc/ansible/hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.
[constrol]
192.168.21.234 ansible_ssh_user=openstack ansible_ssh_pass=zabbix
192.168.21.230 ansible_ssh_pass=123456

    查看系統上當前運行的用戶是誰whoami
[root@node1 ~]# ansible constrol -m command -a 'whoami'
192.168.21.230 | success | rc=0 >>
root

192.168.21.234 | success | rc=0 >>
openstack

    各經常使用模塊
              command  默認
                 #ansible constrol –m command –a ‘date’

              user
                   Manage user accounts and userattributes. 管理用戶帳號和用戶屬性
                 #ansible constrol –m user –a ‘name=fedora password=xxxx’

              copy             Copiesfiles to remote locations.
                   The [copy] module copies a fileon the local box to remote locations. Use the [fetch]module to copy files from remote locations to the local box.
                 #ansibleconstrol –m copy –a ‘src=how.txt dest=/tmp’

              cron              定義管理任務計劃 Manage cron.d andcrontab entries.
                     #ansible constrol -m cron -a 'name="print info" minute="*/3"job="echo How are you. >> /tmp/echo.txt'

              file                       Sets attributes offiles
                     file:src=/file/to/link/to dest=/path/to/symlink owner=foo group=foo state=link 建立符號連接的
                                        state 若是是If `absent',directorieswill be recursively deleted, and files or symlinkswill be unlinked.
                     #ansiblecontrol –m file –a ‘dest=/tmp/you state=absent’ 會刪除文件

              filesystem            Makes file system on block device
                     #Create a ext2 filesystem on /dev/sdb1.
                                        - filesystem:fstype=ext2 dev=/dev/sdb1

              group                          Add or remove groups

              hostname

              ping
                      Try to connect to host and return `pong' onsuccess.,探測主機是否在線
                     #ansibleconstrol –m ping

              yum
                   Installs, upgrade, removes, andlists packages and groups with the
                   `yum' package manager.
                     #ansibleconstrol –m yum –a ‘name=tree state=present’

              service           Controls services on remote hosts.
                     #Example action to enable service httpd, and not touch the running state
                                        - service:name=httpd enabled=yes(enabled開機是否自動啓動)
                                        #ansible constrol–m service –a ‘name=httpd state=restart’

              shell
                     #ansible constrol -m shell -a 'name=fedora password=fedora'

              script
                     #ansibleconstrol –m script –a ‘/root/xxx.sh’


    copy模塊使用
[root@node1 ~]# ansible-doc copy
> COPY
  The [copy]module copies a file on the local box to remote locations. Usethe [fetch] module to copy files from remote locations tothe local box.

Options (= is mandatory):  (」=」號開頭的是必須的)
目標
= dest
      Remoteabsolute path where the file should be copied to. If src is adirectory, this must be a directory too. [Default:None]  遠程節點的位置(絕對路徑)

- src
        Localpath to a file to copy to the remote server; can be absoluteor relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contentsof that directory are copied to destination.
       Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavioris similar to Rsync.[Default: None](可相對可絕對位置)

實例:
Notes:  The"copy" module recursively copy facility does not scale to lots
       (>hundreds) of files. For alternative, see synchronize module,which is a wrapper around rsync.

# Example from Ansible Playbooks
- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.confowner=foo group=foo mode=0644
# The same example as above, but using a symbolic modeequivalent to 0644
- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.confowner=foo group=foo mode="u=rw,g=r,o=r"
# Another symbolic mode example, adding somepermissions and removing others
- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.confowner=foo group=foo mode="u+rw,g-wx,o-rwx"
# Copy a new "ntp.conf file into place, backing upthe original if it differs from the copied version
- copy: src=/mine/ntp.conf dest=/etc/ntp.confowner=root group=root mode=644 backup=yes
# Copy a new "sudoers" file into place, afterpassing validation with visudo
- copy: src=/mine/sudoers dest=/etc/sudoersvalidate='visudo -cf %s'


新增一個複製的文件   
root@node1 ~]# echo "The is new start." > start.txt

[root@node1 ~]# ansible constrol -m copy -a 'src=/root/start.txt dest=/tmp/'複製到/tmp目錄下
192.168.21.230 | success >> {
    "changed": true,
    "checksum": "22be61e943af70c7ff8ae394428f195aaa72d10a",
    "dest": "/tmp/start.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "589e84da9cb01000f0fccba722b6f4c2",
    "mode": "0644",
    "owner": "root",
    "size": 18,
    "src": "/root/.ansible/tmp/ansible-tmp-1427606759.7-78904826422288/source",
    "state": "file",
    "uid": 0
}

192.168.21.234 | success >> {
    "changed": true,
    "checksum": "22be61e943af70c7ff8ae394428f195aaa72d10a",
    "dest": "/tmp/start.txt",
    "gid": 500,
    "group": "openstack",
    "md5sum": "589e84da9cb01000f0fccba722b6f4c2",
    "mode": "0664",
    "owner": "openstack",
    "size": 18,
    "src": "/home/openstack/.ansible/tmp/ansible-tmp-1427606759.7-97947262909113/source",
    "state": "file",
    "uid": 500
}

[root@node1 ~]# ansible constrol -m command -a 'cat /tmp/start.txt'  查看複製成功了
192.168.21.230 | success | rc=0 >>
The is new start.

192.168.21.234 | success | rc=0 >>
The is new start.


    使用基於密鑰的方式認證登陸

[root@node1 ~]# ssh-keygen -t rsa -P ''
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:
11:b5:f7:85:ec:64:b1:b4:95:0b:e6:1c:48:0f:04:32 root@node1
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
|       E.o=+. o o|
|        o. oo* B |
|        . . =.X o|
|         . . B o |
|        S     o  |
|                 |
|                 |
|                 |
|                 |
+-----------------+

    修改配置文件hosts

[root@node1 ~]# cat /etc/ansible/hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.
[constrol]
192.168.21.234 ansible_ssh_pass=123456
192.168.21.230 ansible_ssh_pass=123456

[root@node1 ~]# ansible constrol -m copy -a 'src=/root/.ssh/id_rsa.pub dest=/root/.ssh/authorized_keys owner=root group=root mode=0600'
192.168.21.234 | success >> {
    "changed": true,
    "checksum": "062161f3b71748dfd975c8c4c4fce4fd4f935734",
    "dest": "/root/.ssh/authorized_keys",
    "gid": 0,
    "group": "root",
    "md5sum": "ad2489d1b76241e939c92001ac2a54c1",
    "mode": "0600",
    "owner": "root",
    "size": 392,
    "src": "/root/.ansible/tmp/ansible-tmp-1427607180.58-136701398329016/source",
    "state": "file",
    "uid": 0
}

192.168.21.230 | FAILED >> {
    "checksum": "062161f3b71748dfd975c8c4c4fce4fd4f935734",
    "failed": true,
    "msg": "Destination directory /root/.ssh does not exist"  目錄不存在
}    

[root@node1 ~]# ansible constrol -m command -a 'mkdir /root/.ssh'
192.168.21.230 | success | rc=0 >>


192.168.21.234 | FAILED | rc=1 >>
mkdir: cannot create directory `/root/.ssh': File exists

[root@node1 ~]# ansible constrol -m copy -a 'src=/root/.ssh/id_rsa.pub dest=/root/.ssh/authorized_keys owner=root group=root mode=0600'

    此時ok了,既然是部署好了基於密鑰方式認證,那麼把hosts文件中的ansible_ssh_pass刪除,以下

[root@node1 ~]# ansible all -a 'date'all是全部主機)執行過程的詳細信息可經過加-vvvv選項

192.168.21.230 | success | rc=0 >>
Mon Apr 13 18:32:55 CST 2015

192.168.21.234 | success | rc=0 >>
Mon Apr 13 18:32:55 CST 2015

[root@node1 ~]# vim /etc/ansible/hosts
[root@node1 ~]# cat /etc/ansible/hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.
[constrol]
192.168.21.234
192.168.21.230
[root@node1 ~]# ansible all -a 'date'  發現ok了
192.168.21.230 | success | rc=0 >>
Mon Apr 13 18:33:26 CST 2015

192.168.21.234 | success | rc=0 >>
Mon Apr 13 18:33:31 CST 2015   

    配置文件部份內容

[root@node1 ~]# cat /etc/ansible/ansible.cfg
# config file for ansible -- http://ansible.com/
# ==============================================

# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first

[defaults]

# some basic default values...

inventory      = /etc/ansible/hosts
#library        = /usr/share/my_modules/
remote_tmp     = $HOME/.ansible/tmp
pattern        = *
forks          = 5  每次能夠處理的批量主機個數
poll_interval  = 15
sudo_user      = root
#ask_sudo_pass = True
#ask_pass      = True
transport      = smart
#remote_port    = 22  遠程端口

。。。。。。。。。。

    ping模塊,查看遠程主機是否在線

[root@node1 ~]# ansible-doc ping
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
> PING

  A trivial test module, this module always returns `pong' on
  successful contact. It does not make sense in playbooks, but it is
  useful from `/usr/bin/ansible'

EXAMPLES:
# Test 'webservers' status
ansible webservers -m ping

[root@node1 ~]# ansible constrol -m ping
192.168.21.230 | success >> {
    "changed": false,
    "ping": "pong"
}

192.168.21.234 | success >> {
    "changed": false,
    "ping": "pong"
}  ok了,都在線

    本次ansible到此處結束,後面將介紹ansible的高級功能,使用playbook。歡迎關注

相關文章
相關標籤/搜索