0% found this document useful (0 votes)
7 views4 pages

Ansible Commands 1710820285

Uploaded by

zymdx24zcy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

Ansible Commands 1710820285

Uploaded by

zymdx24zcy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Ansible Quick Reference

ANSIBLE INVENTORY CONFIGURATION FILES


//The /etc/ansible/hosts file is considered the //Configuration File Precedence
system's default static inventory file.
//Inventory file on the command line with the -- 1. Any file specified by the ANSIBLE_CONFIG
inventory PATHNAME or -i PATHNAME option, where environment variable
PATHNAME is the path to the desired inventory file.
2. The directory in which the ansible command was
run is then checked for an ansible.cfg file.
1. Static inventory:

i
[usa] 3. The user's home directory is checked for a

sh
washington1.example.com .ansible.cfg file
washington2.example.com
4. The global /etc/ansible/ansible.cfg file
[canada]
ontario01.example.com //For example, ansible.cfg file:
ontario02.example.com [defaults]

m
inventory = ./inventory
[north-america:children] remote_user = user
canada ask_pass = false
usa

Va
[privilege_escalation]
2. Dynamic Inventory: Dynamic inventory scripts can become = true
be used to generate dynamic lists of managed become_method = sudo
hosts from directory services or other sources
become_user = root
external to Ansible.
become_ask_pass = false
ith
AD-HOC COMMANDS MODULES

// Use the ansible command to run ad hoc commands: //Ansible provides a module
ansible host-pattern -m module [-a 'module arguments'] [-i inventory] library that you can
execute directly on remote
1. Performing Tasks with Modules Using Ad Hoc Commands hosts or through playbooks.
W
$ ansible -m user -a 'name=amin uid=4000 state=present' \
> servera.lab.test.com //Files modules
2. Running Arbitrary Commands on Managed Hosts copy
$ ansible myhosts -m command -a /usr/bin/hostname file
lineinfile
ps

blockinfile
PLAYBOOKS synchronize

//A play is an ordered set of tasks that is run against hosts selected //Software package modules
from your inventory. A playbook is a text file that contains a list of package
one or more plays to run in order. Ex: site.yml playbook: gem
vo

--- apt
- name: Install and start Apache HTTPD pip
hosts: web yum
tasks: dnf
- name: httpd package is present
yum: //System modules
De

name: httpd firewalld


state: present reboot
- name: correct index.html is present service
copy: user
src: files/index.html
dest: /var/www/html/index.html //Net Tools modules
- name: httpd is started get_url
service: nmcli
name: httpd uri
state: started
enabled: true
Ansible Quick Reference

RUNNING YOUR PLAYBOOK VARIABLES


//Verify that its syntax is correct: //Variable names must start with a letter, and they can
$ ansible-playbook --syntax-check site.yml only contain letters, numbers, and underscores. Variables
can be scoped by group, host, or within a playbook.
//Run your playbook: //Variables defined by the inventory are overridden by
$ ansible-playbook site.yml variables defined by the playbook, which are overridden
by variables defined on the command line.
//Dry run the playbook:
$ ansible-playbook -C site.yml ---

i
- hosts: webservers

sh
become: yes
vars:
TEMPLATES target_service: httpd
//Templates are files with Ansible variables target_state: started
inside that are substituted on play tasks:
- name: Ensure target service is at target state

m
execution. Templates use the template module.
service:
Module parameters: name: "{{ target_service }}"
src — Template file to use. state: "{{ target_state }}"
dest — Where the resulting file should be on

Va
the target host. LOOPS
validate — validate a file before deployment.
//The loop keyword may be used to more concisely express
my_app.conf.j2 containing: a repeated action.
local_ip = {{ ansible_default_ipv4["address"] }} - name: add several users
local_user = {{ ansible_user }} user:
name: "{{ item }}"
ith
playbook.yml: state: present
- name: copy configuration file from template groups: "wheel"
template: loop:
src: my_app.conf.j2 - testuser1
dest: $HOME/my_app.conf - testuser2
W
HANDLERS TAGS

//Ansible allows an action to be flagged for execution when a //If you have a large playbook, it
task performs a change. may become useful to be able to run
//Handler is only ran one time at the final phase of play only a specific part of it rather
than running everything in the
ps

execution.
playbook.
tasks:
- name: configuration file tasks:
template: - yum:
src: template.j2 name:
vo

dest: /etc/foo.conf - httpd


notify: - memcached
- restart memcached state: present
- restart apache tags:
handlers: - packages
- name: restart memcached
De

service: - template:
name: memcached src: templates/src.j2
state: restarted dest: /etc/foo.conf
listen: "restart memcached" tags:
- name: restart apache - configuration
service:
name: apache $ ansible-playbook example.yml \
state:restarted --tags "configuration,packages"
listen: "restart apache" $ ansible-playbook example.yml \
--skip-tags "packages"
Ansible Quick Reference

VAULT --VAULT-ID
//Ansible Vault is a feature of ansible that //A vault ID is an identifier for one or more vault secrets;
allows you to keep sensitive data such as Ansible supports multiple vault passwords. Vault IDs provide
passwords or keys in encrypted files labels to distinguish between individual vault passwords.

//To use vault IDs, you must provide an ID label of your


//Creating Encrypted Files
choosing and a source to obtain its password (either prompt or
$ ansible-vault create foo.yml a file path):
//Editing Encrypted Files --vault-id label@source
$ ansible-vault edit foo.yml

i
//Rekeying Encrypted Files //To create a new encrypted data file with the Vault ID

sh
$ ansible-vault rekey foo.yml bar.yml ‘password1’ assigned to it and be prompted for the password,
//Encrypting Unencrypted Files run:
$ ansible-vault encrypt foo.yml bar.yml $ ansible-vault create --vault-id password1@prompt foo.yml
//Decrypting Encrypted Files
//To edit a file encrypted with the ‘vault2’ password file and
$ ansible-vault decrypt foo.yml bar.yml assigned the ‘pass2’ vault ID:
//Viewing Encrypted Files

m
$ ansible-vault edit --vault-id pass2@vault2 foo.yml
$ ansible-vault view foo.yml bar.yml
//To encrypt existing files with the ‘project’ ID and be
prompted for the password:
IGNORE_ERRORS $ ansible-vault encrypt --vault-id project@prompt foo.yml

Va
//By default Ansible stops executing tasks on
a host when a task fails on that host. You REGISTER
can use ignore_errors to continue on in spite
of the failure. //The register module is used to store task output in a
dictionary variable.
- name: Do not count this as a failure - hosts: all
ith
ansible.builtin.command: /bin/false tasks:
ignore_errors: true - shell: cat /etc/motd
register: motd_contents
- shell: echo "motd contains the word hi"
DEFINING "CHANGED" when: motd_contents.stdout.find('hi') != -1
//Ansible lets you define when a particular
W
task has “changed” a remote node using the
changed_when conditional. DEFINING FAILURE
//Ansible lets you define what “failure” means in each
- command: /bin/fake_command task using the failed_when conditional.
register: result
ps

ignore_errors: True - name: Fail task when both files are identical
changed_when: raw: diff foo/file1 bar/file2
- '"ERROR" in result.stderr' register: diff_cmd
- result.rc == 2 failed_when: diff_cmd.rc == 0 or diff_cmd.rc >= 2

DEBUG BLOCKS
vo

//The debug module may be used to help //You can control how Ansible responds to task errors using
troubleshoot plays. Use to print detail blocks. The tasks in the block execute normally. If any tasks
in the block return failed, the rescue section executes tasks
information about in progress plays.
to recover from the error. The always section runs regardless
of the results of the block and rescue sections.
De

//Debug takes two primary parameters : - name: Attempt and graceful roll back demo
msg - A message that is printed to STDOUT block:
var - A variable name to debug. Mutually - debug:
exclusive with the msg option. msg: 'I execute normally'
- name: i force a failure
- name: Print a simple statement command: /bin/false
debug: - debug:
msg: 'I never execute, due to the above task failing, :-('
msg: "Welcome to this Quick Reference"
rescue:
- debug:
msg: 'I caught an error'
ABOUT THIS DOCUMENT - name: i force a failure in middle of recovery! >:-)
command: /bin/false
//This document is prepared for a - debug:
quick review of topics related to the msg: 'I also never execute :-('
preliminary management of Ansible. always:
- debug:
msg: "This always executes"
Ansible Quick Reference

ASYNCHRONOUS ACTIONS PARALLELISM


//A task may take longer to complete than the SSH session allows //The serial keyword may be used to
for, causing a timeout. Or you may want a long-running process to control forks in playbook.
execute in the background while you perform other tasks //You may provide as integer count or as
concurrently. Asynchronous mode lets you control how long-running percentage.
tasks execute.
//key values for an asynchronous task:
//You may provide a step up approach
async - A timeout for an operation (default is unlimited). (can mix and match count with
Poll - A poll value for who often Ansible should check back. value of 0 percentage)

i
will have Ansible not check back on a task. //It is possible to use
max_fail_percentage to allow a certain

sh
- name: 'Install docker-io (async)' percentage to fail.
yum:
name: docker-io
state: installed ---
async: 1000 - hosts: webservers
poll: 25 max_fail_percentage: 10

m
serial:
- 1
ROLES - 5
- "30%"
//Roles provide a way of automatically loading certain var_files, tasks:

Va
tasks, and handlers based on a known file structure. Roles require - name: Install apache
a particular directory structure. yum:
name=httpd
base_directory/ state=latest
<role 1>
tasks/ # Contains the main list of tasks to be executed by
the role.
handlers/ # Contains handlers, whichmay be used by this
ith
DELEGATING PLAYBOOK EXECUTION
role or even anywhere outside this role.
files/ # Contains files which can be deployed via this //Certain tasks may need to be executed
role. on specific hosts. In order to delegate,
tempaltes/ # Contains templates which can be deployed via use the delegate_to keyword.
this role.
vars/ # Other variables for the role - command: /opt/application/upgrade_db.py
W
defaults/ # Default variables for the role run_once: true
meta # Defines some meta data for this role. See below for delegate_to: web01.example.org
more details.
<role 2>
tasks/
RUN_ONCE
ps

defaults/
meta/ //There are scenarios where a specific
task needs to be ran only a single time
in a given playbook and not on each
CREATING ROLES host. This may be achieved using the
run_once keyword.
vo

//Using the ansible-galaxy command line tool that comes bundled


with Ansible, you can create a role with the init command. For
example, the following will create a role directory structure - name: db upgrade task
command: /opt/application/upgrade_db.py
called test-role-1 in the current working directory:
run_once: true
$ ansible-galaxy init test-role-1
De

ABOUT AUTHOR
//Amin Shateri is a Linux/DevOps Engineer who loves knowledge sharing.
Linkedin: https://www.linkedin.com/in/amin-shateri/
Email: [email protected]
Website: https://aminshateri.com

You might also like