Example: air traffic controller

Ansible Best Practices - GitHub

CONFIDENTIAL Designator1 How to write, how to execute, and how to use in real lifeAnsible best Practices2 GENERAL TIPS TO USE ANSIBLEHow to useTreat your Ansible content like codeAUTOMATION IS CODE3 Version control your Ansible content Iterate Start with a basic playbook and static inventory Refactor and modularize laterDo it with styleCODE NEEDS TO HAVE STYLE GUIDELINES4 Create a style guide for consistency: Tagging Whitespace Naming of Tasks, Plays, Variables, and Roles Directory Layouts Enforce the style Nice example: openshift- Ansible Style Guideexample: MUST BE ORGANIZEDUSE GIT! # master playbook, calling # playbook for webserver # separate playbook for single-shot tasksinventories/ production/ # different stages via inventory hosts # inventory file for production servers group_vars/ host_vars/ london/ # additional, alternative grouping if usefulroles/ # includes roles from some other place commo

CODE NEEDS TO HAVE STYLE GUIDELINES 4 Create a style guide for consistency: Tagging ... monitoring if there is a serious problem. LOGS, ANYONE? Send all logs from Tower to central logging CONNECT TOWER TO CENTRAL LOGGING 64 Splunk, Loggly, ELK, REST Send results from Ansible runs - but also from Tower changes. ALWAYS KEEP THE LIGHTS ON.

Tags:

  Guidelines, Practices, Best, Monitoring, Lesbians, Ansible best practices

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Ansible Best Practices - GitHub

1 CONFIDENTIAL Designator1 How to write, how to execute, and how to use in real lifeAnsible best Practices2 GENERAL TIPS TO USE ANSIBLEHow to useTreat your Ansible content like codeAUTOMATION IS CODE3 Version control your Ansible content Iterate Start with a basic playbook and static inventory Refactor and modularize laterDo it with styleCODE NEEDS TO HAVE STYLE GUIDELINES4 Create a style guide for consistency: Tagging Whitespace Naming of Tasks, Plays, Variables, and Roles Directory Layouts Enforce the style Nice example: openshift- Ansible Style Guideexample: MUST BE ORGANIZEDUSE GIT! # master playbook, calling # playbook for webserver # separate playbook for single-shot tasksinventories/ production/ # different stages via inventory hosts # inventory file for production servers group_vars/ host_vars/ london/ # additional, alternative grouping if usefulroles/ # includes roles from some other place common/ # base line, company wide configuration webtier/Do it with styleStart with one Git repository - but when it grows, use multiple!

2 GIT - ONE OR MANY?7At the beginning: put everything in one Git repositoryIn the long term: One Git repository per role Dedicated repositories for completely separated teams / tasksNew to git? Get your cheat sheet here: , WHAT DOWE HAVE?Give inventory nodes human-meaningful names rather than IPs or DNS READABLE INVENTORY ansible_host= ansible_host= ansible_host= ansible_host= ansible_host= ansible_host= ansible_host= ansible_host= hosts for easier inventory selection and less conditional tasks -- the more the ADVANTAGE OF GROUPING10[db]db[1:4][web]web[1:4][dev]d b1web1[testing]db3web3[prod]db2web2db4we b4[east]db1web1db3web3[west]db2web2db4we b4 Use dynamic sources where possible.

3 Either as a single source of truth - or let Ansible unify multiple ALL INVENTORY SOURCES11 Stay in sync automatically Reduce human error No lag when changes occur Let others manage the inventoryVARIABLESJUST WORDS, RIGHT?Proper variable names can make plays more readable and avoid variable name conflictsDESCRIBE VARIABLES WITH THEIR NAMES13a: 25data: abdata2: abcid: 123apache_max_keepalive: 25apache_port: 80tomcat_port: 8080 Avoid collisions and confusion by adding the role name to a variable as a ROLE VARIABLES14apache_max_keepalive: 25apache_port: 80tomcat_port: 8080 Know where your variables arePLACE VARIABLES APPROPRIATELY15 Find the appropriate place for your variables based on what, where and when they are set or modified Separate logic (tasks) from variables and reduce repetitive patterns Do not use every possibility to store variables - settle to a defined scheme and as few places as possibleMAKE YOUR PLAYBOOK READABLENO!

4 USE NATIVE YAML SYNTAX17- name: install telegraf yum: name=telegraf-{{ telegraf_version }} state=present update_cache=yes enablerepo=telegraf notify: restart telegraf- name: start telegraf service: name=telegraf state=startedBetter, but noUSE FOLDING ONLY IF REALLY REQUIRED18- name: install telegraf yum: > name=telegraf-{{ telegraf_version }} state=present update_cache=yes enablerepo=telegraf notify: restart telegraf- name: start telegraf service: name=telegraf state=startedYes!USE KEY:VALUE PAIRS19- name: install telegraf yum: name: telegraf-{{ telegraf_version }} state: present update_cache: yes enablerepo: telegraf notify: restart telegraf- name: start telegraf service: name: telegraf state: startedExhibit ADO NOT OMIT THE TASK NAME20- hosts: web tasks: - yum: name: httpd state: latest - service: name: httpd state: started enabled: yesPLAY [web] **TASK [setup] **ok: [web1]TASK [yum] **ok: [web1]TASK [service] **ok: [web1]Exhibit BUSE TASK NAMES21- hosts: web name: installs and starts apache tasks: - name: install apache packages yum: name: httpd state: latest - name.

5 Starts apache service service: name: httpd state: started enabled: yesPLAY [install and starts apache] **TASK [setup] **ok: [web1]TASK [install apache packages] **ok: [web1]TASK [starts apache service] **ok: [web1]POWERFULBLOCKSB locks can help in organizing code, but also enable rollbacks or output data for critical BLOCK SYNTAX23- block: copy: src: dest: /etc/ service: name: critical state: restarted rescue: command: shutdown -h now24 EXECUTING THE Ansible COMMANDSHow to executePROPERLAUNCHINGA nsible provides multiple switches for command line interaction and ON EXECUTION26-vvvv--step--check--diff--sta rt-at-taskAnsible has switches to show you what will be doneANALYZE WHAT YOUR ARE RUNNING27 Use the power of included options:--list-tasks--list-tags--list-ho sts--syntax-checkIf there is a need to launch something without an inventory - just do it!

6 QUICKLY LAUNCH WITHOUT INVENTORY28 For single tasks - note the comma: Ansible all -i , -m service -a "name=redhat state=present" For playbooks - again, note the comma: Ansible -playbook -i , RIGHT TOOLSDon t just start services -- use smoke testsCHECK IMMEDIATELY WHAT WAS DONE30- name: check for proper response uri: url: http://localhost/myapp return_content: yes register: result until: '"Hello World" in ' retries: 10 delay: 1 Try to avoid the command module - always seek out a module firstUSE NATIVE MODULES WHERE POSSIBLE31- name: add user command: useradd appuser- name: install apache command: yum install httpd- name: start apache shell: | service httpd start && chkconfig httpd on - name: add user user: name: appuser state: present - name: install apache yum: name: httpd state: latest - name: start apache service: name: httpd state: started enabled.

7 YesIf managed files are not marked, they might be overwritten accidentallyMARK MANAGED FILES32 Label template output files as being generated by Ansible Use the ansible_managed** variable with the comment filter{{ ansible_managed | comment }}ROLES AND GALAXIESR oles enable you to encapsulate your ROLES WHERE POSSIBLE34 Like playbooks -- keep roles purpose and function focused Store roles each in a dedicated Git repository Include roles via file, import via Ansible -galaxy tool Limit role dependenciesGet roles from Galaxy, but be careful and adopt them to your needsUSE GALAXY - WITH CARE35 Galaxy provides thousands of roles Quality varies drastically Take them with a grain of salt Pick trusted or well known authorsACCESS RIGHTSRoot access is harder to track than sudo - use sudo wherever possibleUSE BECOME, DON T BE A ROOT37 Ansible can be run as root only But login and security reasons often request non-root access Use become method - so Ansible scripts are executed via sudo (sudo is easy to track) best : create an Ansible only user Don t try to limit sudo rights to certain commands - Ansible does not work that way!

8 DEBUG YOUR PROBLEMC heck logging on target machineHAVE A LOOK AT THE NODE LEVEL39ansible-node sshd[2395]: pam_unix(sshd:session): session opened for user liquidat by (uid=0) Ansible -node Ansible -yum[2399]: Invoked with name=['httpd'] list=None install_repoquery=True conf_file=None disable_gpg_check=False state=absent disablerepo=None update_cache=False enablerepo=None exclude=NoneHow to keep the code executed on the target machineIN WORST CASE, DEBUG ACTUAL CODE40 Look into the logging of your target machine $ ANSIBLE_KEEP_REMOTE_FILES=1 Ansible target-node -m yum -a "name=httpd state=absent"Execute with: $ /bin/sh -c 'sudo -u $SUDO_USER /bin/sh -c "/usr/bin/python /home/liquidat/.

9 Ansible /tmp/.."Debugging tasks can clutter the output, apply some housekeepingUSE THE DEBUG MODULE41- name: Output debug message debug: msg: "This always displays"- name: Output debug message debug: msg: "This only displays with Ansible -playbook -vv+" verbosity: 242 GET TOWER TO ADOPT Ansible IN YOUR DATA CENTERHow to use in real lifeSimple: Use FUNCTIONS43 Tower was developed with Ansible in mind Extends the limits of Ansible to meet enterprise needs:Scalability, API, RBAC, aduits, has inbuilt helpTOWER FUNCTIONS44 Tower provides in-program help via questionmark bubbles Can include examples or links to further docsBRANCHES, ANYONE?Tower can import a repository multiple times with different branchesTAKE ADVANTAGE OF GIT BRANCHES46 Use feature or staging branches in your Git Import them all separately, address them separately Useful for testing of new features but also to move changes through stagesMANY, MANY ROLEST ower automatically imports Roles during Project updateTOWER & ROLES48 Do not copy roles into your playbook repository, just create a Tower will automatically import the roles during Project installation Mix roles from various sources Fix version in to have auditable environment!

10 WHAT ARE WE TALKING TO?Use dynamic & smart inventoriesTOWER FUNCTIONS50 Combine multiple inventory types Let Tower take care of syncing and caching Use smart inventories to group nodesQUICK TIPTry right clicking on the icon and using Replace Image to insert your own GOOD JOBST ower job templates provide multiple options - use them wiselyUSE THE POWER OF JOB TEMPLATES52 Keep jobs simple, focussed - as playbooks or roles Add labels to them to better filter For idempotent jobs, create check templates as well - and let them run over night Combine with notifications - and get feedback when a check failed1+1+1 = 1 Multiple playbooks can be combined into one workflowUSE WORKFLOWS FOR COMPLEX TASKS54 Simple jobs, complex workflows React to problems via workflow Combine playbooks of different teams, different repositories Re-sync inventories during the playDO ASK PROPER QUESTIONSUse surveys to get variable valuesTOWER FUNCTIONS56 Use good, meaningful variable names Provide a default choice Multiple choice > free text If answer not required - do you really need it at all?


Related search queries