Introduction To Ansible - Cisco

Transcription

Introduction to AnsibleRadenko ČitakovićCisco Systems Engineer19.03.2019.

Why learnAnsible? 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Real-Time Remote Execution of Commandsansible -m shell -a “netstat -rn” datacenter-east1. Audit routes on allvirtual machinesVM-1VM-2 VM-982. Updates routesrequired for consistencyVM-99VM-100ansible -m shell -a “route add X.X.X.X” datacenter-east 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Change Control Workflow Orchestration2. Update load balancerpools to point to stageProductionVM-1VM-2 LB-1LB-2VM-B1. Deploy application changeto stage and verify 2018 Cisco and/or its affiliates. All rights reserved.Cisco PublicVM-AStage

How doesAnsible work? 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

How does Ansible work?1. Engineers deployAnsible playbookswritten in YAML to acontrol stationDB-1DB-2WEB-1WEB-2APP-2APP-1Ansible Control Station 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public2. Ansible copies modules typicallywritten in Python to remote hosts toexecute tasks

Inside the Ansible Control Station Linux host with a Python and theAnsible installedSupport transport to remote hosts Typically SSH but could use an APIAnsible Components Ansible configuration fileInventory filesAnsible modulesPlaybooks 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Ansible Configuration File Control operation of AnsibleDevNet cat ansible.cfgDefault configuration/etc/ansible/ansible.cfg# config file for ansible# override global certain global settingsOverride default settings ANSIBLE CONFIG ENVansible.cfg in current directory.ansible.cfg in home directorySee Ansible documentation for ntro configuration.html 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public[defaults]# default to inventory file of ./hostsinventory ./hosts# disable host checking to automatically add# hosts to known hostshost key checking False# set the roles path to the local directoryroles path ./

Ansible Authentication Basics Typically, Ansible uses SSH forauthentication and assumes keys arein placeSetting up and transferring SSH keysallows playbooks to be runautomaticallyUsing passwords is possible Network Devices often use passwords 2018 Cisco and/or its affiliates. All rights reserved.Cisco PublicDevNet ssh-keygenGenerating public/private rsa key pair.Enter file in which to save the key:Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /.ssh/id rsa.Your public key has been saved in /.ssh/id rsa.pub.DevNet ssh-copy-id root@10.10.20.20.Number of key(s) added:1Now try logging into the machine, with:"ssh 'root@10.10.20.20'"DevNet ssh root@10.10.20.20Last login: Fri Jul 28 13:33:46 2017 from 10.10.20.7(python2) [root@localhost sbx nxos]#Output edited for brevity and clarity

Ansible Inventory File Inventory file identifies hosts, and groups of hosts under management Hosts can be IP or FQDNGroups enclosed in []Can include host specific parameters as well Example: Instructing Ansible to use the active Python Interpreter when using PythonVirtual EnvironmentsDevNet cat enter-west[datacenter-east]198.18.134.49 ansible python interpreter "/usr/bin/env python”[datacenter-west]198.18.134.50 ansible python interpreter "/usr/bin/env python"Output edited for brevity and clarity 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Ansible CLI Tool OverviewToolDescriptionansibleExecutes modules against targeted hosts without creating playbooks.ansible-playbookRun playbooks against targeted hosts.ansible-vaultEncrypt sensitive data into an encrypted YAML file.ansible-pullReverses the normal “push” model and lets clients "pull" from acentralized server for execution.ansible-docsParses the docstrings of Ansible modules to see example syntax andthe parameters modules require.ansible-galaxyCreates or downloads roles from the Ansible community. 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Using Ansible CLI for ad-hoc Commands Quickly run a command against a setof hostsSpecify the module with –m moduleSpecfiy the username to use with–u user Default is to use local usernameSpecify the server or group to targetProvide module arguments with–a argument 2018 Cisco and/or its affiliates. All rights reserved.Cisco PublicDevNet ansible -m setup -u root servers10.10.20.20 SUCCESS {"ansible facts": {"ansible all ipv4 addresses": ["10.10.20.20","172.17.0.1"],"ansible all ipv6 addresses": ["fe80::250:56ff:febb:3a3f"],"ansible apparmor": {"status": "disabled"},"ansible architecture": "x86 64",.Output edited for brevity and clarity

YAML Overview

YAML Overview What is YAML? “YAML Ain’t Markup Language” YAML is a human readable data serialization language YAML files are easily parsed into software data structures YAML is a common basis for a number of domain specific languages Ansible Heat Saltstack cloud-init Many more! 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

YAML OverviewYAMLsequencesbecome PythonlistsYAMLmappingsbecome PythondictionariesMultiple YAMLdocumentsseparates by a--- 2018 Cisco and/or its affiliates. All rights reserved.Cisco PublicYAML usesspacing to nestdata structures

Ansible Playbooks

Ansible TermsToolDescriptionmoduleCode, typically written in Python, that will perform some action on a host.taskA single action that references a module to run along with any inputarguments and actionsplayMatching a set of tasks to a host or group of hostsplaybookA YAML file that includes one or more playroleA pre-built set of playbooks designed to perform some standardconfiguration in a repeatable fashion. A play could leverage a role ratherthan tasks.Example: yum - Manages packages with the yum package managerExample: A role to configure a web server would install Apache, configure thefirewall, and copy application files.http://docs.ansible.com/ansible/latest/list of all /playbooks.html 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Ansible Playbooks Written in YAMLOne or more plays that contain hostsand tasks Tasks have a name & module keys. Modules have parameters Variables referenced with {{name}} Ansible gathers “facts”Create your own by register-ing outputfrom another tax.html 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Ansible PlaybooksDevNet ansible-playbook -u root example1.yamlPLAY [Report Hostname and Operating System ***TASK [Gathering *******ok: [10.10.20.20]TASK [Get hostname from ********ok: [10.10.20.20] {"msg": "localhost"}PLAY [Report Network Details of *********TASK [Network routes ***********ok: [10.10.20.20] {"stdout lines": ["Kernel IP routing table","DestinationGatewayGenmaskFlagsMSS Window irtt Iface","0.0.0.010.10.20.2540.0.0.0UG0 00 ens160","10.10.20.00.0.0.0255.255.255.0U0 00 ens160","172.16.30.010.10.20.160255.255.255.0UG0 00 ens160",]PLAY 20: ok 7changed 1unreachable 0failed 0 2018 Cisco and/or its affiliates. All rights reserved.Cisco PublicOutput edited for brevity and clarity

Using Variable Files and Loops with Ansibleexample2 vars.yaml Include external variable files usingvars files: filename.yamlReference variables with{{name}}YAML supports lists and hashes (iekey/value)Loop to repeat actions withwith items: variable 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Using Variable Files and Loops with AnsibleDevNet ansible-playbook -u root example2.yamlPLAY [Illustrate Variables] **************************TASK [Print Company Name from Variable] **************ok: [10.10.20.20] {"msg": "Hello DevNet"}TASK [Loop over a List] ******************************ok: [10.10.20.20] (item DevNet Rocks!) {"item": "DevNet Rocks!","msg": "DevNet Rocks!"}ok: [10.10.20.20] (item Programmability is amazing) {"item": "Programmability is amazing","msg": "Programmability is amazing"}ok: [10.10.20.20] (item Ansible is easy to use) {"item": "Ansible is easy to use","msg": "Ansible is easy to use"}ok: [10.10.20.20] (item Lists are fun!) {"item": "Lists are fun!","msg": "Lists are fun!"} 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Jinja2 Templating – Variables to the Max!example3.j2 Not just for Ansible templates Powerful templating language Loops, conditionals and moresupportedLeverage template module Attributes src: The template filedest: Where to save atest/playbooks templating.html 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Jinja2 Templating – Variables to the Max!DevNet ansible-playbook -u root example3.yamlPLAY [Generate Configuration from Template] ********************************TASK [Generate config] ***changed: [localhost]PLAY RECAP ***************localhost: ok 1changed 1unreachable 0failed 0DevNet cat example3.conffeature bgprouter bgp 65001router-id 10.10.10.1 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Host and Group Variables Ansible allows for Group and Hostspecific variables group vars/groupname.yamlhost vars/host.yamlVariables automatically available 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public group vars all.yaml switches.yamlhost vars 172.16.30.101.yaml 172.16.30.102.yaml 172.16.30.103.yaml 172.16.30.104.yaml

Using Ansible Rolesrolesdeclares anyplaybooksdefined withina role must beexecutedagainst hosts 2018 Cisco and/or its affiliates. All rights reserved.Roles promoteplaybook reuseRoles contain playbooks,templates, and variablesto complete a workflow(e.g. installing Apache)Cisco Public

Learning More About Ansible Ansible has an extensive module library capable of operating compute, storage andnetworking devices http://docs.ansible.com/ansible/modules by category.html Ansible’s domain specific language is powerful Loops Conditionals Many more! http://docs.ansible.com/ansible/playbooks.html Ansible galaxy contains community supported roles for re-use https://galaxy.ansible.com/ 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Wrap-Up 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

What you learned in this session Ansible use cases Setting up Ansible infrastructure Using the Ansible ad-hoc CLI Creating and running Ansible playbooks 2018 Cisco and/or its affiliates. All rights reserved.Cisco Public

Inventory file identifies hosts, and groups of hosts under management Hosts can be IP or FQDN Groups enclosed in [] Can include host specific parameters as well Example: Instructing Ansible to use the active Python Interpreter when using Python Virtual Environments DevNet cat hosts [dcloud-servers:children] datacenter-east .