Ansible Windows Workshop

Transcription

Ansible Windows WorkshopIntroduction to Ansible Automation for Windows

Housekeeping Timing Breaks Takeaways

What you will learn Introduction to Ansible automationHow Ansible works for Windows automationUnderstanding Ansible modules and playbooksUsing Ansible Tower to scale automation to the enterpriseReusing automation with Ansible Roles

Ansible Windows Automation WorkshopIntroductionTopics Covered: Why Automate? How Ansible Windows Automation works Understanding Inventory An example Ansible Playbook4

Automation happens when one person meets aproblem they never want to solve again

Teams are automating.Lines Of ructure

Ad-hoc Automation is happening in silosAnsible used in siloDevelopersDIY scripting automationSecurityOpen source configmanagement toolInfrastructureProprietary vendor suppliedautomationNetworkIs organicautomation enough?

Why Ansible?SimplePowerfulAgentlessHuman readable automationApp deploymentAgentless architectureNo special coding skills neededConfiguration managementUses OpenSSH & WinRMTasks executed in orderWorkflow orchestrationNo agents to exploit or updateUsable by every teamNetwork automationGet started immediatelyGet productive quicklyOrchestrate the app lifecycleMore efficient & more secure

What can I do using Ansible?Automate the deployment and management of your entire IT footprint.Do onDeploymentProvisioningContinuousDeliverySecurity andComplianceOn these.FirewallsLoad tructureStorageNetwork DevicesAnd more.

When automation crosses teams,you need an automation platformNetworkDevelopersLines Of BusinessInfrastructureSecurityOperations

Red Hat Ansible Automation PlatformNetworkLines sible Hosted Services: Engage users with an automation focused experienceScaleAnsible Tower: Operate & control at scaleCreateAnsible Engine: Universal language of automationFueled by an open source communityDevelopers

Red Hat Ansible Towerby the numbers:94%Reduction in recovery time followinga security incident84%Savings by deploying workloadsto generic systems appliancesusing Ansible Tower67%Reduction in man hours requiredfor customer deliveriesFinancial summary:146%ROI on Ansible Tower 3 MONTHSPayback on Ansible TowerSOURCE: "The Total Economic Impact Of Red Hat Ansible Tower, a June 2018 commissioned study conducted by Forrester Consulting on behalf of Red sible-tower-20180710

WINDOWS AUTOMATION90 1,300 WindowsModulesPowershell DSCresourcesansible.com/windows

WHAT CAN I DO USING ANSIBLE FOR WINDOWSNative Windows support uses PowerShell remoting to manage Windows inthe same Ansible agentless way Install and uninstall MSIs Gather facts on Windows hosts Enable and disable Windows features Start, stop, and manage Windows Services Create and Manage local users and groups Manage Windows packages via Chocolatey packagemanager Manage and install Windows updates Fetch files from remote sites Push and execute any Powershell scripts

Ansible automates technologies you useTime to automate is measured in minutes, 50 certified platformsCloudVirt & igital OceanGoogleOpenStackRackspace moreDockerKubernetesOpenStackOpenShiftVMware igsUsersDomainsUpdates erakiOpenvSwitchRuckusVyOS o AltoSnort moreDynatraceDatadogLogicMonitorNew RelicSensu moreRed HatProductsRHELSatelliteInsights moreStorageInfinidatNetappPure Storage moreDevopsJiraGitHubVagrantJenkinsSlack more

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBANSIBLE AUTOMATION NSHOSTSNETWORKDEVICES

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBANSIBLE AUTOMATION ENGINEUSERSANSIBLEPLAYBOOKPLAYBOOKS ARE WRITTEN IN YAMLTasks are executed sequentiallyInvoke Ansible ES

--- name: start IIS/stop firewallhosts: windows-webbecome: yestasks:- name: IIS is runningwin service:name: W3Svcstate: running- name: firewall service is stopped/disabledwin service:name: MpsSvcstate: stoppedstart mode: disabled

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBANSIBLE AUTOMATIONMODULESENGINEARE “TOOLS IN THE TOOLKIT”Python, Powershell, or any languageExtend Ansible simplicity to the entire K- name: Start the SNMP servicewin service:name: SNMPstate: startedHOSTSNETWORKDEVICES

ModulesModules do the actual work in Ansible, they are whatgets executed in each playbook task. Written in Powershell Modules can be idempotent Modules take user input in the form of parameterstasks:- name: start IISwin service:name: W3Svcstate: running

Windows modulesAnsible modules for Windows automation typically begin with win *win copy - Copies files to remote locations on windows hostswin service - Manage and query Windows serviceswin domain - Ensures the existence of a Windows domainwin reboot - Reboot a windows machinewin regedit - win regedit – Add, change, or remove registry keys and valueswin ping - A windows version of the classic ping modulewin dsc - Invokes a PowerShell DSC configurationwin acl - Set file/directory/registry permissions for a system user or group

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBPLUGINS ARE “GEARS IN THE ENGINE”Code that plugs into the core engineANSIBLE AUTOMATION ENGINEAdaptability for various uses & UGINSHOSTSNETWORKDEVICES{{ some variable to nice yaml }}

PUBLIC / er2.example.comPUBLIC / PRIVATECLOUDINVENTORYList of systems in your infrastructure thatautomation is executed againstANSIBLE AUTOMATION ES

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBANSIBLE AUTOMATION ENGINEUSERSCLOUDRed Hat Openstack, Red Hat Satellite, VMware,INVENTORYCLIEngine, AzureAWS EC2, Rackspace,Google VICES

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBANSIBLE AUTOMATION iceNow, Cobbler, BMC,Custom cmdbHOSTSCLIPLUGINSNETWORKDEVICES

PUBLIC / PRIVATECLOUDPUBLIC / PRIVATECLOUDCMDBANSIBLE AUTOMATION ENGINEUSERSINVENTORYCLIMODULESPLUGINSAUTOMATE EVERYTHINGANSIBLERed Hat Enterprise Linux, Cisco routers, AristaPLAYBOOKswitches, Juniper routers, Windows hosts, CheckPoint firewalls, NetApp storage, F5 load balancersand moreHOSTSNETWORKDEVICES

Ansible Windows Automation WorkshopTower IntroductionTopics Covered: What is Ansible Tower? Job Templates Inventory Credentials Projects27

What is Ansible Tower?Ansible Tower is a UI and RESTful API allowing youto scale IT automation, manage complexdeployments and speed productivity. Role-based access control Deploy entire applications withpush-button deployment access All automations are centrally logged Powerful workflows match your IT processes

Red Hat Ansible Automation PlatformNetworkLines Ansible SaaS: Engage users with an automation focused experienceEngageScaleSecurityControlWeb UI and APIDelegationRole Based Access ControlsAnsible Engine: Universal language of automationFueled by an open source communityScaleScalable Execution Capacity

Red Hat Ansible TowerPush buttonRESTful APIRBACAn intuitive user interface experiencemakes it easy for novice users toexecute playbooks you allow themaccess to.With an API first mentality everyfeature and function of Tower can beAPI driven. Allow seamless integrationwith other tools like ServiceNow andInfoblox.Allow restricting playbook access toauthorized users. One team can useplaybooks in check mode (read-only)while others have full administrativeabilities.Enterprise integrationsCentralized loggingWorkflowsIntegrate with enterprise authenticationlike TACACS , RADIUS, Azure AD.Setup token authentication with OAuth2. Setup notifications with PagerDuty,Slack and Twilio.All automation activity is securelylogged. Who ran it, how theycustomized it, what it did, where ithappened - all securely stored andviewable later, or exported throughAnsible Tower’s API.Ansible Tower’s multi-playbookworkflows chain any number ofplaybooks, regardless of whether theyuse different inventories, run asdifferent users, run at once or utilizedifferent credentials.

Red Hat Ansible Automation Platform .ADMINSANSIBLE CLI & CI SYSTEMSANSIBLE PLAYBOOKSANSIBLETOWERROLE-BASEDACCESS CONTROLKNOWLEDGE& VISIBILITYCLOUD.REDHAT.COMSCHEDULED &CENTRALIZED JOBSSIMPLE USER INTERFACETOWER APIUSERSANSIBLEENGINEOPEN SOURCE MODULE LIBRARYPLUGINSAUTOMATIONHUBCERTIFIED COLLECTIONSAUTOMATIONANALYTICSPERFORMANCE DASHBOARDPARTNER COLLECTIONSORGANIZATIONAL STATSPYTHON ANCESSH, WINRM, NETWORK CLI, SECURITYCLOUDSERVICESAPP S,CONTAINERS ARISTA,CISCO,JUNIPERINFOBLOXF5 CHECKPOINT,QRADAR,SNORTCYBERARK,SPLUNK,FORTINET AWS,GOOGLE CLOUD,AZURE,IBM CLOUD DATABASES,LOGGING,SOURCE CONTROLMANAGEMENT PYTHON ITY &COMPLIANCEORCHESTRATION

Job TemplatesEverything in Ansible Tower revolves around theconcept of a Job Template. Job Templatesallow Ansible Playbooks to be controlled,delegated and scaled for an organization.Job templates also encourage the reuse ofAnsible Playbook content and collaborationbetween teams.A Job Template requires: An Inventory to run the job against A Credential to login to devices. A Project which contains AnsiblePlaybooks

InventoryInventory is a collection of hosts (nodes) withassociated data and groupings that AnsibleTower can connect to and manage. Hosts (nodes)GroupsInventory-specific data (variables)Static or dynamic sources

CredentialsCredentials are utilized by Ansible Tower forauthentication with various external resources: Connecting to remote machines to runjobs Syncing with inventory sources Importing project content from versioncontrol systems Connecting to and managing networkdevicesCentralized management of variouscredentials allows end users to leverage asecret without ever exposing that secret tothem.

ProjectA project is a logical collection of AnsiblePlaybooks, represented in Ansible Tower.You can manage Ansible Playbooks andplaybook directories by placing them in asource code management systemsupported by Ansible Tower, including Git,Subversion, and Mercurial.

Ansible Windows Automation WorkshopExercise 1 Configuring Ansible Tower36

Ansible Windows Automation WorkshopAd-hoc CommandsTopics Covered: What are ad-hoc commands Common options Run from Command line Ansible Tower37

Ad-hoc CommandsAn ad-hoc command is a single Ansible task to performquickly, but don’t want to save for later.

Ad-hoc Commands: Common Options -m MODULE NAME, --module-name MODULE NAMEModule name to execute the ad-hoc command-a MODULE ARGS, --args MODULE ARGSModule arguments for the ad-hoc command-b, --becomeRun ad-hoc command with elevated rights such as sudo, the default method-e EXTRA VARS, --extra-vars EXTRA VARSSet additional variables as key value or YAML/JSON--versionDisplay the version of Ansible--helpDisplay the MAN page for the Ansible tool

Ad-hoc Commands# check all my inventory hosts are ready to be# managed by Ansible ansible all -m ping# collect and display the discovered facts# for the localhost ansible localhost -m setup# run the uptime command on all hosts in the# web group ansible web -m command -a "uptime"

Ad-hoc Commands from Tower

Ansible Windows Automation WorkshopExercise 2 Ad-hoc Commands42

Ansible Windows Automation WorkshopPlaybooksTopics Covered: Variables Facts PrecedenceTasks 43Handlers

VariablesAnsible can work with metadata from various sources andmanage their context in the form of variables. Command line parameters Plays and tasks Files Inventory Discovered facts Roles

Discovered factsFacts are bits of information derived from examining a hostsystems that are stored as variables for later use in a play. ansible localhost -m setuplocalhost 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"},

Variable PrecedenceThe order in which the same variable from different sourceswill override each other.1.command line values (eg “-u user”)12.play vars2.role defaults [1]13.play vars prompt3.inventory file or script group vars [2]14.play vars files4.inventory group vars/all [3]15.role vars (defined in role/vars/main.yml)5.playbook group vars/all [3]16.block vars (only for tasks in block)6.inventory group vars/* [3]17.task vars (only for the task)7.playbook group vars/* [3]18.include vars8.inventory file or script host vars [2]19.set facts / registered vars9.inventory host vars/* [3]20.role (and include role) params10.11.playbook host vars/* [3]21.include paramshost facts / cached set facts [4]22.extra vars (always win precedence)

TasksTasks are the application of a module to perform a specific unit ofwork. win file: A directory should existwin package: A package should be installedwin service: A service should be runningwin template: Render a configuration file from a templatewin get url: Fetch an archive file from a URLwin copy: Copy a file from your repository or a remote source

Taskstasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Restart IISwin service:name: IIS Admin Servicestate: restarted

Handler TasksHandlers are special tasks that run at the end of a play if notifiedby another task when a change occurs.If a package gets installed or updated, notify a service restarttask that it needs to run.

Handler Taskstasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: presentnotify: Restart IIS- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\handlers:- name: Restart IISwin service:name: IIS Admin Servicestate: restarted

Plays and playbooksPlays are ordered sets of tasks to execute against host selectionsfrom your inventory. A playbook is a file containing one or moreplays.

Plays and playbooks--- name: Ensure IIS is installed and startedhosts: webbecome: yesvars:service name: IIS Admin Servicetasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Ensure IIS is startedwin service:name: "{{ service name }}"state: started

Meaningful names--- name: Ensure IIS is installed and startedhosts: webbecome: yesvars:service name: IIS Admin Servicetasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Ensure IIS is startedwin service:name: "{{ service name }}"state: started

Host selector--- name: Ensure IIS is installed and startedhosts: webbecome: yesvars:service name: IIS Admin Servicetasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Ensure IIS is startedwin service:name: "{{ service name }}"state: started

Privilege escalation--- name: Ensure IIS is installed and startedhosts: webbecome: yesvars:service name: IIS Admin Servicetasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Ensure IIS is startedwin service:name: "{{ service name }}"state: started

Plays variables--- name: Ensure IIS is installed and startedhosts: webbecome: yesvars:service name: IIS Admin Servicetasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Ensure IIS is startedwin service:name: "{{ service name }}"state: started

Tasks--- name: Ensure IIS is installed and startedhosts: webbecome: yesvars:service name: IIS Admin Servicetasks:- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: present- name: Ensure latest index.html file is presentwin copy:src: files/index.htmldest: c:\www\- name: Ensure IIS is startedwin service:name: "{{ service name }}"state: started

Ansible Windows Automation WorkshopExercise 3 & 4 Your First Playbook58

Ansible Windows Automation WorkshopAdvanced playbooksTopics Covered:59 Templates Loops Conditionals Tags Blocks

Doing more with playbooksHere are some more essential playbook features that you canapply: TemplatesLoopsConditionalsTagsBlocks

Doing more with playbooks: TemplatesAnsible embeds the Jinja2 templating engine that can be used todynamically: Set and modify play variables Conditional logic Generate files such as configurations from variables

Doing more with playbooks: LoopsLoops can do one task on multiple things, such as create a lotof users, install a lot of packages, or repeat a polling step untila certain result is reached.- name: Ensure IIS Server is presentwin feature:name: "{{ item }}"state: presentloop:- Web-Server- NET-Framework-Core

Doing more with playbooks: ConditionalsAnsible supports the conditional execution of a taskbased on the run-time evaluation of variable, fact, orprevious task result.- name: Ensure IIS Server is presentwin feature:name: Web-Serverstate: presentwhen: ansible os family "Windows"

Doing more with playbooks: TagsTags are useful to be able to run a subset of a playbookon-demand.- name: Ensure IIS Server is presentwin feature:name: "{{ item }}"state: presentwith items:- Web-Server- NET-Framework-Coretags:- packages- name: Copy web.config template to Serverwin template:src: templates/web.config.j2dest: C:\inetpub\wwwroot\web.configtags:- configuration

Doing more with playbooks: BlocksBlocks cut down on repetitive task directives, allow for logicalgrouping of tasks and even in play error handling.- block:- name: Ensure IIS Server is presentwin feature:name: "{{ item }}"state: presentwith items:- Web-Server- name: Copy web.config template to Serverwin template:src: templates/web.config.j2dest: C:\inetpub\wwwroot\web.configwhen: ansible os family "Windows"

Ansible Windows Automation WorkshopExercise 5 Practical Playbook Development66

Ansible Windows Automation WorkshopSharing automationTopics Covered:67 Roles Galaxy

RolesRoles are a packages of closely related Ansible content that canbe shared more easily than plays alone. Improves readability and maintainability of complex plays Eases sharing, reuse and standardization of automationprocesses Enables Ansible content to exist independently ofplaybooks, projects -- even organizations Provides functional conveniences such as file pathresolution and default values

RolesProject with Embedded Roles handlers

cmdb users hosts network devices cli ansible playbook public / private public / private cloud cloud modules plugins inventory inventory list of systems in your infrastructure that . open source module library plugins python codebase app development python venv,