ansible hands-on introduction - wordpress.com · 2018-04-20 · ansible hands-on introduction jon...
TRANSCRIPT
WhatisAnsible?It'sasimpleautomationlanguagethatcanperfectlydescribeanITapplicationinfrastructureinAnsiblePlaybooks.
It'sanautomationenginethatrunsAnsiblePlaybooks.
AnsibleTowerisanenterpriseframeworkforcontrolling,securingandmanagingyourAnsibleautomationwithaUIandRESTfulAPI.
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
ModulesModulesarebitsofcodetransferredtothetargetsystemandexecutedtosatisfythetaskdeclaration.Ansibleshipswithseveralhundredtoday!
apt/yumcopyfileget_urlgitpingdebugservicesynchronizetemplate
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
[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"},
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
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/
AnsibleGalaxyhttp://galaxy.ansible.com
AnsibleGalaxyisahubforfinding,reusingandsharingAnsiblecontent.
Jump-startyourautomationprojectwithcontentcontributedandreviewedbytheAnsiblecommunity.