ansible hands-on introduction - wordpress.com · 2018-04-20 · ansible hands-on introduction jon...

41
Ansible Hands-on Introduction Jon Jozwiak, Sr. Cloud Solutions Architect Minneapolis RHUG - April 13, 2017

Upload: others

Post on 30-May-2020

14 views

Category:

Documents


1 download

TRANSCRIPT

AnsibleHands-onIntroduction

JonJozwiak,Sr.CloudSolutionsArchitect

MinneapolisRHUG-April13,2017

WhatisAnsible?It'sasimpleautomationlanguagethatcanperfectlydescribeanITapplicationinfrastructureinAnsiblePlaybooks.

It'sanautomationenginethatrunsAnsiblePlaybooks.

AnsibleTowerisanenterpriseframeworkforcontrolling,securingandmanagingyourAnsibleautomationwithaUIandRESTfulAPI.

AnsibleIs...

CommunityTHEMOSTPOPULAROPEN-SOURCEAUTOMATIONCOMMUNITYONGITHUB

13,000+stars&4,000+forksonGitHub2000+GitHubContributorsOver900modulesshippedwithAnsibleNewcontributorsaddedeveryday1200+usersonIRCchannelTop10opensourceprojectsin2014World-widemeetupstakingplaceeveryweekAnsibleGalaxy:over18,000subscribers250,000+downloadsamonthAnsibleFestsinNYC,SF,London

http://ansible.com/community

InstallingAnsible

#Installwithyum(ExampleRHEL7)$wgethttp://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm$yumlocalinstallepel-release-7-9.noarch.rpm$yum--enablerepo=epelinstallansible

#Installusingpip$pipinstallansible

HowAnsibleWorks

ModulesModulesarebitsofcodetransferredtothetargetsystemandexecutedtosatisfythetaskdeclaration.Ansibleshipswithseveralhundredtoday!

apt/yumcopyfileget_urlgitpingdebugservicesynchronizetemplate

ModulesDocumentationhttp://docs.ansible.com/

ModulesDocumentation

#Listoutallmodulesinstalled$ansible-doc-l...copycron...

#Readdocumentationforinstalledmodule$ansible-doccopy>COPY

The[copy]modulecopiesafileonthelocalboxtoremotelocations.Usethe[fetch]moduletocopyfilesfromremotelocationstothelocalbox.Ifyouneedvariableinterpolationincopiedfiles,usethe[template]module.

*note:Thismodulehasacorrespondingactionplugin.

Options(=ismandatory):...

Modules:RunCommandsIfAnsibledoesn’thaveamodulethatsuitsyourneedstherearethe“runcommand”modules:

command:Takesthecommandandexecutesitonthehost.Themostsecureandpredictable.shell:Executesthroughashelllike/bin/shsoyoucanusepipesetc.Becareful.script:Runsalocalscriptonaremotenodeaftertransferringit.raw:ExecutesacommandwithoutgoingthroughtheAnsiblemodulesubsystem.

NOTE:Unlikestandardmodules,runcommandshavenoconceptofdesiredstateandshouldonlybeusedasalastresort.

InventoryInventoryisacollectionofhosts(nodes)withassociateddataandgroupingsthatAnsiblecanconnectandmanage.

Hosts(nodes)GroupsInventory-specificdata(variables)Staticordynamicsources

StaticInventoryExample

10.42.0.210.42.0.610.42.0.710.42.0.810.42.0.100host.example.com

StaticInventoryExample

[control]controlansible_host=10.42.0.2

[web]node-[1:3]ansible_host=10.42.0.[6:8]

[haproxy]haproxyansible_host=10.42.0.100

[all:vars]ansible_user=vagrantansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

Ad-HocCommandsAnad-hoccommandisasingleAnsibletasktoperformquickly,butdon’twanttosaveforlater.

#checkallmyinventoryhostsarereadytobe#managedbyAnsible$ansibleall-mping

#collectanddisplaythediscoveredfacts#forthelocalhost$ansiblelocalhost-msetup

#runtheuptimecommandonallhostsinthe#webgroup$ansibleweb-mcommand-a"uptime"

Sidebar:DiscoveredFactsFactsarebitsofinformationderivedfromexaminingahostsystemsthatarestoredasvariablesforlateruseinaplay.

$ansiblelocalhost-msetuplocalhost|success>>{"ansible_facts":{"ansible_default_ipv4":{"address":"192.168.1.37","alias":"wlan0","gateway":"192.168.1.1","interface":"wlan0","macaddress":"c4:85:08:3b:a9:16","mtu":1500,"netmask":"255.255.255.0","network":"192.168.1.0","type":"ether"},

Lab#1:Ad-HocCommands

VariablesAnsiblecanworkwithmetadatafromvarioussourcesandmanagetheircontextintheformofvariables.

CommandlineparametersPlaysandtasksFilesInventoryDiscoveredfactsRoles

TasksTasksaretheapplicationofamoduletoperformaspecificunitofwork.

file:Adirectoryshouldexistyum:Apackageshouldbeinstalledservice:Aserviceshouldberunningtemplate:Renderaconfigurationfilefromatemplateget_url:FetchanarchivefilefromaURLgit:Cloneasourcecoderepository

ExampleTasksinaPlay

tasks:-name:httpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:restarthttpdservice:name:httpdstate:restarted

HandlerTasksHandlersarespecialtasksthatrunattheendofaplayifnotifiedbyanothertaskwhenachangeoccurs.

Ifaconfigurationfilegetschangednotifyaservicerestarttaskthatitneedstorun.

ExampleHandlerTaskinaPlay

tasks:-name:httpdpackageispresentyum:name:httpdstate:latestnotify:restarthttpd

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

handlers:-name:restarthttpdservice:name:httpdstate:restarted

Plays&PlaybooksPlaysareorderedsetsoftaskstoexecuteagainsthostselectionsfromyourinventory.Aplaybookisafilecontainingoneormoreplays.

PlaybookExample

----name:installandstartapachehosts:webbecome:yesvars:http_port:80

tasks:-name:httpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:httpdisstartedservice:name:httpdstate:started

Human-MeaningfulNaming

----name:installandstartapachehosts:webbecome:yesvars:http_port:80

tasks:-name:httpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:httpdisstartedservice:name:httpdstate:started

HostSelector

----name:installandstartapachehosts:webbecome:yesvars:http_port:80

tasks:-name:httpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:httpdisstartedservice:name:httpdstate:started

PrivilegeEscalation

----name:installandstartapachehosts:webbecome:yesvars:http_port:80

tasks:-name:httpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:httpdisstartedservice:name:httpdstate:started

PlayVariables

----name:installandstartapachehosts:webbecome:yesvars:http_port:80

tasks:-name:httpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:httpdisstartedservice:name:httpdstate:started

Tasks

----name:installandstartapachehosts:webbecome:yesvars:http_port:80

tasks:-name:latesthttpdpackageispresentyum:name:httpdstate:latest

-name:latestindex.htmlfileispresentcopy:src:files/index.htmldest:/var/www/html/

-name:httpdisstartedservice:name:httpdstate:started

Lab#2:ASimplePlaybook

DoingMorewithPlaybooksHerearesomemoreessentialplaybookfeaturesthatyoucanapply:

TemplatesLoopsConditionalsTagsBlocks

TemplatesAnsibleembedsthe thatcanbeusedtodynamically:

SetandmodifyplayvariablesConditionallogicGeneratefilessuchasconfigurationsfromvariables

Jinja2templatingengine

LoopsLoopscandoonetaskonmultiplethings,suchascreatealotofusers,installalotofpackages,orrepeatapollingstepuntilacertainresultisreached.

-yum:name:"{{item}}"state:latestwith_items:-httpd-mod_wsgi

ConditionalsAnsiblesupportstheconditionalexecutionofataskbasedontherun-timeevaluationofvariable,fact,orprevioustaskresult.

-yum:name:httpdstate:latestwhen:ansible_os_family=="RedHat"

TagsTagsareusefultobeabletorunasubsetofaplaybookon-demand.

-yum:name:"{{item}}"state:latestwith_items:-httpd-mod_wsgitags:-packages

-template:src:templates/httpd.conf.j2dest:/etc/httpd/conf/httpd.conftags:-configuration

BlocksBlockscutdownonrepetitivetaskdirectives,allowforlogicalgroupingoftasksandeveninplayerrorhandling.

-block:-yum:name:"{{item}}"state:latestwith_items:-httpd-mod_wsgi

-template:src:templates/httpd.conf.j2dest:/etc/httpd/conf/httpd.confwhen:ansible_os_family=="RedHat"

RolesRolesareapackagesofcloselyrelatedAnsiblecontentthatcanbesharedmoreeasilythanplaysalone.

ImprovesreadabilityandmaintainabilityofcomplexplaysEasessharing,reuseandstandardizationofautomationprocessesEnablesAnsiblecontenttoexistindependentlyofplaybooks,projects--evenorganizationsProvidesfunctionalconveniencessuchasfilepathresolutionanddefaultvalues

ProjectwithEmbeddedRolesExample

site.ymlroles/common/files/templates/tasks/handlers/vars/defaults/meta/apache/files/templates/tasks/handlers/vars/defaults/meta/

ProjectwithEmbeddedRolesExample

#site.yml----hosts:webroles:-common-apache

AnsibleGalaxyhttp://galaxy.ansible.com

AnsibleGalaxyisahubforfinding,reusingandsharingAnsiblecontent.

Jump-startyourautomationprojectwithcontentcontributedandreviewedbytheAnsiblecommunity.

Lab#3:APlaybookUsingRoles

Lab#4:UsinganAnsibleGalaxyRole

NextStepsIt'seasytogetstartedansible.com/get-startedJointheAnsiblecommunityansible.com/communityWouldyouliketolearnalotmore?redhat.com/en/services/training/do407-automation-ansible