Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Automatización de tareas con Ansible

Automatización de tareas con Ansible

César Suárez Ortega

March 14, 2015
Tweet

More Decks by César Suárez Ortega

Other Decks in Programming

Transcript

  1. Automatización
    de tareas con
    Seminario TheEvnt
    Preguntando a las ballenas
    Devops con Ansible y Docker
    13-14 Febrero (Cáceres)

    View Slide

  2. csuarez
    César Suárez Ortega
    Software Engineer / Researcher
    tharandur
    [email protected]

    View Slide

  3. Software Engineer / Researcher
    César Suárez Ortega

    View Slide

  4. View Slide

  5. http://www.meetup.com/phpcaceres
    24 de Marzo // 18:30 // 7 Jardines
    LESS IS MORE
    By Juan José Galán (@Jgalanlo)

    View Slide

  6. www.suicidebystar.com

    View Slide

  7. HERRAMIENTAS DE AUTOMATIZACIÓN
    ¿PARA QUÉ VALEN?

    View Slide

  8. DESPLIEGUE DE
    APLICACIONES
    CONTINOUS
    DELIVERY
    VIRTUALIZACIÓN
    CLOUDS
    VAGRANT
    GESTIÓN DE
    CONFIGURACIONES
    DOCKER
    TEST
    HOMOGENEIZACIÓN

    View Slide

  9. View Slide

  10. Lenguaje Ruby DSL YAML YAML
    Agentless No No Sí Sí
    Arquitectura Master/Slave Master/Slave Masterless Ambos
    Comunicación Propio Propio SSH ZeroMQ

    View Slide

  11. View Slide

  12. ¿Por qué Ansible?
    ¥ “Radically simple”
    ¥ Agentless
    ¥ Pocos requisitos (python, OpenSSH, …)
    ¥ Curva de aprendizaje escasa
    ¥ Configuración legible (YAML)
    ¥ Buena documentación
    ¥ http://docs.ansible.com/

    View Slide

  13. Cualquiera es mejor que
    nada

    View Slide

  14. ANSIBLE 101
    Empezando con Ansible

    View Slide

  15. Instalación
    $ sudo apt-get install software-properties-common!
    $ sudo apt-add-repository ppa:ansible/ansible!
    $ sudo apt-get update!
    $ sudo apt-get install ansible!
    $ sudo yum install epel-release!
    $ sudo yum install ansible!
    $ brew update!
    $ brew install ansible!
    $ sudo pip install ansible!
    http://brew.sh/

    View Slide

  16. View Slide

  17. Inventories
    ¥  Inventario de máquinas
    ¥  Definición de nuestra infraestructura
    ¥  Formato INI
    ¥  Por defecto en /etc/ansible/hosts!
    ¥  Muchas vitaminas
    ¥ Grupos
    ¥ Rangos
    ¥ Parámetros
    ¥ …
    ¥  Inventories dinámicos

    View Slide

  18. Inventories
    !
    [webservers]!
    server1.company.com!
    server2.company.com!
    188.234.123.12!
    !
    [databases]!
    mysql-prod-[1:10].company.com!
    mysql-test-[a:f].company.com!
    !
    [base]!
    dns.company.com ansible_ssh_user=root ansible_ssh_password=chapuza!
    dhcp.company.com ansible_conection=ssh!
    !
    [storage]!
    ftp.company.com ftp_port=23!
    !
    [misc]!
    some_alias ansible_ssh_host=134.23.42.123!
    !

    View Slide

  19. $ ansible all -m command -a ”pwd” –f 10 -k !
    $ ssh-keygen -t rsa -C "[email protected]"!
    !
    $ cat ~/.ssh/id_rsa.pub | \!
    ssh @ “cat >> .ssh/authorized_keys”!
    Confianza SSH
    o

    View Slide

  20. Nuestro primer comando :)
    ¥ ansible: Comando!
    ¥ all: Parte del inventario a usar.!
    ¥ -m command: Módulo
    ¥ -a "ls /tmp": Atributos del módulo
    $ ansible all -m command -a "ls /tmp”!

    View Slide

  21. Más comandos
    $ ansible all -m copy -a "src=/tmp/foo dest=/tmp/foo"!
    $ ansible webservers -m yum -a "name=php5 state=present"!
    $ ansible all -m command -a ”pwd” –f 10 !
    $ ansible all -m command -a ”rm –rf /” –i custom_inventory!

    View Slide

  22. PLAYBOOKS

    View Slide

  23. Introducción a Playbooks
    ¥ Automatización de tareas complejas.
    ¥ Ficheros en formato YAML.
    ¥ Definición de:
    ¥ Tareas
    ¥ Pasos
    ¥ Variables
    “Los módulos son las herramientas
    y los playbooks los planos”

    View Slide

  24. YAML Ain’t Another Markup
    Language
    ---!
    -  hosts: webservers!
    ..vars:!
    ....http_port: 80!
    ....max_clients: 200!
    ....remote_user: root!
    ..tasks:!
    ....- name: ensure apache is at the latest version!
    ......yum: pkg=httpd state=latest!
    ....- name: write the apache config file!
    ......template: src=/srv/httpd.j2 dest=/etc/httpd.conf!
    ....- name: ensure apache is running!
    ......service: name=httpd state=started!

    View Slide

  25. ---!
    - hosts: webservers!
    vars:!
    http_port: 80!
    max_clients: 200!
    remote_user: root!
    tasks:!
    - name: ensure apache is at the latest version!
    yum: pkg=httpd state=latest!
    - name: write the apache config file!
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf!
    - name: ensure apache is running!
    service: name=httpd state=started!
    !
    !
    $ ansible-playbook my-playbook.yml!
    !
    !

    View Slide

  26. View Slide

  27. Módulos
    ¥ +200 incluidos por defecto
    ¥ Aceptan parámetros clave-valor:
    ¥  key1=value1, key2=value2, key3=value3!
    ¥ Ídempotentes
    ¥ No se ejecutan si no hace falta.
    ¥ Documentación:
    $ ansible-doc !
    http://docs.ansible.com/modules.html !
    o

    View Slide

  28. Manejo de ficheros
    template: src=www.conf dest=/etc/php-fpm.d/www.conf!
    copy: src=www.conf dest=/etc/php-fpm.d/www.conf!
    copy
    template
    lineinfile: dest=/etc/foo regexp=^SELINUX= line=SELINUX=enforcing!
    lineinfile
    replace: dest=/foo regexp='(\s+)old(\s+.*)?$' replace='\1new\2’!
    replace

    View Slide

  29. template
    [www]!
    !
    listen = 127.0.0.1:9000!
    !
    listen.allowed_clients = 127.0.0.1!
    !
    user = {{ php_user }}!
    group = {{ php_group }}!
    !
    pm = dynamic!
    pm.max_children = 50!
    pm.start_servers = 5!
    pm.min_spare_servers = 5!
    pm.max_spare_servers = 35!
    !
    php_admin_value[error_log] = /var/log/php-fpm/www-error.log!
    php_admin_flag[log_errors] = on!
    !
    php_value[session.save_handler] = files!
    php_value[session.save_path] = /var/lib/php/session!

    View Slide

  30. Linux básico
    shell: chmod –R 777 /tmp!
    command: touch /tmp/foo!
    command
    shell
    yum: name=php-fpm state=latest #present, absent, ...!
    yum / apt
    service: name=httpd state=stopped #started, restarted, ...!
    service

    View Slide

  31. Miscelánea
    git: repo=https://github.com/WordPress/WordPress.git dest=/!
    mysql_db: name=db state=present login_user=root login_password=!
    mysql_db
    git
    docker: image=foo/image_name links=postgresql:db,redis:redis!
    docker++
    docker: image=centos command="service tomcat6 start" ports=8080!
    docker

    View Slide

  32. View Slide

  33. PLAYBOOKS++

    View Slide

  34. Variables

    View Slide

  35. Uso de variables
    !
    !
    !
    !
    !
    !
    ---!
    - hosts: webservers!
    vars:!
    deploy_path: /var/www/html/current!
    base_packages: [php-fpm, mysql, nginx] !
    tasks:!
    - name: deploy code!
    copy: src=local_wordpress/ dest={{ deploy_path }}!
    !
    - name: copy wp-config!
    copy: src=config.php dest={{ deploy_path }}/wp-config.php!
    !
    !
    !

    View Slide

  36. Filtros
    !
    !
    !
    !
    {{ random_variable | mandatory }}!
    !
    !
    {{ some_port | default(80) }}!
    !
    !
    {{ http_response | to_nice_json }}!
    !
    !
    {{ password | hash(‘md5’) }}!
    !
    !
    {{ something | regex_replace(‘[email protected]#/”!!!’) }}!
    !
    !
    !

    View Slide

  37. Facts
    ¥ Variables del “sistema”.
    ¥ Algunas
    ¥ ansible_hostname!
    ¥ ansible_kernal!
    ¥ ansible_eth0.ipv4.address!
    ¥ …!
    ¥ Obtener todas:
    $ ansible all –m setup!

    View Slide

  38. Condicionales

    View Slide

  39. when
    !
    !
    !
    !
    !
    !
    !
    - name: ”apagar sistema Debian”!
    command: /sbin/shutdown -t now!
    when: ansible_os_family == ”Debian” !
    !
    - shell: echo ”sistemas RedHat 6 o superiores"!
    when: ansible_os_family == "RedHat" !
    and ansible_lsb.major_release|int >= 6!
    !
    !
    !
    !
    !
    !

    View Slide

  40. Filtros interesantes
    !
    tasks:!
    !
    - shell: /usr/bin/foo!
    register: result!
    ignore_errors: True!
    !
    - debug: msg=”¡falló!"!
    when: result|failed!
    !
    - debug: msg=”¡cambió!"!
    when: result|changed!
    !
    - debug: msg=”¡funcionó!"!
    when: result|success!
    !
    - debug: msg=”¡se saltó!"!
    when: result|skipped!
    !
    !

    View Slide

  41. Loops

    View Slide

  42. with_xxx
    vars:!
    php_packages: [php-xml, php-mysql, php-gd]!
    users:!
    user1:!
    nombre: Curro!
    apellido: Rodríguez!
    user2:!
    nombre: Álvaro!
    apellido: De la Mata!
    !
    tasks:!
    - name: Instalar paquetes PHP!
    yum: name={{ item }} state=latest!
    with_items: php_packages!
    !
    - name: Imprimir nombres!
    debug: msg=“{{ item.key }}: {{ item.value.nombre }} {{ item.value.apellido }}"!
    with_dict: users!
    !
    - name: Copiar ficheros!
    copy: src={{ item }} dest=/tmp/!
    with_fileglob:!
    - /home/user/*!
    !
    !

    View Slide

  43. Handlers

    View Slide

  44. Handlers
    ¥ Lanzar acciones cuando un módulo cambia
    ---!
    - hosts: webservers!
    vars:!
    http_port: 80!
    tasks:!
    - name: ensure apache is at the latest version!
    yum: pkg=httpd state=latest!
    - name: write the apache config file!
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf!
    notify:!
    - restart apache!
    - name: ensure apache is running!
    service: name=httpd state=started!
    handlers:!
    - name: restart apache!
    service: name=httpd state=restarted!

    View Slide

  45. Tags

    View Slide

  46. !
    !
    ---!
    -  hosts: webservers!
    -  tasks:!
    - name: ensure apache is running!
    service: name=httpd state=started!
    tags:!
    - apache!
    - name: ensure php-fpm is running!
    service: name=php-fpm state=started!
    tags:!
    - php!
    !
    !
    $ ansible-playbook my-playbook.yml –-tags “php”!
    !
    !

    View Slide

  47. Includes

    View Slide

  48. includes
    !
    !
    !
    !
    tasks:!
    !
    - include: tasks/foo.yml!
    !
    - include: wordpress.yml wp_user=timmy!
    - include: wordpress.yml wp_user=alice!
    - include: wordpress.yml wp_user=bob!
    !
    - include: tasks/sometasks.yml!
    when: ansible_os_family == 'Debian’!
    !
    !
    !
    !
    !
    !

    View Slide

  49. ROLES

    View Slide

  50. ¿Qué son los roles?
    ¥ Organización de playbooks.
    ¥ “Convention over configuration”
    ¥ Carga automática de:
    ¥ Tasks
    ¥ Vars
    ¥ Handlers
    ¥ Dependencias
    ¥ Reutilizables

    View Slide

  51. Estructura de roles
    ¥  some_role/!
    ¥  files/ * Ficheros para copy
    ¥  templates/ * Ficheros para template
    ¥  tasks/
    ¥  handlers/
    ¥  vars/
    ¥  defaults/ * Valores por defecto
    ¥  meta/ * Dependencias
    ---!
    - hosts: webservers!
    roles:!
    - some_role!
    !
    !

    View Slide

  52. http://github.com/csuarez/theevnt-ansible

    View Slide

  53. View Slide

  54. View Slide