Ansible-cheatsheet 2n41q

  • ed by: Don CoachDon High
  • 0
  • 0
  • May 2020
  • PDF

This document was ed by and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this report form. Report 2z6p3t


Overview 5o1f4z

& View Ansible-cheatsheet as PDF for free.

More details 6z3438

  • Words: 5,156
  • Pages: 21
# Comments: {# ... #} # Built-in Filtres in J2 template(s):

'{{ '{{ '{{ '{{ '{{ '{{ '{{ '{{

VARIABLE_NAME | capitalize }}' output | to_json }} output | to_yaml }} output | to_nice_json }} output | to_nice_yaml }} output | from_json }} output | from_yaml }} forest_blockers|split('-') }}'

# Conditionals: { % ... % } a/ Equal to example A {% if ansible_eth0.active == True %}

eth0 address {{ ansible_eth0.ipv4.address }}.

{% endif %} b/ Equal to example B {% if ansible_eth0.active is equalto True %}

eth0 address {{ ansible_eth0.ipv4.address }}.

{% endif %} # Cycles/loops: {% for address in ansible_all_ipv4_addresses %}
  • {{ address }}
  • {% endfor %} # Issues a/ When value after : starts with { you need to " the whole object app_path: "{{ base_path }}/bin" b/ When you have nested {{...}} elements, remove the inner set: msg: Host {{ params[{{ host_ip }}] }} <-wrong msg: Host {{ params[ host_ip] }} <-fine More information: http://jinja.pocoo.org/docs/dev/templates/#builtin-filters http://jinja.pocoo.org/docs/dev/templates/#builtin-tests ############################################################################### ## Roles # Structure: It looks for different roles at 'roles' subdirectory or 'roles_path' dir in ansible.cfg (default /etc/ansible/roles) Top-level = specifically named role name Subdirs = main.yml files = contains objects referenced by main.yml templates = contains objects referenced by main.yml !Role tasks execute before tasks of play in which they appear !To override default, use 'pre_tasks' (performed before any roles applied) and 'post_tasks' (performed after all roles completed) # Example - folder structure: $ tree .example .example/ ├── defaults │ └── main.yml ├── files ├── handlers │ └── main.yml ├── meta

    <-define default variables, easily overriden <-fixed-content files, empty subdir is ignored

    │ └── main.yml yes') ├── REE.md ├── tasks │ └── main.yml hosts where the role is applied ├── templates ├── tests │ ├── inventory │ └── test.yml └── vars │ └── main.yml └── main.yml # Use roles in play example: --- hosts: remote.example.com roles: - role1 - role2 - davidkarban.git

    <-define dependency roles ('allow_duplicates:

    <-role content (defines modules to call on managed <-contain templates

    <-vars for this module (best practice)

    <-role from Ansible Galaxy using _AUTHOR.NAME_

    # Override default variables example: --- hosts: remote.example.com roles: - { role: role1 } - { role: role2, var1: val1, var2: val2 } # Define dependency roles in meta/main.yml example: --dependencies: - { role: apache, port: 8080 } - { role: postgress, dbname: serverlist, _: felix } !Role added as dependency to play once, to override default, set 'allow_duplicates=yes' in meta/main.yml # Content example of MOTD role (tasks/main.yml) --# tasks file for MOTD - name: deliver motd file template: src: templates/motd.j2 dest: /etc/motd owner: root group: root mode: 0444 # Role sources $ cat roles2install.yml # From Galaxy: - src: author.rolename # From different source: - src: https://webserver.example.com/files.tgz name: ftpserver-role $ ansible-galaxy init -r roles2install.yml

    ############################################################################### ## Modules # Custom modules Priority in which the custom module is being processed: 1, ANSIBLE_LIBRARY environment variable 2, 'library' in the ansible.cfg 3, ./library/ relative to location of playbook in use # Default modules $ cd /usr/lib/python2.7/site-packages/ansible/modules $ ansible-doc -l <-list all modules $ ansible-doc <MODULE> <-help for the module $ ansible-doc -s <MODULE> <-simple view for the module ############################################################################### ## Optimizations (1) Default 'smart' settings (transport=smart in ansible.cfg): a/ check if locally installed SSH s 'ControlPersist', if not, 'paramiko' is used b/ ControlPersist=60s (listed as comment in /etc/ansible/ansible.cfg) (2) Other settings include: a/ paramiko (Python implementation of SSHv2, does not have ControlPersist) b/ local (runs locally and not over SSH) c/ ssh (uses OpenSSH) d/ docker (uses docker exec) e/ plug-ins (not based on SSH, e.g. chroot, libvirt_lxc...) (3) Change on-the-fly settings with a/ $ ansible-playbook -c b/ $ ansible -c (4) SSH settings are under [ssh_connection] (5) Paramiko settings are under [paramiko_connection] (6) To specify connection type in the inventory file, use 'ansible_connection': [targets] localgost ansible_connection=local demo.lab.example.com ansible_connection=ssh (7) To specify connection type in play: --- name: Connection type hosts: 127.0.0.01 connection: local (8) To limit concurrent connection, use SSH server's 'MaxStartups' option (9) Parallelism - by default 5 different machines at once: a/ setting 'forks' in 'ansible.cfg' b/ $ ansible-playbook --forks c/ 'serial' in the play overrides 'ansible.cfg' - either number or % d/ 'async' & 'async_status' - value is time that Ansible waits for command to complete [default 3600s, long tasks 0] e/ 'pool' - sets how often Ansible checks if command has completed [default 10s, long tasks 0] f/ 'wait_for' g/ pause module ############################################################################### ## Ansible vault (1a) Create encrypted file: $ ansible-vault create $ ansible-vault create --vault--file=.secret_file (2a) Enter and confirm new vault (1b) Or encrypt and existing file(s):

    $ ansible-vault encrypt ... $ ansible-vault encrypt --output=NEW_FILE (2b) Enter and confirm new vault (3) View file: $ ansible-vault view (4) Edit file: $ ansible-vault edit (5) Change : $ ansible-vault rekey $ ansible-vault rekey --new-vault--file=.secret_file (6) Decrypt file: $ ansible-vault decrypt --output= Variable types: a/ Defined in 'group_vars' or 'host_vars' b/ Loaded by 'include_vars' or 'vars_files' c/ ed on 'ansible-playbook -e @file.yml' d/ Defined as role variables & defaults $ ansible-playbook --ask-vault- $ ansible-playbook --vault--file=.secret_file or 'EXPORT ANSIBLE_VAULT__FILE=~/.secret_file' ############################################################################### ## Troubleshooting By default no log, but you can enable it: a/ 'log_path' parameter under [default] in 'ansible.cfg' b/ ANSIBLE_LOG_PATH environment variable # Debug mode examples: - debug: msg="The free memory for this system is {{ ansible_memfree_mb }}" - debug: var=output verbosity=2 # Report changes made to templated files: $ ansible-playbook --check --diff <MYAML.YML> # 'URI' module to check if RESTfuk API is returning required content: tasks: - action: uri url=http://api.myapp.com return_content=yes : apiresponse - fail: msg='version was not provided' when: "'version' not in apiresponse.content" # 'script' module to execute script on managed host (module fails if $? is other then 0): taks: - script: check_free_memory # 'stat' module to see if files/dirs not managed by Ansible are present 'assert' module to see if file exists in managed host tasks: - stat: path=/var/run/app.lock : lock - assert: that: - lock.stat.exists ############################################################################### ## Ansible Tower

    Web-based interface Enterprise solution for IT automation Dashboard for managing deployments and monitoring resources Adds automation, visual management, monitoring capabilities to Ansible Gives s control over access Uses SSH credentials Blocks access to or transfer of credentials Implements continuous delivery and configuration management Integrates management in single tool # Installation - Configuration file: tower_setup_conf.yml under setup bundle directory Installation - 'configure' options: -l <-install on local machine with internal PostgreSQL --no-secondary-prompt <-skip prompts regarding secondary Tower nodes to be added -A <-Disable aut-generation of PostgreSQL , prompt for s -o <-source for configuration answers Installation - after the config file is ready: ./setup.sh -c <-specify file that stores the configuration -i <-p <-specify file to use for host inventory -s <-require Ansible to prompt for SSH s -u <-require Ansible to prompt for sudo s -e <-set additional variables during installation -b <-perform database backup instead of installing Tower -r <-perform database restore instead of installing Tower Changing your : $ sudo tower-manage change # SSL certificate: /etc/tower/awx.cert /etc/tower/awx.key # REST API from CLI example: $ curl -s http://demo.lab.example.com/api/v1/ping | json_reformat # types: normal organization super # permissions: read write execute commands check run create # Projects: /var/lib/awx/projects $ sudo mkdir /var/lib/awx/projects/demoproject

    $ sudo demo.yml /var/lib/awx/projects/demoproject $ sudo chown -R awx /var/lib/awx/projects/demoproject ############################################################################### ## CLI: (1) Run a command somewhere else using Ansible $ ansible Usage: ansible [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS module arguments --ask-vault- ask for vault -B SECONDS, --background=SECONDS run asynchronously, failing after X seconds (default=N/A) -C, --check don't make any changes; instead, try to predict some of the changes that may occur -D, --diff when changing (small) files and templates, show the differences in those files; works great with --check -e EXTRA_VARS, --extra-vars=EXTRA_VARS set additional variables as key=value or YAML/JSON -f FORKS, --forks=FORKS specify number of parallel processes to use (default=5) -h, --help show this help message and exit -i INVENTORY, --inventory-file=INVENTORY specify inventory host path (default=/etc/ansible/hosts) or comma separated host list. -l SUBSET, --limit=SUBSET further limit selected hosts to an additional pattern --list-hosts outputs a list of matching hosts; does not execute anything else -m MODULE_NAME, --module-name=MODULE_NAME module name to execute (default=command) -M MODULE_PATH, --module-path=MODULE_PATH specify path(s) to module library (default=None) --new-vault--file=NEW_VAULT__FILE new vault file for rekey -o, --one-line condense output --output=OUTPUT_FILE output file name for encrypt or decrypt; use - for stdout -P POLL_INTERVAL, --poll=POLL_INTERVAL set the poll interval if using -B (default=15) --syntax-check perform a syntax check on the playbook, but do not execute it -t TREE, --tree=TREE log output to this directory --vault--file=VAULT__FILE vault file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit Connection Options: control as whom and how to connect to hosts -k, --ask- ask for connection --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE use this file to authenticate the connection

    -u REMOTE_, --=REMOTE_ connect as this (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart) -T TIMEOUT, --timeout=TIMEOUT override the connection timeout in seconds (default=10) --ssh-common-args=SSH_COMMON_ARGS specify common arguments to to sftp/s/ssh (e.g. ProxyCommand) --sftp-extra-args=SFTP_EXTRA_ARGS specify extra arguments to to sftp only (e.g. -f, -l) --s-extra-args=S_EXTRA_ARGS specify extra arguments to to s only (e.g. -l) --ssh-extra-args=SSH_EXTRA_ARGS specify extra arguments to to ssh only (e.g. -R) Privilege Escalation Options: control how and which you become as on target hosts -s, --sudo

    run operations with sudo (nowd) (deprecated, use become) -U SUDO_, --sudo-=SUDO_ desired sudo (default=root) (deprecated, use become) -S, --su run operations with su (deprecated, use become) -R SU_, --su-=SU_ run operations with su as this (default=root) (deprecated, use become) -b, --become run operations with become (does not imply prompting) --become-method=BECOME_METHOD privilege escalation method to use (default=sudo), valid choices: [ sudo | su | pbrun | pfexec | runas | doas | dzdo ] --become-=BECOME_ run operations as this (default=root) --ask-sudo- ask for sudo (deprecated, use become) --ask-su- ask for su (deprecated, use become) -K, --ask-become- ask for privilege escalation ############################################################################### (2) Run Ansible playbook $ ansible-playbook Usage: ansible-playbook playbook.yml Options: --ask-vault- ask for vault -C, --check don't make any changes; instead, try to predict some of the changes that may occur -D, --diff when changing (small) files and templates, show the differences in those files; works great with --check -e EXTRA_VARS, --extra-vars=EXTRA_VARS set additional variables as key=value or YAML/JSON --flush-cache clear the fact cache --force-handlers run handlers even if a task fails -f FORKS, --forks=FORKS

    specify number of parallel processes to use (default=5) -h, --help show this help message and exit -i INVENTORY, --inventory-file=INVENTORY specify inventory host path (default=/etc/ansible/hosts) or comma separated host list. -l SUBSET, --limit=SUBSET further limit selected hosts to an additional pattern --list-hosts outputs a list of matching hosts; does not execute anything else --list-tags list all available tags --list-tasks list all tasks that would be executed -M MODULE_PATH, --module-path=MODULE_PATH specify path(s) to module library (default=None) --new-vault--file=NEW_VAULT__FILE new vault file for rekey --output=OUTPUT_FILE output file name for encrypt or decrypt; use - for stdout --skip-tags=SKIP_TAGS only run plays and tasks whose tags do not match these values --start-at-task=START_AT_TASK start the playbook at the task matching this name --step one-step-at-a-time: confirm each task before running --syntax-check perform a syntax check on the playbook, but do not execute it -t TAGS, --tags=TAGS only run plays and tasks tagged with these values --vault--file=VAULT__FILE vault file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit Connection Options: control as whom and how to connect to hosts -k, --ask- ask for connection --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE use this file to authenticate the connection -u REMOTE_, --=REMOTE_ connect as this (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart) -T TIMEOUT, --timeout=TIMEOUT override the connection timeout in seconds (default=10) --ssh-common-args=SSH_COMMON_ARGS specify common arguments to to sftp/s/ssh (e.g. ProxyCommand) --sftp-extra-args=SFTP_EXTRA_ARGS specify extra arguments to to sftp only (e.g. -f, -l) --s-extra-args=S_EXTRA_ARGS specify extra arguments to to s only (e.g. -l) --ssh-extra-args=SSH_EXTRA_ARGS specify extra arguments to to ssh only (e.g. -R) Privilege Escalation Options:

    control how and which you become as on target hosts -s, --sudo

    run operations with sudo (nowd) (deprecated, use become) -U SUDO_, --sudo-=SUDO_ desired sudo (default=root) (deprecated, use become) -S, --su run operations with su (deprecated, use become) -R SU_, --su-=SU_ run operations with su as this (default=root) (deprecated, use become) -b, --become run operations with become (does not imply prompting) --become-method=BECOME_METHOD privilege escalation method to use (default=sudo), valid choices: [ sudo | su | pbrun | pfexec | runas | doas | dzdo ] --become-=BECOME_ run operations as this (default=root) --ask-sudo- ask for sudo (deprecated, use become) --ask-su- ask for su (deprecated, use become) -K, --ask-become- ask for privilege escalation ############################################################################### (3) Set up a remote copy of ansible on each managed node (clone Ansible configuration files from Git repository) $ ansible-pull Usage: ansible-pull -U [options] Options: --accept-host-key adds the hostkey for the repo url if not already added --ask-vault- ask for vault -C CHECKOUT, --checkout=CHECKOUT branch/tag/commit to checkout. Defaults to behavior of repository module. -d DEST, --directory=DEST directory to checkout repository to -e EXTRA_VARS, --extra-vars=EXTRA_VARS set additional variables as key=value or YAML/JSON -f, --force run the playbook even if the repository could not be updated --full Do a full clone, instead of a shallow one. -h, --help show this help message and exit -i INVENTORY, --inventory-file=INVENTORY specify inventory host path (default=/etc/ansible/hosts) or comma separated host list. -l SUBSET, --limit=SUBSET further limit selected hosts to an additional pattern --list-hosts outputs a list of matching hosts; does not execute anything else -m MODULE_NAME, --module-name=MODULE_NAME Repository module name, which ansible will use to check out the repo. Default is git. -M MODULE_PATH, --module-path=MODULE_PATH specify path(s) to module library (default=None) --new-vault--file=NEW_VAULT__FILE

    -o, --only-if-changed --output=OUTPUT_FILE --purge --skip-tags=SKIP_TAGS

    new vault file for rekey only run the playbook if the repository has been updated output file name for encrypt or decrypt; use - for stdout purge checkout after playbook run

    only run plays and tasks whose tags do not match these values -s SLEEP, --sleep=SLEEP sleep for random interval (between 0 and n number of seconds) before starting. This is a useful way to disperse git requests -t TAGS, --tags=TAGS only run plays and tasks tagged with these values -U URL, --url=URL URL of the playbook repository --vault--file=VAULT__FILE vault file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) ---commit GPG signature of checked out commit, if it fails abort running the playbook. This needs the corresponding VCS module to such an operation --version show program's version number and exit Connection Options: control as whom and how to connect to hosts -k, --ask- ask for connection --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE use this file to authenticate the connection -u REMOTE_, --=REMOTE_ connect as this (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart) -T TIMEOUT, --timeout=TIMEOUT override the connection timeout in seconds (default=10) --ssh-common-args=SSH_COMMON_ARGS specify common arguments to to sftp/s/ssh (e.g. ProxyCommand) --sftp-extra-args=SFTP_EXTRA_ARGS specify extra arguments to to sftp only (e.g. -f, -l) --s-extra-args=S_EXTRA_ARGS specify extra arguments to to s only (e.g. -l) --ssh-extra-args=SSH_EXTRA_ARGS specify extra arguments to to ssh only (e.g. -R) Privilege Escalation Options: control how and which you become as on target hosts --ask-sudo- ask for sudo (deprecated, use become) --ask-su- ask for su (deprecated, use become) -K, --ask-become- ask for privilege escalation ############################################################################### (4) Accessing documentation locally

    $ ansible-doc Usage: ansible-doc [options] [module...] Options: -h, --help show this help message and exit -l, --list List available modules -M MODULE_PATH, --module-path=MODULE_PATH specify path(s) to module library (default=None) -s, --snippet Show playbook snippet for specified module(s) -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit ############################################################################### (5) Ansible Galaxy tool $ ansible-galaxy Usage: ansible-galaxy [delete|import|info|init|install|list||remove|search| setup] [--help] [options] ... Options: -h, --help -v, --verbose --version Examples: ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy ansible-galaxy

    show this help message and exit verbose mode (-vvv for more, -vvvv to enable connection debugging) show program's version number and exit search --author search --platforms search --galaxy-tags info install -p install -r ... list remove init init --offline

    ############################################################################### (6) Hiding secrets $ ansible-vault Usage: ansible-vault [create|decrypt|edit|encrypt|rekey|view] [--help] [options] vaultfile.yml Options: --ask-vault- ask for vault -h, --help show this help message and exit --new-vault--file=NEW_VAULT__FILE new vault file for rekey --output=OUTPUT_FILE output file name for encrypt or decrypt; use - for stdout --vault--file=VAULT__FILE vault file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit ############################################################################### (7) Windows

    $ pip install pywinrm

    <-- on the control machine

    Authentication: a/ Certificate: authentication similar to SSH b/ Kerberos: python-kerberos c/ CredSSP: for local and domain s On a/ b/ c/

    the client(s): PowerShell 3.0 or higher Enable PowerShell Set up WinRM:

    https://github.com/ansible/ansible/blob/devel/examples/scripts/ConfigureRemotingFor Ansible.ps1 For Kerberos, on the client(s): python-devel, krb5-devel, krb5-libs, krb5-workstation, pywinrm /etc/krb5.conf.d/ansible.conf [realms] ad1.${GUID}.example.com = { kdc = ad1.${GUID}.example.opentlc.com } 'ansible.cfg' example: ansible_connection=winrm ansible_= Windows Ansible modules examples: win_ping win_chocolatey win_service win_firewall win_firewall_rule win_ win_domain_ win_domain_controller

    More Documents from "Don CoachDon High" 72611x

    Ansible-cheatsheet 2n41q
    May 2020 26
    250406394-sap-pra.pdf 386766
    December 2021 0
    Baby Shark 22m5n
    December 2019 85
    Vdocuments.site Cat Spec List 5g113q
    January 2022 0
    Error Vl 609.txt 6zk
    May 2023 0
    Exercicios Treinamento Funcional Pdf 1y4s4g
    October 2019 544