zoukankan      html  css  js  c++  java
  • Ansible Playbook

    Ansible Playbook

    官方文档:


    环境:
    CentOS 7.2
    ansible 2.2

    root@router:lamp_haproxy#pwd

    /root/lamp_haproxy

    root@router:lamp_haproxy#cat hosts 

    [self]

    localhost ansible_connection=local


    [nodes:children]

    webservers

    dbservers

    lbservers


    [nodes:vars]

    ansible_ssh_private_key_file=/home/web/.ssh/id_rsa


    [webservers]

    192.168.8.101


    [dbservers]

    192.168.8.102


    [lbservers]

    192.168.8.103


    一.创建管理用户

    1.所有节点创建web(sudoer)

    ansible all -i hosts -m user -a 'name=web generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa'

    ansible all -i hosts -m shell -a "echo 'web ALL=(ALL) NOPASSWD:ALL' >/etc/sudoers.d/web"

    2.将web用户的公钥导入到被管理节点

    ansible nodes -i hosts -m copy -a "src=/home/web/.ssh/id_rsa.pub dest=/home/web/.ssh/authorized_keys"

    ansible nodes -i hosts -m file -a "dest=/home/web/.ssh/authorized_keys mode=600 owner=web group=web"


    root@router:lamp_haproxy#ansible nodes -i hosts -u web -s -m ping 

    192.168.8.103 | SUCCESS => {

        "changed": false, 

        "ping": "pong"

    }

    192.168.8.102 | SUCCESS => {

        "changed": false, 

        "ping": "pong"

    }

    192.168.8.101 | SUCCESS => {

        "changed": false, 

        "ping": "pong"

     

    }

    测试ok



    二.简单playbook

    cat >foo.yml <<EOF

    ---

    - name: install a few packages

      hosts: webservers

      remote_user: web 

      become: yes 


      tasks:

      - name: install python bindings for selinux

        yum: name={{item}} state=present

        with_items:

        - libselinux-python

        - libsemanage-python

        tags:

        - p1

      - name: test to see if selinux is running

        command: getenforce

        register: sestatus

        changed_when: false

        tags:

        - p2

      - name: install apache

        yum: name=httpd state=present

        when: ansible_os_family == "RedHat"

          tags:

        - p3

      - name: ensure apache is running 

        service: name=httpd state=started enabled=yes
        tags:

        - p4

    EOF


    root@router:lamp_haproxy#ansible-playbook foo.yml 


    PLAY [install a few packages] **************************************************


    TASK [setup] *******************************************************************

    ok: [192.168.8.101]


    TASK [install python bindings for selinux] *************************************

    ok: [192.168.8.101] => (item=[u'libselinux-python', u'libsemanage-python'])


    TASK [test to see if selinux is running] ***************************************

    ok: [192.168.8.101]


    TASK [install apache] **********************************************************

    ok: [192.168.8.101]


    TASK [ensure apache is running] ************************************************

    ok: [192.168.8.101]


    PLAY RECAP *********************************************************************

    192.168.8.101              : ok=5    changed=0    unreachable=0    failed=0 

    提示: ansible-playbook提供非常实用的retry和tag机制(执行指定tag,跳过某些tag)来减少没必要的操作以加快执行速度。

    root@router:playbook#ansible-playbook foo.yml --list-tags

    playbook: foo.yml

      play #1 (webservers): install a few packages    TAGS: []
          TASK TAGS: [p1, p2, p3, p4]
    root@router:playbook#ansible-playbook foo.yml --list-task

    playbook: foo.yml

      play #1 (webservers): install a few packages    TAGS: []
        tasks:
          install python bindings for selinux    TAGS: [p1]
          test to see if selinux is running    TAGS: [p2]
          install apache    TAGS: [p3]
          ensure apache is running    TAGS: [p4]
    root@router:playbook#ansible-playbook foo.yml --tags p3

    PLAY [install a few packages] **************************************************

    TASK [setup] *******************************************************************
    ok: [192.168.8.101]

    TASK [install apache] **********************************************************
    ok: [192.168.8.101]

    PLAY RECAP *********************************************************************
    192.168.8.101              : ok=2    changed=0    unreachable=0    failed=0  

    root@router:playbook#ansible-playbook foo.yml --skip-tags p1,p2,p3

    PLAY [install a few packages] **************************************************

    TASK [setup] *******************************************************************
    ok: [192.168.8.101]

    TASK [ensure apache is running] ************************************************
    ok: [192.168.8.101]

    PLAY RECAP *********************************************************************
    192.168.8.101              : ok=2    changed=0    unreachable=0    failed=0 



    三.基于roles的模块化playbook(lamp_haproxy)

    1.初始化roles目录结构(ansible-galaxy init)

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

    root@router:lamp_haproxy#mkdir roles

    root@router:lamp_haproxy#cd roles/

    root@router:roles#for i in common apache web db haproxy;do ansible-galaxy init $i;done

    - common was created successfully

    - apache was created successfully

    - web was created successfully

    - db was created successfully

    - haproxy was created successfully

    root@router:roles#tree common/

    common/

    ├── defaults

    │   └── main.yml

    ├── files

    ├── handlers

    │   └── main.yml

    ├── meta

    │   └── main.yml

    ├── README.md

    ├── tasks

    │   └── main.yml

    ├── templates

    ├── tests

    │   ├── inventory

    │   └── test.yml

    └── vars

        └── main.yml

    8 directories, 8 files

    2.编写playbook

    i.selinux

    selinux task

    cat >roles/common/tasks/selinux.yml <<EOF

    ---

    - name: install python bindings for selinux

      yum: name={{item}} state=present

      with_items:

      - libselinux-python

      - libsemanage-python


    - name: test to see if selinux is running

      command: getenforce

      register: sestatus

      changed_when: false

    EOF

    ii.ntp

    ntp变量

    cat >group_vars/all <<EOF

    ---

    # Variables here are applicable to all host groups

    httpd_port: 80 

    ntpserver: 192.168.8.254

    EOF

    模板ntp.conf.j2

    cat >roles/common/templates/ntp.conf.j2 <<EOF

    driftfile /var/lib/ntp/drift

    restrict 127.0.0.1

    restrict -6 ::1

    server {{ ntpserver }}

    includefile /etc/ntp/crypto/pw

    keys /etc/ntp/keys

    EOF

    ntp task

    cat >roles/common/tasks/ntp.yml <<EOF

    ---

    - name: install ntp 

      yum: name=ntp state=present


    - name: configure ntp 

      template: src=ntp.conf.j2 dest=/etc/ntp.conf

      notify: restart ntp 


    - name: start the ntp service

      service: name=ntpd state=started enabled=yes

    EOF

     

    ntp handler

    cat >roles/common/handlers/main.yml <<EOF

    ---

    - name: restart ntp

      service: name=ntpd state=restarted

    EOF

    作为common组件的入口,只需要在main.yml中include定义好的yml及可

    cat >roles/common/tasks/main.yml <<EOF

    ---

    - include: selinux.yml

    - include: ntp.yml

    EOF

    iii.apache

    cat >roles/apache/tasks/main.yml <<EOF

    ---

      - name: install apache

        yum: name=httpd state=present

      

      - name: ensure apache is running 

        service: name=httpd state=started enabled=yes

    EOF

    iv.web

    web变量

    cat >group_vars/webservers <<EOF

    ---

    # Variables for the web server configuration

    # iface: eth1

    iface: '{{ ansible_default_ipv4.interface }}'


    # sample webapp

    repository: https://github.com/bennojoy/mywebapp.git


    # this is the sha1sum of V5 of test test webapp.

    webapp_version: 351e47276cc66b018f4890a04709d4cc3d3edb0d

    EOF

    web task

    cat >roles/web/tasks/main.yml <<EOF

    ---

    - name: install php and git 

      yum: name={{item}} state=present

      with_items:

      - php

      - php-mysql

      - git


    - name: configure selinux to allow httpd to connect to remote database

      seboolean: name=httpd_can_network_connect_db state=true persistent=yes

      when: sestatus.rc != 0


    - name: checkout code from repository

      git: repo={{repository}} version={{webapp_version}} dest=/var/www/html/

    EOF

    v.mariadb

    mariadb变量

    cat >group_vars/dbservers <<EOF

    ---

    # The variables file used by the playbooks in the dbservers group.

    # These don't have to be explicityly imported by vars_files: they are autopopulated.


    mysqlservice: mysqld

    mysql_port: 3306

    dbuser: root

    dbname: foodb

    upassword: abc

    EOF

    mariadb配置文件模板

    cat >roles/db/templates/my.cnf.j2 <<EOF

    [mysqld]

    datadir=/var/lib/mysql

    socket=/var/lib/mysql/mysql.sock

    user=mysql

    init_connect = 'SET collation_connection = utf8_general_ci'

    init_connect = 'SET NAMES utf8'

    character_set_server = utf8

    collation_server = utf8_general_ci

    # Disabling symbolic-links is recommended to prevent assorted security risks

    symbolic-links=0

    port={{ mysql_port }}


    [mysqld_safe]

    pid-file = /var/run/mysqld/mysqld.pid

    log-error = /var/log/mysqld.log

    EOF

    mariadb task

    cat >roles/db/tasks/main.yml <<EOF

    ---

    - name: install mariadb/firewalld

      yum: name={{item}} state=installed

      with_items:

      - mariadb-server

      - MySQL-python

      - firewalld


    - name: configure selinux to start mariadb on any port

      seboolean: name=mysql_connect_any state=true persistent=yes

      when: sestatus.rc != 0


    - name: create mariadb configuration file

      template: src=my.cnf.j2 dest=/etc/my.cnf

      notify: restart mariadb


    - name: create mariadb log file

      file: path=/var/log/mysqld.log state=touch owner=mysql group=mysql mode=0664


    - name: create mariadb PID directory

      file: path=/var/run/mysqld state=directory owner=mysql group=mysql mode=0775


    - name: start mariadb service

      service: name=mariadb state=started enabled=yes


    - name: start firewalld service

      service: name=firewalld state=started enabled=yes


    - name: insert firewalld rule

      firewalld: port={{mysql_port}}/tcp permanent=true state=enabled immediate=yes


    - name: create application database

      mysql_db: name={{dbname}} state=present


    - name: create application database user

      mysql_user: name={{dbuser}} password={{upassword}} priv=*.*:ALL host='%' state=present

    EOF

    mariadb handler

    cat >roles/db/handlers/main.yml <<EOF

    ---

    - name: restart mariadb

      service: name=mariadb state=restarted

    EOF

    vi.haproxy

    haproxy变量

    cat >group_vars/lbservers <<EOF

    ---

    # Variables for the HAproxy configuration


    # HAProxy supports 'http' and 'tcp'. For SSL, SMTP, etc, use 'tcp'.

    mode: http


    # Port on which HAProxy should listen

    listenport: 8888


    # A name for the haproxy daemon, this will be the suffix in the logs.

    daemonname: myapplb


    # Balancing Algorithm. Available options:

    # roundrobin,source,leastconn,uri (if persistance is required use 'source')

    balance: leastconn


    # iface: eth1

    iface: '{{ ansible_default_ipv4.interface }}'

    EOF

    haproxy配置文件模板

    cat >roles/haproxy/templates/haproxy.cfg.j2 <<EOF

    global

        log         127.0.0.1 local2

        chroot      /var/lib/haproxy

        pidfile     /var/run/haproxy.pid

        maxconn     4000

        user        haproxy

        group       haproxy

        daemon

        stats socket /var/lib/haproxy/stats


    defaults

        log                     global

        option                  dontlognull

        option http-server-close

        option                  redispatch

        retries                 3

        timeout http-request    10s

        timeout queue           1m

        timeout connect         10s

        timeout client          1m

        timeout server          1m

        timeout http-keep-alive 10s

        timeout check           10s

        maxconn                 3000

        stats enable    

        stats uri /haproxy-stats

        stats refresh 10s

        stats realm Haproxy statistic

        stats auth hadmin:foo.123


    backend app

        {% for host in groups['lbservers'] %}

        listen {{ daemonname }} {{ hostvars[host]['ansible_'+iface].ipv4.address }}:{{ listenport }}

        {% endfor %}

        balance {{ balance }}

        {% for host in groups['webservers'] %}

        server {{ host }} {{ hostvars[host]['ansible_'+iface].ipv4.address }}:{{ httpd_port }}

        {% endfor %}

    EOF

    haproxy task

    cat >roles/haproxy/tasks/main.yml <<EOF

    ---

      name: install haproxy

        yum: name=haproxy state=present

      

      name: create haproxy configuration file

        template: src=haproxy.cfg.j2 dest=/etc/haproxy/haproxy.cfg

        notify: restart haproxy

      

      name: start haproxy service

        service: name=haproxy state=started enabled=yes

    EOF

    haproxy handler

    cat >roles/haproxy/handlers/main.yml <<EOF

    ---

    name: restart haproxy

      service: name=haproxy state=restarted

    EOF

    vii.整合playbook

    cat >lamph.yml <<EOF

    ---

    - name: install a few packages

      hosts: nodes

      remote_user: web 

      become: yes 


      roles:

      - common


    - name: configure and deploy database server

      hosts: dbservers

      remote_user: web 

      become: yes 


      roles:

      - db


    - name: configure and deploy web server

      hosts: webservers

      remote_user: web 

      become: yes 


      roles:

      - apache

      - web


    - name: configure and deploy load balancer

      hosts: lbservers

      remote_user: web 

      become: yes 


      roles:

      - haproxy

    EOF

    3.测试playbook

    root@router:lamp_haproxy#ansible-playbook -i hosts lamph.yml 

    PLAY [install a few packages] **************************************************


    TASK [setup] *******************************************************************

    ok: [192.168.8.103]

    ok: [192.168.8.102]

    ok: [192.168.8.101]


    TASK [common : install python bindings for selinux] ****************************

    ok: [192.168.8.103] => (item=[u'libselinux-python', u'libsemanage-python'])

    ok: [192.168.8.102] => (item=[u'libselinux-python', u'libsemanage-python'])

    ok: [192.168.8.101] => (item=[u'libselinux-python', u'libsemanage-python'])


    TASK [common : test to see if selinux is running] ******************************

    ok: [192.168.8.103]

    ok: [192.168.8.102]

    ok: [192.168.8.101]


    TASK [common : install ntp] ****************************************************

    ok: [192.168.8.102]

    ok: [192.168.8.103]

    ok: [192.168.8.101]


    TASK [common : configure ntp] **************************************************

    ok: [192.168.8.103]

    ok: [192.168.8.102]

    ok: [192.168.8.101]


    TASK [common : start the ntp service] ******************************************

    ok: [192.168.8.103]

    ok: [192.168.8.102]

    ok: [192.168.8.101]


    PLAY [configure and deploy database server] ************************************


    TASK [setup] *******************************************************************

    ok: [192.168.8.102]


    TASK [db : install mariadb/firewalld] ******************************************

    ok: [192.168.8.102] => (item=[u'mariadb-server', u'MySQL-python', u'firewalld'])


    TASK [db : configure selinux to start mariadb on any port] *********************

    ok: [192.168.8.102]


    TASK [db : create mariadb configuration file] **********************************

    ok: [192.168.8.102]


    TASK [db : create mariadb log file] ********************************************

    changed: [192.168.8.102]


    TASK [db : create mariadb PID directory] ***************************************

    ok: [192.168.8.102]


    TASK [db : start mariadb service] **********************************************

    ok: [192.168.8.102]


    TASK [db : start firewalld service] ********************************************

    ok: [192.168.8.102]


    TASK [db : insert firewalld rule] **********************************************

    ok: [192.168.8.102]


    TASK [db : create application database] ****************************************

    ok: [192.168.8.102]


    TASK [db : create application database user] ***********************************

    ok: [192.168.8.102]


    PLAY [configure and deploy web server] *****************************************


    TASK [setup] *******************************************************************

    ok: [192.168.8.101]


    TASK [apache : install apache] *************************************************

    ok: [192.168.8.101]


    TASK [apache : ensure apache is running] ***************************************

    ok: [192.168.8.101]


    TASK [web : install php and git] ***********************************************

    ok: [192.168.8.101] => (item=[u'php', u'php-mysql', u'git'])


    TASK [web : configure selinux to allow httpd to connect to remote database] ****

    skipping: [192.168.8.101]


    TASK [web : checkout code from repository] *************************************

    ok: [192.168.8.101]


    PLAY [configure and deploy load balancer] **************************************


    TASK [setup] *******************************************************************

    ok: [192.168.8.103]


    TASK [haproxy : install haproxy] ***********************************************

    ok: [192.168.8.103]


    TASK [haproxy : create haproxy configuration file] *****************************

    ok: [192.168.8.103]


    TASK [haproxy : start haproxy service] *****************************************

    ok: [192.168.8.103]


    PLAY RECAP *********************************************************************

    192.168.8.101              : ok=11   changed=0    unreachable=0    failed=0   

    192.168.8.102              : ok=17   changed=1    unreachable=0    failed=0   

    192.168.8.103              : ok=10   changed=0    unreachable=0    failed=0

    root@router:lamp_haproxy#elinks -dump 192.168.8.103:8888

       Hello World! My App deployed via Ansible V5.

    root@router:lamp_haproxy#telnet 192.168.8.102 3306

    Trying 192.168.8.102...

    Connected to 192.168.8.102.

    Escape character is '^]'.

    R

    5.5.44-MariaDBu+r!J0O|!?D}jzH6sbr9cemysql_native_password

    ^]

    telnet> ^C   

    Connection closed by foreign host.

  • 相关阅读:
    Visual Studio Code使用NVM指定的节点版本
    webpackd学习的意义
    scss--函数 (Functions)--unit
    scss--函数 (Functions)--unitless
    JS中的事件绑定,事件捕获,事件冒泡以及事件委托,事件参数(event.target,e.srcElement,event.currentTarget,),兼容IE
    移动端rem
    单例模式
    代理模式
    装饰者模式
    策略模式
  • 原文地址:https://www.cnblogs.com/lixuebin/p/10813991.html
Copyright © 2011-2022 走看看