ansible

ansible

安裝ansible

  • 查看當前的系統版本

    yum install redhat-lsb-core -y 
    
      [root@localhost httpd]# lsb_release -a
          LSB Version:    :core-4.1-amd64:core-4.1-noarch
          Distributor ID:    CentOS
          Description:    CentOS Linux release 7.3.1611 (Core) 
          Release:    7.3.1611
          Codename:    Core
  • 安裝ansible,ansible在epel中

    yum install epel-release
      yum install ansible
  • 公鑰的分發

    ssh-keygen -t rsa -P ''
      ssh-copy-id -i .ssh/id_rsa.pub root@192.168.99.120
  • 測試:

    • 嘗試登陸被控制節點的主機,ssh root@192.168.99.120,不用輸入密碼即可登陸
    • 為方便測試驗證,將master也同樣添加入列表

配置文件

  • /etc/ansible/hosts文件中添加主機

  • /etc/ansible/ansible.cfg

    命令執行完的結果顯示的顏色
          [colors]
          #highlight = white
          #verbose = blue
          #warn = bright purple
          #error = red
          #debug = dark gray
          #deprecate = purple
          #skip = cyan
          #unreachable = red
          #ok = green
          #changed = yellow
          #diff_add = green
          #diff_remove = red
          #diff_lines = cyan
  • roles目錄

ansible命令集

  • ansible

    ~]# ansible
      ansible           ansible-doc       ansible-playbook  ansible-vault
      ansible-console   ansible-galaxy    ansible-pull
  • ansible-doc命令

    • 查看所有模塊:ansible-doc -l
    • 查看指定模塊(command為例)的說明:ansible-doc commond
  • ansible命令

    • 幫助:man ansible

      ansible <host-pattern> [-m module_name] [-a args] [options]
        -m NAME, --module-name=NAME        #標識模塊
            Execute the module called NAME.
        -a 'ARGUMENTS', --args='ARGUMENTS'        #標識所使用的參數
            The ARGUMENTS to pass to the module.
    • ping模塊
      ansible srv1 -m ping

      示例:

      [root@localhost ~]# ansible web -m ping
        172.16.251.255 | SUCCESS => {
            "changed": false, 
            "ping": "pong"
        }
        172.16.251.207 | SUCCESS => {
            "changed": false, 
            "ping": "pong"
        }
        172.16.251.185 | SUCCESS => {
            "changed": false, 
            "ping": "pong"
        }
    • command模塊

    • shell模塊

    • copy模塊

      ansible web -m copy -a 'src=/etc/fstab dest=/tmp/fstab2.log'
        ansible web -m command -a 'md5sum /tmp/fstab2.log'
        ansible web -m copy -a 'src=/etc/fstab dest=/tmp/fstab.log.1 owner=stanley group=httpd'
        ansible web -m copy -a 'src=/etc/fstab dest=/tmp/fstab.log.2 mode=600'
        ansible web -m shell -a 'ls -l /tmp/fstab*'
        ansible web -m copy -a 'src=/root/fstab dest=/tmp/fstab.log.1 backup=yes'
    • cron模塊

      • 創建定時任務
        ansible web -m cron -a ‘name=”harddrive check” minute=”15″ hour=”3″ job=”df -lh >> /tmp/df.log”‘
      • 查看定時任務
        crontab -l
      • 刪除定時任務
        ansible web -m cron -a ‘name=”harddrive check” state=absent’
    • fetch模塊 #從遠程拉一個文件到本地
      ansible web -m fetch -a ‘src=/tmp/df.txt dest=/root/’

      注意:此模塊在拉取時無法進行改名,到本地之后的是主機IP地址的目錄

      [root@localhost ~]# ls
        172.16.251.185  172.16.251.255   fstab
        172.16.251.207  anaconda-ks.cfg  memcache
    • file模塊

      • 修改文件屬性
        ansible web -m file -a ‘path=/tmp/df.txt state=touch mode=”600″ owner=stanley group=httpd’
      • 創建一個目錄
        ansible web -m file -a ‘path=/root/file state=directory’
    • hostname模塊

      • 修改特定主機的主機名
        ansible 172.16.251.185 -m hostname -a ‘name=master185’

      • 在底層系統不同的基礎上使用相同的指令,改變主機名

    • yum模塊

      安裝httpd:ansible web -m yum -a ‘name=httpd’

    • service模塊

      started、stopped、restarted、reloaded
        enabled=yes

      啟動httpd:ansible web -m service -a ‘name=httpd state=started’

    • user模塊

      • 示例:新增一個用戶(先創建一個tom組)
        user:tom
        comment: tom is tom
        /home/tomhome/
        /bash/zshell
        uid = 1066
        group = tom
        group = wheel

        ~]# ansible web -m user -a 'name=tom comment="tom is tom" uid=1066 group=tom groups=wheel shell=/bin/zshell home=/home/tomhome'
      • 查看tom的信息

        ~]# getent passwd tom
        tom:x:1066:1002:tom is tom:/home/tomhome:/bin/zshell
        ~]# getent group tom
        tom:x:1002:
    • group模塊

      ansible web -m group -a 'name=tom'
    • scripts腳本 #將本地的腳本復制到遠程主機并在遠程主機執行

      編輯一個本地腳本,/root/run.sh 
            #!/bin/bash
      
            touch /tmp/run.sh.log
            echo `date` >> /tmp/run.sh.log
      ~]# ansible web -m script -a '/root/run.sh'
            此腳本在傳到遠程主機的時候會自動執行一次
  • ansible-vault命令

    • 參數:

      • 加密:encrypt
      • 解密:decrypt

        創建一個文件進行測試;crypt.yml
        加密:encrypt
        ~]# ansible-vault encrypt crypt.yml
        Vault password: 
        Encryption successful
        
        [root@localhost ansible]# cat crypt.yml
        $ANSIBLE_VAULT;1.1;AES256
        37393130653139316462336338643462393636376638326131353231316635666131333833373731
        3633356338303963356636353265396133303535636266620a333133343935326362326231666465
        62323038653633616135363532313731663363316433663730386430306635346264343135346631
        3339336466613334300a366237656561383635633866356634393265313462323630356338623236
        6266
        解密:
        [root@localhost ansible]# ansible-vault view crypt.yml
        Vault password: 
        
        [root@localhost ansible]# ansible-vault decrypt crypt.yml
        Vault password: 
        Decryption successful
        [root@localhost ansible]# cat crypt.yml
  • ansible-galaxy命令

    ~]# ansible-galaxy -h
      Usage: ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...
    • Options:

      -h, --help     show this help message and exit
      -v, --verbose  verbose mode (-vvv for more, -vvvv to enable connection
                     debugging)
      --version      show program's version number and exit
    • 搜索:ansible-galaxy search nginx
    • 安裝:ansible-galaxy install nginx
      下載的默認路徑是/etc/ansible/roles/
  • ansible-console命令(ansible用戶交互界面)

    root@all (3)[f:5]$
          root:當前的執行用戶
          @:
          all:當前所處的默認分組的組名
          (3):當前的分組中的主機數
          [f:5]:當前開啟了多少個線程,對遠程主機進行任務操作
    
      root@all (3)[f:5]$ ?            列出所有的可用模塊
      root@all (3)[f:5]$ cd web        切換到web分組
      root@web (3)[f:5]$ list            web分組的所有主機列表
      172.16.251.185
      172.16.251.207
      172.16.251.255
      root@web (3)[f:5]$ forks 10        調整線程數
      root@web (3)[f:10]$
    • 示例:

      root@web (3)[f:10]$ service name=httpd state=restarted
        root@web (3)[f:10]$ command ls
        root@web (3)[f:10]$ ls
        root@web (3)[f:10]$ pwd
      
        卸載httpd
        root@all (3)[f:5]$ command yum remove httpd -y
  • ansible-playbook命令

    • YAML語法

      1)首先以“---”(3個減號)開始,且需頂行首寫。
        2)次行開始正常寫Playbook的內容,但筆者一般建議寫明該Playbook的功能。
        3)使用#號注釋代碼。
        4)縮進必須是統一的,不能空格和tab混用。
        5)縮進的級別也必須是一致的,同樣的縮進代表同樣的級別,程序判別配置的級別是通過縮進結合換行來實現的。
        6)YAML文件內容和Linux系統大小寫判斷方式保持一致,是別大小寫的,k/v的值均需大小寫敏感。
        7)k/v的值可同行寫也可換行寫。同行使用:分隔,換行寫需要以-分隔。
        8)一個完整的代碼塊功能需最少元素需包括 name: task。
        9)一個name只能包括一個task。
        10)文件名以.yaml和.yml結尾。
    • Playbook的核心元素

      Hosts: 運行指定任務的目標主機;可以是:IP地址、hostname、組名
        Tasks: 任務列表
        Varniables: 變量
        Templates: 模板
        Handlers: 由特定條件觸發的任務 監控資源改變時才會觸發改變
        Roles: Playbook的按固定目錄結構組成
        remote_user: 執行用戶,通常使用root用戶
    • yml格式示例:使用ansible-playbook添加用戶

      [root@localhost ansible]# vim user.yml
        ---
      
        - hosts: web
          remote_user: root
          tasks:
          - name: user natasha
            user: name=natasha shell=/bin/bash home=/home/natasha
      
        [root@localhost ansible]# ansible-playbook user.yml
    • 運行playbook:
      Usage: ansible-playbook playbook.yml

      • Options:

        • -t TAGS, –tags=TAGS
          only run plays and tasks tagged with these values

          示例:
                ~]# ansible-playbook web.yml --tags="confighttpd,reloadhttpd"
        • -l SUBSET, –limit=SUBSET
          further limit selected hosts to an additional pattern

          示例:
                ~]# ansible-playbook web.yml -l 172.16.251.207
    • handlers和tags

      示例:
        - hosts: web
          remote_user: root
          tasks:
          - name: install httpd
            tags: installhttpd
            yum: name=httpd state=latest
      
          - name: config httpd
            tags: confighttpd
            copy: src=/root/ansible/httpd.conf dest=/etc/httpd/conf/ backup=yes
            when: ansible_distribution_major_version == "7"
            notify: restart httpd
      
          handlers:
          - name: restart httpd
            service: name=httpd state=restarted
      
          - name: reload httpd
            tags: reloadhttpd
            service: name=httpd state=reloaded
    • playbook變量的使用

      • 變量的優先級
        命令行 > 主機變量 > 組變量
      • 變量來源:

        • Ansible setup中facts到的信息變量可直接使用
          示例:ansible web -m setup
        • 自定義變量

          • 主機變量定義

            /etc/ansible/hosts
                  [web]
                  172.16.251.185 hname=master185
                  172.16.251.207 hname=node207
                  172.16.251.32 hname=node32
              引用變量
                  ansible調用變量
                      ~]#  ansible web -m hostname -a 'name={{ hname }}'
            
                  ansible-playbook調用變量
                      hostname.yml            
                      - hosts: web
                        remote_user: root
                        tasks:
                        - name: change hostname to {{ hname }}
                          hostname: name="H{{ hname }}"
                      ~]# ansible-playbook hostname.yml
          • 命令行指定變量
            Ansible-playbook –e 調用

          • 組變量

            [svr1:vars]
              http_port=808
              [srv1]
              192.168.99.120 http_port=8080 hname=www120
              192.168.99.178 http_port=80 hname=www178
      • Inventory參數(ansible內置變量)
        ansible_ssh_host
        ansible_ssh_port
        ansible_ssh_user
        ansible_ssh_pass
        ansible_sudo_pass

        示例:提取本機的hostname變量

        [root@Hmaster185 ~]# ansible 172.16.251.207 -m setup | grep hostname
              "ansible_hostname": "localhost",
    • template

      • 功能同copy模塊,但是可以實現變量的引用。在.yml文件中定義變量,在.j2文件中引用變量

        步驟:

        1. /etc/ansible/hosts,定義變量
        2. 服務的配置文件(.j2)。編輯.j2的文件,在.j2文件中引用變量
        3. ansible-playbook的執行文件(.yml)。編輯.yml文件,在.yml文件中引用.j2文件
        4. 命令行執行.yml文件
    • for循環、if條件判斷、when條件判斷

      示例:
        編輯vhostj2.yml文件,(在.yml文件中定義變量)
        - hosts: web
          remote_user: root
          vars:
            - vports:
              - 80
              - 443
          tasks:
            - name: install httpd
            yum: name=httpd state=latest
      
            - name: config httpd
            copy: src=/root/ansible/httpd.conf dest=/etc/httpd/conf/ backup=yes
            when: ansible_distribution_major_version == "7"
      
            - name: reload httpd
            service: name=httpd state=reloaded
      
        編輯vhost.conf.j2文件
        {% for vport in vports  %}
        <VirtualHost>
                Listen {{ vport }}
                ServerName {{ ansible_hostname }}.magedu.com
                DocumentRoot /var/www/html
                {% if accesslog is not defined %}
                Accesslog {{ accesslog | default('/var/log/access.log')}}
                {% endif %}
                <Directory  "/var/www/html/">
                        Require All granted
                </Directory>
        </VirtualHOst>    
      
        {% endfor %}
      
        執行效果,/etc/httpd/conf.d/vhost.conf
        <VirtualHost>
                Listen 80
                ServerName Hmaster185.magedu.com
                DocumentRoot /var/www/html
                Accesslog /var/log/access.log
                <Directory "/var/www/html/">
                        Require All granted
                </Directory>
        </VirtualHost>
      
        <VirtualHost>
                Listen 443
                ServerName Hmaster185.magedu.com
                DocumentRoot /var/www/html
                Accesslog /var/log/access.log
                <Directory "/var/www/html/">
                        Require All granted
                </Directory>
        </VirtualHost>
    • debug

      • Options:

        - msg
              The customized message that is printed. If omitted, prints a
              generic message.
              [Default: Hello world!]
          - var
              A variable name to debug.  Mutually exclusive with the 'msg'
              option.
              [Default: (null)]
        vim webj2.yml
        - name: show message
          debug: msg={{ ansible_distribution_major_version }}
        
        執行效果:ansible-playbook webj2.yml    
          TASK [show message] ************************************************************
          ok: [172.16.251.185] => {
              "msg": "7"
          }
          ok: [172.16.251.207] => {
              "msg": "7"
          }
          ok: [172.16.251.32] => {
              "msg": "6"
          }
    • with_items
      迭代,重復執行的任務,對迭代項的引用,固定變量名為item,而后在task中使用with_items給定迭代的元素列表;

      示例:
        - name: Create rsyncd config
          copy: src={{ item }} dest=/etc/{{ item }}
          with_items:
            - rsyncd.secrets
            - rsyncd.conf
      示例:
        - hosts: mageduweb
          remote_user: root
          tasks:
          - name: add several users
            user: name={{ item.name }} state=present groups={{ item.groups }}
            with_items:
              - { name: 'testuser1' , groups: 'wheel'}
              - { name: 'testuser2' , groups: 'root'}
  • roles

    • 實驗:使用roles實現httpd的安裝配置

      [root@Hmaster185 ansible]# mkdir /root/ansible/roles/httpd/{tasks,handlers,templates,files,vars} -pv
        mkdir: created directory ‘roles/httpd’
        mkdir: created directory ‘roles/httpd/tasks’
        mkdir: created directory ‘roles/httpd/handlers’
        mkdir: created directory ‘roles/httpd/templates’
        mkdir: created directory ‘roles/httpd/files’
        mkdir: created directory ‘roles/httpd/vars’
      
        vi /root/ansible/roles/httpd/tasks/install.yml    
            ---
      
            - name: install httpd
              yum: name=httpd state=present
      
        vi /root/ansible/roles/httpd/tasks/init.yml
            ---
      
            - name: init httpd
              copy: src=README dest=/etc/httpd/conf/
      
            - name: init vhost.conf
              template: src=vhost.conf.j2 dest=/etc/httpd/conf.d/vhost.conf
      
        vi /root/ansible/roles/httpd/handlers/main.yml
            ---
      
            - name: restart httpd
              service: name=httpd state=restarted
      
        將需要的資源文件拷貝到指定的目錄中
            ~]# cp /etc/httpd/conf.d/README  files/
            ~]# cp /root/ansible/httpd.conf.j2 templates/
      
        引用tasks中的文件
            vi /root/ansible/roles/httpd/tasks/main.yml
            ---
      
            - include: install.yml
            - include: init.yml
      
        編輯執行的.yml文件
            vi /root/ansible/httpdrole.yml
            ---
      
            - hosts: web
              remote_user: root
              vars:
                - vports:
                  - 80
                  - 443
                  - 808
              roles:
              - httpd
    • 實驗:使用roles實現創建用戶

      創建目錄  
        [root@Hmaster185 roles]# mkdir useradd/{tasks,vars,files,templates,handlers} -pv
        mkdir: created directory ‘useradd’
        mkdir: created directory ‘useradd/tasks’
        mkdir: created directory ‘useradd/vars’
        mkdir: created directory ‘useradd/files’
        mkdir: created directory ‘useradd/templates’
        mkdir: created directory ‘useradd/handlers’
      
        vi /root/ansible/useradd/tasks/main.ymml
        ---
      
        - name: mul add user
          user: name={{ item.name }} groups={{ item.groups }} state=present
          with_items:
            - { name: 'tom11' , groups: 'wheel' }
            - { name: 'tom22' , groups: 'root' }
      
        編輯執行文件的userrole.yml
        ---
      
        - hosts: web
          remote_user: root
          roles:
          - useradd
      
        ~]# ansible-playbook userrole.yml
    • 實驗:使用roles的tags功能

      ---
      
        - hosts: web
          remote_user: root
          vars:
            - vports:
              - 80
              - 443
              - 808
          roles:
          - { role: httpd ,tags: [ 'httpd','web' ] }
          - { role: useradd ,tags: [ 'useradd','web' ] }

原創文章,作者:s,如若轉載,請注明出處:http://www.www58058.com/79624

(0)
ss
上一篇 2017-07-09
下一篇 2017-07-09

相關推薦

欧美性久久久久