56
Ansible Basics

Ansible Basics - Adfinis SyGroup · Introduction to Ansible What's it all about? Facts Project started in 2012 Licensed under the GPLv3 Acquired by Red Hat in October 2015 Development

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

AnsibleBasics

Besmart.Thinkopensource.

Ansible-BasicsSimpleconfigmanagementandorchestration

-name:teachansiblebasicstemplate:src:good_ideas.j2dest:customersstate:present

Agenda

Configmanagementvs.orchestration

IntroductiontoAnsible

Basiccomponents

Variables

Templates

Configmanagementvs.orchestrationLearnthedifference

Configmanagement"Definehowasystemshouldlooklikeinanabstractway."

EnsureApacheandMariaDBisinstalled

Ensurefile/etc/motdcontainslineXYZ

Orchestration"Runasetoftasksonasetofserversatonce."

Updateandrestartexactly49%ofaclusteredservicetoensurethequorum

PatchallsystemswhicharevulnerabletotheDirtyCOWbug

Goals

Reproducibilityiskey

Consistency

Savetimeinthelongrun*

IntroductiontoAnsibleWhat'sitallabout?

Facts

Projectstartedin2012

LicensedundertheGPLv3

AcquiredbyRedHatinOctober2015

DevelopmentpushedbyRedHatandcommunityisgrowingfast

Ecosystem

Ansible

AnsibleAWX/Tower

AnsibleContainer(thenewfaceintown)

AnsibleGalaxy

Design

Agentless

YAMLbasedconfigurationviaSSH

WritteninPython2

TemplaterenderingwithJinja2

Strongsuite

Simplicityiskey

Easyaspie

Zeroconfiguration(almost)

WorksviaSSH

Strongsuite

Idempotence

Smallfootprint

Weakspots

Doesnotscaleaswellasothertools

Certaincomplextasksturnugly

Weakspots

AnsibleGalaxy(proceedwithcaution!)

Contributionsaresomewhatslowlyprocessed

AnsiblecomponentsBasicterminologyyouneedtoknow

ModulesModulesareusedtointeractwithnodesandmanagedifferentresources:

pingcommandcopy/synchronizelineinfilepackagemysql_user/mysql_db

HavealookattheAnsibleModuleIndex!

ModulesModulescanbeexecutedad-hoc:

$ansibleweb-iinventory.txt-uroot-mping$ansibleweb-iinventory.txt-uroot-mcommand-a"df-h"

Eachmoduleexposesdifferentoptionsthatcanbecustomized

InventoryAninventorycontainsallthetargetnodesandstructuresthemintogroups:

[adfinis:children]bernbasel

[bern:children]database

[basel:children]web

[database]db[01:03].adfinis-sygroup.chansible_user=db_admin

[web]web[01:03].adfinis-sygroup.chansible_user=web_admin

Hands-on::Basics01InstallAnsibleandtakethefirststeps

Ansiblecomponents2Furtherdowntherabbithole

Tasks

TasksareAnsiblecommandswhichcallamodule

WritteninaYAMLfile

Executedfromtoptobottom

-name:installnginx

package:name:nginxstate:present

-name:startnginxserviceservice:name:nginxstate:started

Handlers

Handlersarebasicallytasksbutnotifiedbyothertasks

Executedonlywhennecessary

-name:restartnginxservice:name:nginxstate:restarted

PlaybooksGrouptasksandhandlerstogetherinaplaybookandmakethemreusable

----hosts:webtasks:-name:templatenginx.conftemplate:src:nginx.conf.j2dest:/etc/nginx/nginx.confbackup:yesnotify:-restartnginxhandlers:-name:restartnginxservice:name:nginxstate:restarted

PlaybooksExecutetheplaybook:

$ansible-playbookwebserver.yml-iinventory.txt-uroot

RolesDivideandstructureaplaybookintodifferentroles:

Eachroleisresponsibleforacertaincomponent

Reusethesamerolesinmanydifferentprojects(playbooks)

----hosts:webroles:-common-webserver-monitoring

RolesArolehasaspecificdirectorystructure:

ansible|--webserver.yml|--roles|--nginx|--defaults|--files|--handlers|--tasks

|--templates|--vars|--meta

FactsNodespecificinformationstoredinvariables:

Hardwareresources

Networkconfiguration

Operatingsystem

andmuchmuchmore

FactsUsethe setup moduletogatheranddisplayfacts:

$ansibleweb-iinventory.txt-uroot-msetup

"ansible_facts":{"ansible_all_ipv4_addresses":["192.168.122.10"],"ansible_all_ipv6_addresses":["fe80::5054:ff:fe5c:593"],"ansible_architecture":"x86_64","ansible_bios_date":"04/01/2014","ansible_bios_version":"1.9.3-20160701_074356-anatol",[...]

Hands-on::Basics02Createsometasksandthefirstplaybook

VariablesHowtomakeyourplaybooksadaptable

Generaloverview

Ansibleallowsonetousevariablesinsteadofhardcodedvalues

Variablescanbeoverwrittenandincludedfromdifferentplaces

Supportfordifferenttypes(strings,numbers,lists,etc.)

Factsarevariablestoo

Generaloverview

Exampleofseveralvars:

nginx_packages:-nginx

nginx_conf_dir:/etc/nginx/conf.d

nginx_server_name:"{{ansible_fqdn}}"

Variablesusedwithinatask:

-name:installnginxpackage:name:"{{nginx_packages}}"state:present

ScopeAnsiblehas3differentvariablescopes:

Global(config,ENV&commandline)

Play(vars,include_vars,roledefaults&vars)

Host(specifictoamachinelikefacts)

LocationsVariablescanbeincludedfrommanydifferentlocations:

Inventory

group_vars

host_vars

Playbook

Rolesdefaults

Rolesvars

group_varsGroupvariablesareincludedbasedonthenode'sgroups:

[adfinis:children]bernbasel

[bern:children]database

[basel:children]web

[database]db[01:03].adfinis-sygroup.chansible_user=db_admin

[web]web[01:03].adfinis-sygroup.chansible_user=web_admin

host_varsCreatehostspecificvariablesinthedirectoryhost_vars:

ansible/host_vars/db01.adfinis-sygroup.ch

ansible/host_vars/web01.adfinis-sygroup.ch

PlayvarsIt'spossibletoincludevarsinyourplaybooks:

----hosts:webvars:

nginx_package:nginxvars_files:-/vars/external_vars.ymlroles:-nginx

RolevariablesTodefinevarsinyourrolecreatethefollowingfiles:

roles/nginx/defaults/main.yml

roles/nginx/vars/main.yml

Prefixallvariableswiththerolenametopreventconflicts!

VariableprecedenceAnsiblehasatrickyvariableprecedence:

roledefaultsinventoryplaybookhostfactsplayvarsregisteredvarsroleandincludevarsextravars

Seethedocumentation!

HowyoushouldusethemStartsimpleandrestrictyourselftothefollowingvars:

roledefaults

group_vars

host_vars

rolevars

Hands-on::Basics03Makeyourplaybookmoredynamicwithvariables

TemplatesGenerateconfigurationsonthefly

GeneraloverviewAnsiblesupportsrenderingoftemplatesthroughJinja2:

Usethetemplatemodule

Createafileintheroledirectory"templates"withthesuffix.j2

server{listen80default_server;server_name{{nginx_server_name}};

location/{root/var/www;}}

LoopsJinja2templatesalsosupportloopstogeneratemultipleconfigblocks:

nginx_locations:-path:/webalias:/var/www/web-path:/adminalias:/var/www/admin

{%foriteminnginx_locations%}location{{item.path}}{alias{{item.alias}};autoindexon;}

{%endfor%}

ConditionsUseconditions(if,else,etc.)tohaveevenmorecontrol:

{%-ifnginx_ssl%}server{listen443default_server;server_name{{nginx_server_name}};[...]{%-endif%}

Hands-on::Basics04Generatefilesdynamicallywithtemplates

FieldreportWhathaveyoulearned?

Ansiblebasics

AnsiblecomponentsVariablehandling

Templaterendering

FieldreportCanyoudescribealldirectories?

ansible|--group_vars|--host_vars|--webserver.yml|--roles|--nginx|--defaults|--files|--handlers|--tasks|--templates|--vars|--meta

Quovadis?

AnsibleBestPractice

AnsibleVault

Multidistributionsupport

DevelopmentWorkflow(CI&CT)

Rolloutstrategyandclustermanagement

FeedbackThegood,thebadandtheugly

Thankyou!Besmart.Thinkopensource.

Attribution/License

XKCD-TheGeneralProblem,byxkcdhttps://xkcd.com/974/LicenseCC-BY-NCseehttps://xkcd.com/license.html