Ansible Interview Questions and Answers


What is Ansible?
  • Ansible is an open-source automation tool used for configuration management, application deployment, task automation, and orchestration.
  • It is known for its simplicity, agentless architecture, and use of YAML for defining automation tasks.
What are the key benefits of using Ansible?
  • Simplicity: Easy to learn and use due to its YAML syntax and agentless nature.
  • Agentless: Does not require installing agents on managed nodes, relying on SSH.
  • Powerful: Can automate a wide range of tasks, from simple configuration to complex deployments and orchestration.
  • Idempotent: Tasks can be run repeatedly without changing the system state unnecessarily.
  • Extensible: Provides a large collection of modules and allows for custom module creation.
  • Community: Strong and active community support.
What is the difference between Ansible and other configuration management tools like Puppet or Chef?
  • Agentless: Ansible is agentless, while Puppet and Chef require agents on managed nodes.
  • Language: Ansible uses YAML (Playbooks), Puppet uses its own DSL (Puppet DSL), and Chef uses Ruby (Cookbooks/Recipes).
  • Pull vs. Push: Puppet and Chef typically use a pull model (agents pull configurations), while Ansible uses a push model (control node pushes configurations).
What is the architecture of Ansible?
  • Control Node: The machine where Ansible is installed and from which commands and Playbooks are run.
  • Managed Nodes: The target machines that Ansible manages.
  • Inventory: A list of managed nodes.
  • Modules: Units of code that execute specific tasks on managed nodes.
  • Plugins: Extend Ansible's core functionality.
  • Playbooks: YAML files that define automation tasks.
  • Roles: Structure Playbooks into reusable components.
What is an Inventory file in Ansible?
  • An Inventory file is a list of managed nodes (servers, network devices, etc.) that Ansible will manage.
  • It can be in INI or YAML format.
  • It defines hosts and groups of hosts.
How do you define hosts and groups in an Inventory file?
  • In INI format:
    [webservers]
    web1.example.com
    web2.example.com
    
    [databases]
    db1.example.com
  • In YAML format:
    all:
      hosts:
        web1.example.com:
        web2.example.com:
        db1.example.com:
      children:
        webservers:
          hosts:
            web1.example.com:
            web2.example.com:
        databases:
          hosts:
            db1.example.com:
How does Ansible connect to managed nodes?
  • Ansible primarily uses SSH to connect to Linux/Unix-like systems.
  • For Windows, it uses WinRM.
  • It requires Python installed on the managed nodes for most modules.
What is a Playbook in Ansible?
  • A Playbook is a YAML file that defines a set of automation tasks to be executed on managed nodes.
  • It describes the desired state of the system.
  • Playbooks consist of one or more "plays".
What is a Play in a Playbook?
  • A Play is a collection of tasks that are executed on a specific set of hosts defined in the Inventory.
  • Each play targets hosts and defines the tasks to be run on those hosts.
What is a Task in a Playbook?
  • A Task is the basic unit of action in a Playbook.
  • Each task executes a specific module with a set of arguments.
  • Tasks are executed in the order they are defined within a play.
What is a Module in Ansible?
  • A Module is a unit of code that performs a specific action on a managed node.
  • Ansible provides a large collection of modules for various tasks (package management, service control, file operations, etc.).
  • Modules are idempotent, meaning they can be run multiple times without unintended side effects.
What is Idempotency in Ansible?
  • Idempotency means that running an Ansible task multiple times will result in the same system state as running it just once.
  • Tasks only make changes if the desired state is not already met.
  • This simplifies automation and prevents unexpected side effects.
How do you run an Ad-Hoc command in Ansible?
  • You use the ansible command followed by the target host/group, the -m flag to specify the module, and the -a flag for module arguments.
  • Example: ansible webservers -m ping
  • Example: ansible all -m apt -a "name=nginx state=present"
How do you run a Playbook?
  • You use the ansible-playbook command followed by the path to the Playbook file.
  • Example: ansible-playbook site.yml
What is the purpose of the hosts keyword in a Playbook?
  • The hosts keyword in a play specifies which hosts from the Inventory the tasks in that play will be executed on.
  • It can be a single host, a group, or a pattern.
What is the purpose of the become keyword in a Playbook?
  • The become keyword is used for privilege escalation (like sudo or su).
  • It allows tasks to be run with elevated privileges on the managed nodes.
How do you set variables in Ansible?
  • Variables can be set in various places:
    • Inventory file (host variables, group variables).
    • Playbooks (vars section).
    • Roles (vars, defaults).
    • Command line (-e flag).
    • Facts (gathered automatically).
    • Vault.
What is the order of precedence for variables in Ansible?
  • Variable precedence is important for understanding which variable value will be used when there are conflicting definitions. The order is complex but generally follows: command line > role/playbook vars > inventory vars > facts > defaults. Refer to the official documentation for the precise order.
What are Facts in Ansible?
  • Facts are pieces of information gathered about the managed nodes by Ansible's setup module.
  • This information includes details about the operating system, network interfaces, hardware, etc.
  • Facts are automatically gathered at the beginning of each play unless explicitly disabled.
How do you access facts in a Playbook?
  • Facts are available as variables within the Playbook.
  • Example: {{ ansible_distribution }} to get the OS distribution name.
What are Handlers in Ansible?
  • Handlers are tasks that are triggered by other tasks using the notify keyword.
  • They are executed only once at the end of a play, even if notified multiple times.
  • They are commonly used for restarting services after configuration changes.
How do you notify a Handler?
  • You use the notify keyword in a task, referencing the name of the handler.
  • - name: Install Nginx
      apt: name=nginx state=present
      notify: Restart Nginx
What is the purpose of the when keyword in a task?
  • The when keyword is used to conditionally execute a task based on a condition.
  • The condition is typically a Jinja2 expression that evaluates to true or false.

Example:

- name: Restart Nginx on Ubuntu
  service: name=nginx state=restarted
  when: ansible_distribution == 'Ubuntu'
What are Loops in Ansible?
  • Loops are used to repeat a task multiple times with different input values.
  • The loop keyword is the modern way to define loops.

Example:

- name: Create multiple directories
  file:
    path: /tmp/{{ item }}
    state: directory
  loop:
    - dir1
    - dir2
    - dir3
What are Templates in Ansible?
  • Templates are files that contain dynamic content and use the Jinja2 templating language.
  • The template module is used to render templates on managed nodes, replacing variables and expressions with their actual values.
What is Jinja2 in the context of Ansible?
  • Jinja2 is a templating language used in Ansible templates.
  • It allows you to use variables, loops, conditionals, and filters within template files to generate dynamic content.
What is Ansible Vault?
  • Ansible Vault is a feature used to encrypt sensitive data, such as passwords, API keys, and certificates.
  • Vault-encrypted files can be included in your Playbooks and roles.
How do you encrypt a file with Ansible Vault?
  • You use the ansible-vault encrypt command.
  • You will be prompted to set a password.
How do you decrypt a file with Ansible Vault?
  • You use the ansible-vault decrypt command.
  • You will be prompted for the password.
How do you run a Playbook that uses Vault-encrypted files?
  • You use the --ask-vault-pass flag with the ansible-playbook command.
  • Example: ansible-playbook site.yml --ask-vault-pass
  • You can also provide the password in a file using --vault-password-file.
What is a Role in Ansible?
  • A Role is a way to structure Playbooks into reusable components.
  • It organizes tasks, handlers, variables, templates, and files into a predefined directory structure.
  • Roles make Playbooks more modular, readable, and maintainable.
What are the standard directories within an Ansible Role?
  • tasks/ (main.yml)
  • handlers/ (main.yml)
  • vars/ (main.yml)
  • defaults/ (main.yml)
  • files/
  • templates/
  • meta/ (dependencies)
How do you use a Role in a Playbook?
  • You include the role in the roles section of a play.

Example:

- hosts: webservers
  roles:
    - webserver
What is Ansible Galaxy?
  • Ansible Galaxy is a website and command-line tool for finding, sharing, and installing community-contributed Ansible roles.
  • You can use the ansible-galaxy command to install roles.
How do you install a role from Ansible Galaxy?
  • You use the ansible-galaxy install command.
  • Example: ansible-galaxy install geerlingguy.nginx
What is the difference between import_tasks and include_tasks?
  • import_tasks is a static import. The tasks are loaded at Playbook parse time. This is more performant and allows for syntax checking.
  • include_tasks is a dynamic include. The tasks are loaded at runtime. This allows for including tasks conditionally or in loops.
  • import_tasks is generally preferred unless dynamic behavior is required.
What is the difference between import_playbook and include_playbook?
  • Similar to tasks, import_playbook is static (parsed at the beginning), while include_playbook is dynamic (parsed at runtime).
What is Dynamic Inventory?
  • Dynamic Inventory is a way to generate the list of managed nodes dynamically from external sources, such as cloud providers (AWS, Azure, GCP), CMDBs, or custom scripts.
  • This is useful in dynamic environments where the list of servers changes frequently.
Why would you use Dynamic Inventory?
  • To automatically update the Inventory as infrastructure changes.
  • To fetch host variables and group assignments from external sources.
  • To manage large and constantly changing environments.
How do you perform a dry run of a Playbook?
  • You use the --check flag with the ansible-playbook command.
  • Example: ansible-playbook site.yml --check
  • This shows what changes *would* be made without actually making them.
How do you limit Playbook execution to specific tasks?
  • You can use the --tags or --skip-tags flags if tasks are tagged.
  • You can use the --start-at-task flag to start execution from a specific task name.
How do you limit Playbook execution to specific hosts?
  • You can use the --limit flag with a host name or group name.
  • Example: ansible-playbook site.yml --limit webservers
What is the purpose of the ansible.cfg file?
  • ansible.cfg is the main configuration file for Ansible.
  • It allows you to set default values for various Ansible settings, such as the Inventory file location, roles path, connection settings, etc.
  • It can be placed in multiple locations (e.g., project directory, user home directory, system-wide) with precedence rules.
What is the default location for the Inventory file?
  • The default location is /etc/ansible/hosts.
  • You can specify a different location using the -i flag or in ansible.cfg.
How do you increase the verbosity of Ansible output?
  • You use the -v, -vv, -vvv, or -vvvv flags with Ansible commands.
  • Higher verbosity provides more detailed output, useful for debugging.
How do you debug a task in a Playbook?
  • You can add the debugger: on_failed or debugger: always keyword to a task.
  • This will drop you into an interactive debugging session if the task fails or always, respectively.
What is the purpose of the failed_when keyword?
  • failed_when is used to define custom failure conditions for a task.
  • If the condition specified in failed_when evaluates to true, the task will be marked as failed, even if the module itself didn't report an error.
What is the purpose of the changed_when keyword?
  • changed_when is used to define custom change conditions for a task.
  • By default, modules report whether they made changes. You can override this behavior with changed_when if the module's default detection is incorrect.
What is the difference between command and shell modules?
  • command module is simpler and safer. It executes commands without going through a shell. It does not support shell features like pipes, redirection, or environment variables.
  • shell module executes commands through a shell (e.g., /bin/sh). It supports shell features but is less secure and can be more prone to errors.
  • Prefer command unless you specifically need shell features.
What is the purpose of the copy module?
  • The copy module is used to copy files from the control node to managed nodes.
  • It can also set file permissions, ownership, and modes.
What is the purpose of the file module?
  • The file module is used for managing files, directories, and symlinks on managed nodes.
  • It can create, delete, change permissions, ownership, and state (e.g., present, absent, directory, link).
What is the purpose of the service module?
  • The service module is used for managing services on managed nodes (e.g., starting, stopping, restarting, enabling, disabling).
  • It supports various init systems (sysvinit, systemd, upstart).
What is the purpose of the package module (or platform-specific like apt, yum)?
  • These modules are used for managing packages on managed nodes.
  • They can install, update, remove, and list packages using the native package manager of the target system.
What is the purpose of the user module?
  • The user module is used for managing user accounts on managed nodes (creating, deleting, modifying user properties like password, UID, groups, etc.).
What is the purpose of the group module?
  • The group module is used for managing groups on managed nodes (creating, deleting, modifying group properties).
What is the purpose of the wait_for module?
  • The wait_for module is used to wait for a specific condition on a managed node, such as a port to become open, a file to exist, or a string to appear in a file.
  • It's useful for synchronizing tasks that depend on asynchronous operations.
What is the purpose of the debug module?
  • The debug module is used to print messages or variable values during Playbook execution.
  • It's helpful for debugging and understanding the flow of your Playbook.
How do you gather facts explicitly in a Playbook?
  • You can use the setup module as a task.
  • Alternatively, you can set gather_facts: true (which is the default) in a play.
How do you disable fact gathering in a Playbook?
  • You set gather_facts: false in a play.
  • This can improve performance if you don't need facts in that play.
What is the purpose of the delegate_to keyword?
  • delegate_to is used to execute a task on a different host than the one specified in the play's hosts section.
  • It's useful for tasks that need to be performed on a central server or a specific machine (e.g., running a database migration script from the control node).
What is the purpose of the run_once keyword?
  • run_once: true executes a task only once on the first host in the current batch of hosts, even if the play targets multiple hosts.
  • This is useful for tasks that should only be performed a single time, such as creating a database or running a migration.
What is the purpose of the local_action keyword?
  • local_action is a shorthand for delegate_to: localhost.
  • It executes a task on the control node where the Playbook is being run.
What are Roles dependencies?
  • Roles can declare dependencies on other roles in their meta/main.yml file.
  • When a role with dependencies is included in a Playbook, Ansible automatically ensures that the dependent roles are executed first.
What is the purpose of the meta/main.yml file in a Role?
  • The meta/main.yml file contains metadata about the role, including:
    • Role dependencies.
    • Author information.
    • Supported platforms.
How do you create a new Role using the Ansible CLI?
  • You use the ansible-galaxy init command.
  • Example: ansible-galaxy init my_webserver_role
What is the difference between vars and defaults directories in a Role?
  • vars/: Contains variables that are specific to the role and have higher precedence than variables defined in the Inventory or Playbook's vars section.
  • defaults/: Contains variables with the lowest precedence. These are default values that can be easily overridden in the Inventory or Playbook.
What is the purpose of the lookup plugin?
  • Lookup plugins are used to retrieve data from external sources during Playbook execution.
  • Examples: reading from files (file lookup), getting environment variables (env lookup), generating passwords (password lookup).

Example:

- name: Read content from a file
  debug: msg="{{ lookup('file', '/path/to/my/file') }}"
What is the purpose of the filter plugin?
  • Filter plugins are used to transform data using Jinja2 filters.
  • Ansible provides many built-in filters, and you can create custom ones.

Example:

- name: Display uppercase string
  debug: msg="{{ my_string | upper }}"
What is the purpose of the test plugin?
  • Test plugins are used to test conditions or expressions within Jinja2 templates or when clauses.
  • They return a boolean value.

Example:

- name: Check if a variable is defined
  debug: msg="Variable is defined"
  when: my_variable is defined
What is the purpose of the callback plugin?
  • Callback plugins allow you to hook into Ansible events during Playbook execution (e.g., when a task starts, when a task completes, when a handler is run).
  • They are used for reporting, logging, or integrating with other systems.
What is the purpose of the connection plugin?
  • Connection plugins determine how Ansible connects to managed nodes (e.g., ssh, local, docker, winrm).
What is the purpose of the inventory plugin?
  • Inventory plugins are used for generating dynamic inventory from various sources.
  • They replace the older dynamic inventory scripts.
How do you include a file within a Playbook?
  • You can use include_vars to include variable files.
  • You can use include_tasks or import_tasks to include task files.
  • You can use include_role or import_role to include roles.
What is the difference between copy and template modules?
  • copy module copies a static file from the control node to the managed node.
  • template module processes a Jinja2 template file, substituting variables and expressions, before copying the rendered file to the managed node.
  • Use template when the content of the file needs to be dynamic based on variables or facts.
What is the purpose of the lineinfile module?
  • The lineinfile module is used to ensure a specific line is present, absent, or matches a pattern in a file.
  • It's useful for modifying configuration files without replacing the entire file.
What is the purpose of the blockinfile module?
  • The blockinfile module is used to manage blocks of lines in a file, typically marked with start and end markers.
  • It's useful for inserting or managing large configuration blocks.
What is the purpose of the replace module?
  • The replace module is used to replace all occurrences of a pattern in a file with a replacement string.
  • It uses regular expressions for pattern matching.
What is the purpose of the stat module?
  • The stat module is used to retrieve information (like size, permissions, owner, existence) about a file or directory on a managed node without changing its state.
  • The information is stored in the task's result and can be accessed using register.
What is the purpose of the register keyword?
  • The register keyword is used to capture the output of a task and store it in a variable.
  • This variable can then be used in subsequent tasks, conditionals, or debug messages.

Example:

- name: Check file status
  stat: path=/etc/passwd
  register: passwd_stat

- name: Debug file existence
  debug: msg="File exists: {{ passwd_stat.stat.exists }}"
What is the purpose of the ignore_errors keyword?
  • ignore_errors: true allows a task to continue executing even if it fails.
  • Use with caution, as it can mask underlying issues.
What is the purpose of the listen keyword in Handlers (deprecated)?
  • listen was an older way to trigger handlers. It was replaced by the more explicit notify keyword.
What is the purpose of the serial keyword in a Play?
  • serial is used to control the number of hosts that are managed in parallel within a play.
  • It allows you to perform rolling updates or deployments on a subset of hosts at a time.

Example:

- hosts: webservers
  serial: 2 # Process 2 webservers at a time
  tasks:
    - ...
What is the purpose of the max_fail_percentage keyword in a Play?
  • max_fail_percentage sets a threshold for the maximum percentage of hosts in a play that can fail before Ansible stops executing the play on the remaining hosts.
What is the purpose of the strategy keyword in a Play?
  • strategy defines how tasks are executed on hosts within a play.
  • The default strategy is linear (tasks are executed on all hosts in the batch before moving to the next task).
  • Other strategies include free (tasks are executed as hosts become available) and custom strategies.
What is the purpose of the delegate_facts keyword?
  • delegate_facts: true is used in conjunction with delegate_to.
  • It instructs Ansible to store the facts gathered from the delegated host under the original host's facts.
  • This is useful when gathering information about a host from a different machine.
What is the purpose of the register keyword (revisited)?
  • The register keyword is used to capture the output of a task and store it in a variable.
  • This variable contains details about the task's execution, including whether it changed the system, its standard output, and any errors.
What is the purpose of the check_mode in Ansible?
  • check_mode (enabled with --check) is a mode where Ansible runs tasks without actually making changes to the managed nodes.
  • Modules that support check mode will report what changes *would* be made.
  • It's useful for validating Playbooks and understanding their impact.
What is the purpose of the diff flag?
  • The --diff flag shows the differences in files that would be copied or templated when running in check mode or when changes are made.
  • It helps visualize the impact of file-related tasks.
What is the purpose of the tags keyword?
  • tags are used to label tasks, plays, or roles.
  • You can then run only specific parts of a Playbook using the --tags or --skip-tags flags.
  • This is useful for running subsets of your automation.
How do you include a file in a Playbook?
  • You can use include_tasks or import_tasks for tasks.
  • You can use include_vars for variable files.
  • You can use the copy or template modules to copy files.
What is the difference between copy and synchronize modules?
  • copy copies a single file or directory from the control node to the managed node.
  • synchronize is a wrapper around rsync and is used for efficiently synchronizing directories between the control node and managed nodes, or between two managed nodes. It's better for large file transfers or when dealing with many files.
What is the purpose of the roles_path setting in ansible.cfg?
  • roles_path specifies the directories where Ansible should look for roles.
  • You can list multiple paths, and Ansible will search them in order.
What is the purpose of the collections_paths setting in ansible.cfg?
  • collections_paths specifies the directories where Ansible should look for collections.
  • Collections are a newer way to package and distribute Ansible content (roles, modules, plugins).
What is a Collection in Ansible?
  • A Collection is a new format for packaging and distributing Ansible content.
  • It can include roles, modules, plugins, and documentation.
  • Collections are managed using the ansible-galaxy collection command.
How do you install a Collection?
  • You use the ansible-galaxy collection install command.
  • Example: ansible-galaxy collection install community.general
How do you use a module from a Collection in a Playbook?
  • You use the fully qualified collection name (FQCN) for the module.
  • Example: community.general.docker_container
  • You can also use the collections keyword in a play to shorten the FQCN.
What is the purpose of the defaults directory in a Role?
  • The defaults directory contains default variables for the role.
  • Variables in defaults have the lowest precedence and are easily overridden by variables defined elsewhere (Inventory, Playbook, vars directory).
What is the purpose of the vars directory in a Role?
  • The vars directory contains variables that are specific to the role.
  • Variables in vars have higher precedence than variables in defaults, Inventory, or Playbook vars.
What is the purpose of the files directory in a Role?
  • The files directory contains static files that the role needs to copy to managed nodes using the copy module.
  • Files in this directory can be referenced by name in the copy module without specifying the full path.
What is the purpose of the templates directory in a Role?
  • The templates directory contains Jinja2 template files that the role needs to render on managed nodes using the template module.
  • Template files in this directory can be referenced by name in the template module without specifying the full path.
What is the purpose of the handlers directory in a Role?
  • The handlers directory contains handler tasks for the role, typically defined in main.yml.
  • These handlers can be notified by tasks within the same role or from plays that include the role.
What is the purpose of the tasks directory in a Role?
  • The tasks directory contains the main tasks for the role, typically defined in main.yml.
  • These tasks define the primary automation steps performed by the role.
What is the purpose of the meta directory in a Role?
  • The meta directory contains metadata about the role in main.yml.
  • This includes role dependencies, author information, and supported platforms.
What is the purpose of the pre_tasks keyword in a Play?
  • pre_tasks is a list of tasks that are executed before any roles or regular tasks in a play.
  • It's useful for performing setup tasks like gathering facts or installing prerequisites.
What is the purpose of the post_tasks keyword in a Play?
  • post_tasks is a list of tasks that are executed after all roles and regular tasks in a play.
  • It's useful for performing cleanup tasks or reporting.
What is the purpose of the vars_files keyword in a Play or Role?
  • vars_files is used to include variable definitions from external YAML files.
  • This helps in organizing large sets of variables.
What is the purpose of the environment keyword in a task?
  • The environment keyword sets environment variables for a specific task.
  • It takes a dictionary of key-value pairs.

Example:

- name: Run command with specific environment variable
  command: my_command
  environment:
    MY_VAR: my_value
What is the purpose of the args keyword in a task?
  • The args keyword is used to pass arguments to a module.
  • It's an alternative way to specify module parameters, especially for complex arguments or when using reserved keywords.
What is the purpose of the delegate_facts keyword (revisited)?
  • delegate_facts: true is used in conjunction with delegate_to.
  • It instructs Ansible to store the facts gathered from the delegated host under the original host's facts.
  • This is useful when gathering information about a host from a different machine.
What is the purpose of the run_once keyword (revisited)?
  • run_once: true executes a task only once on the first host in the current batch of hosts, even if the play targets multiple hosts.
  • This is useful for tasks that should only be performed a single time, such as creating a database or running a migration.
What is the purpose of the local_action keyword (revisited)?
  • local_action is a shorthand for delegate_to: localhost.
  • It executes a task on the control node where the Playbook is being run.
What is the purpose of the poll keyword in a task?
  • poll controls how often Ansible checks the status of a task when using asynchronous execution.
  • By default, tasks are synchronous (Ansible waits for completion). For long-running tasks, you can make them asynchronous and poll for their status.
What is the purpose of the async keyword in a task?
  • async is used to run a task asynchronously.
  • Ansible will start the task on the managed node and move on to the next task without waiting for the asynchronous task to complete.
  • You typically use async with poll or the async_status module to check the status later.
What is the purpose of the until keyword in a task?
  • until is used with retries and delay to retry a task until a specific condition is met or a maximum number of retries is reached.
  • It's useful for waiting for services to start or for conditions to be true after a change.

Example:

- name: Wait for Nginx to be listening on port 80
  wait_for:
    port: 80
    timeout: 60
  retries: 10
  delay: 6
  until: result is success # 'result' is the output of the wait_for module
What is the purpose of the retries keyword in a task?
  • retries specifies the number of times a task should be retried when used with the until keyword.
What is the purpose of the delay keyword in a task?
  • delay specifies the number of seconds to wait between retries when used with the until and retries keywords.
What is the purpose of the check_mode in Ansible (revisited)?
  • check_mode (enabled with --check) is a mode where Ansible runs tasks without actually making changes to the managed nodes.
  • Modules that support check mode will report what changes *would* be made.
  • It's useful for validating Playbooks and understanding their impact.
What is the purpose of the diff flag (revisited)?
  • The --diff flag shows the differences in files that would be copied or templated when running in check mode or when changes are made.
  • It helps visualize the impact of file-related tasks.
What is the purpose of the syntax-check flag?
  • The --syntax-check flag checks the syntax of a Playbook without executing it.
  • It's a quick way to catch YAML or Playbook structure errors.
What is the purpose of the list-tasks flag?
  • The --list-tasks flag shows the list of tasks that would be executed by a Playbook without actually running them.
  • It's useful for previewing the execution plan.
What is the purpose of the list-hosts flag?
  • The --list-hosts flag shows the list of hosts that a Playbook would target based on the inventory and play definitions.
What is the purpose of the start-at-task flag?
  • The --start-at-task flag starts Playbook execution from a specific task.
  • This is useful for continuing a failed Playbook run or testing specific parts of a Playbook.
What is the purpose of the step flag?
  • The --step flag runs the Playbook in step-by-step mode.
  • Ansible will pause before each task and ask for confirmation before executing it.
  • Useful for debugging or carefully executing sensitive Playbooks.
What is the purpose of the one_at_a_time keyword in a Play?
  • one_at_a_time: true is equivalent to serial: 1.
  • It processes hosts one by one.
What is the purpose of the order keyword in a Play?
  • order controls the order in which hosts are processed within a play.
  • Options include sorted (default), reverse, shuffle, random, reverse_sorted.
What is the purpose of the any_errors_fatal keyword in a Play?
  • any_errors_fatal: true stops the entire Playbook execution immediately if any task on any host fails within that play.
  • By default, Ansible continues with other hosts in the batch even if one fails.
What is the purpose of the max_fail_percentage keyword (revisited)?
  • max_fail_percentage sets a threshold for the maximum percentage of hosts in a play that can fail before Ansible stops executing the play on the remaining hosts.
What is the purpose of the connection keyword in a Play or Task?
  • connection specifies the connection type to use for a play or task (e.g., ssh, local, docker, winrm).
  • This overrides the default connection type.
What is the purpose of the port keyword in a Play or Task?
  • port specifies the port number to use for the connection to the managed node.
  • This overrides the default port for the connection type.
What is the purpose of the remote_user keyword in a Play or Task?
  • remote_user specifies the user to connect as on the managed node.
  • This overrides the default remote user.
What is the purpose of the become_user keyword in a Play or Task?
  • become_user specifies the user to become (switch to) after connecting to the managed node using become: true.
  • The default is typically root.
What is the purpose of the become_method keyword in a Play or Task?
  • become_method specifies the method to use for privilege escalation (e.g., sudo, su, pbrun).
  • The default is typically sudo.
What is the purpose of the become_flags keyword in a Play or Task?
  • become_flags specifies additional flags to pass to the privilege escalation command (e.g., -i for interactive sudo).
What is the purpose of the any_errors_fatal keyword (revisited)?
  • any_errors_fatal: true stops the entire Playbook execution immediately if any task on any host fails within that play.
  • By default, Ansible continues with other hosts in the batch even if one fails.
What is the purpose of the run_once keyword (revisited)?
  • run_once: true executes a task only once on the first host in the current batch of hosts, even if the play targets multiple hosts.
  • This is useful for tasks that should only be performed a single time, such as creating a database or running a migration.
What is the purpose of the local_action keyword (revisited)?
  • local_action is a shorthand for delegate_to: localhost.
  • It executes a task on the control node where the Playbook is being run.
What is the purpose of the poll keyword in a task (revisited)?
  • poll controls how often Ansible checks the status of a task when using asynchronous execution.
  • By default, tasks are synchronous (Ansible waits for completion). For long-running tasks, you can make them asynchronous and poll for their status.
What is the purpose of the async keyword in a task (revisited)?
  • async is used to run a task asynchronously.
  • Ansible will start the task on the managed node and move on to the next task without waiting for the asynchronous task to complete.
  • You typically use async with poll or the async_status module to check the status later.
What is the purpose of the until keyword in a task (revisited)?
  • until is used with retries and delay to retry a task until a specific condition is met or a maximum number of retries is reached.
  • It's useful for waiting for services to start or for conditions to be true after a change.
What is the purpose of the retries keyword in a task (revisited)?
  • retries specifies the number of times a task should be retried when used with the until keyword.
What is the purpose of the delay keyword in a task (revisited)?
  • delay specifies the number of seconds to wait between retries when used with the until and retries keywords.
What is the purpose of the validate option in file-related modules (like copy or template)?
  • The validate option allows you to specify a command to run on the managed node to validate the syntax or correctness of a copied or templated file before it's put into its final destination.
  • If the validation command fails, the task will fail.

Example (validating Nginx config):

- name: Deploy Nginx config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    validate: nginx -t -c %s # %s is replaced with the temporary file path
What is the purpose of the creates and removes options in the command and shell modules?
  • creates: If the specified file exists, the command/shell task will not be executed. This helps make the task more idempotent.
  • removes: If the specified file exists, the command/shell task will be executed. If the file does *not* exist, the task will not be executed. This is less common.
What is the purpose of the register keyword (final revisit)?
  • The register keyword is used to capture the output of a task and store it in a variable.
  • This variable contains details about the task's execution, including whether it changed the system, its standard output (stdout), standard error (stderr), return code (rc), and any errors.
How do you handle sensitive output from tasks (e.g., passwords in logs)?
  • You can use the no_log: true keyword on a task to prevent its output from being displayed in the console logs.
What is the purpose of the check_mode in Ansible (final revisit)?
  • check_mode (enabled with --check) is a mode where Ansible runs tasks without actually making changes to the managed nodes.
  • Modules that support check mode will report what changes *would* be made.
  • It's useful for validating Playbooks and understanding their impact.
What is the purpose of the diff flag (final revisit)?
  • The --diff flag shows the differences in files that would be copied or templated when running in check mode or when changes are made.
  • It helps visualize the impact of file-related tasks.
What are some common use cases for Ansible?
  • Configuration Management
  • Application Deployment
  • Task Automation
  • Orchestration
  • Cloud Provisioning
  • Security Automation
  • Network Automation
How do you ensure your Playbooks are idempotent?
  • Use Ansible modules whenever possible, as they are designed to be idempotent.
  • When using command or shell, use creates or removes where appropriate.
  • Use the state parameter in modules (e.g., present, absent, latest) to define the desired state.
What are some best practices for writing Ansible Playbooks?
  • Use Roles to organize your Playbooks.
  • Use descriptive names for tasks and plays.
  • Keep tasks small and focused.
  • Use variables effectively.
  • Manage secrets with Ansible Vault.
  • Test your Playbooks (using --check, --syntax-check, and potentially Molecule).
  • Follow a consistent coding style.
What is the purpose of the ansible-lint tool?
  • ansible-lint is a linter for checking Ansible Playbooks, roles, and collections for syntax errors, best practices violations, and potential issues.
  • It helps maintain code quality and consistency.
What is the purpose of the molecule framework?
  • Molecule is a testing framework for testing Ansible roles and collections.
  • It automates the process of creating test environments (e.g., using Docker or Vagrant), converging the role/collection on the test instances, and running tests (e.g., using Testinfra or Ansible's built-in tests).
What is the purpose of the become_user keyword (final revisit)?
  • become_user specifies the user to become (switch to) after connecting to the managed node using become: true.
  • The default is typically root.
What is the purpose of the become_method keyword (final revisit)?
  • become_method specifies the method to use for privilege escalation (e.g., sudo, su, pbrun).
  • The default is typically sudo.
What is the purpose of the become_flags keyword (final revisit)?
  • become_flags specifies additional flags to pass to the privilege escalation command (e.g., -i for interactive sudo).
What is the purpose of the any_errors_fatal keyword (final revisit)?
  • any_errors_fatal: true stops the entire Playbook execution immediately if any task on any host fails within that play.
  • By default, Ansible continues with other hosts in the batch even if one fails.
What is the purpose of the run_once keyword (final revisit)?
  • run_once: true executes a task only once on the first host in the current batch of hosts, even if the play targets multiple hosts.
  • This is useful for tasks that should only be performed a single time, such as creating a database or running a migration.
What is the purpose of the local_action keyword (final revisit)?
  • local_action is a shorthand for delegate_to: localhost.
  • It executes a task on the control node where the Playbook is being run.
What is the purpose of the poll keyword in a task (final revisit)?
  • poll controls how often Ansible checks the status of a task when using asynchronous execution.
  • By default, tasks are synchronous (Ansible waits for completion). For long-running tasks, you can make them asynchronous and poll for their status.
What is the purpose of the async keyword in a task (final revisit)?
  • async is used to run a task asynchronously.
  • Ansible will start the task on the managed node and move on to the next task without waiting for the asynchronous task to complete.
  • You typically use async with poll or the async_status module to check the status later.
What is the purpose of the until keyword in a task (final revisit)?
  • until is used with retries and delay to retry a task until a specific condition is met or a maximum number of retries is reached.
  • It's useful for waiting for services to start or for conditions to be true after a change.
What is the purpose of the retries keyword in a task (final revisit)?
  • retries specifies the number of times a task should be retried when used with the until keyword.
What is the purpose of the delay keyword in a task (final revisit)?
  • delay specifies the number of seconds to wait between retries when used with the until and retries keywords.
What is the purpose of the delegate_facts keyword (final revisit)?
  • delegate_facts: true is used in conjunction with delegate_to.
  • It instructs Ansible to store the facts gathered from the delegated host under the original host's facts.
  • This is useful when gathering information about a host from a different machine.