Ansible Commands 1710820285
Ansible Commands 1710820285
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
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
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.
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
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
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