Ansible interview questions
50 questions, 33 with answers. 737 open jobs in India ask for Ansible.
What are playbooks in Ansible?Intermediate
Playbooks are Ansible’s configuration, deployment, and orchestration language.
They can describe a policy you want your remote systems to enforce, or a set of steps in a general IT process. Playbooks are designed to be human-readable and are developed in a basic text language.
At a basic level, playbooks can be used to manage configurations of and deployments to remote machines.
From Test your Sysadmin Skills (MIT)
What's the difference between defaults and vars in an Ansible role?
The Ansible documentation on variable precedence summarizes this nicely:
If multiple variables of the same name are defined in different places, they win in a certain order, which is:
- extra vars (-e in the command line) always win
- then comes connection variables defined in inventory (ansible_ssh_user, etc)
- then comes "most everything else" (command line switches, vars in play, included vars, role vars, etc)
- then comes the rest of the variables defined in inventory
- then comes facts discovered about a system
- then "role defaults", which are the most "defaulty" and lose in priority to everything.
So suppose you have a "tomcat" role that you use to install Tomcat on a bunch of webhosts, but you need different versions of tomcat on a couple hosts, need it to run as different users in other cases, etc. The
defaults/main.ymlfile might look something like this:tomcat_version: 7.0.56 tomcat_user: tomcatSince those are just default values it means they'll be used if those variables aren't defined anywhere else for the host in question. You could override these via extra-vars, via facts in your inventory file, etc. to specify different values for these variables.
Edit: Note that the above list is for Ansible 1.x. In Ansible 2.x the list has been expanded on. As always, the Ansible Documentation provides a detailed description of variable precedence for 2.x.
From Stack Overflow: asked by nwinkler, answered by Bruce P (CC BY-SA 4.0)
Where can I get a list of Ansible pre-defined variables?
From the FAQ:
How do I see a list of all of the ansible_ variables?
Ansible by default gathers “facts” about the machines under management, and these facts can be accessed in playbooks and in templates. To see a list of all of the facts that are available about a machine, you can run the
setupmodule as an ad hoc action:ansible -m setup hostnameThis will print out a dictionary of all of the facts that are available for that particular host. You might want to pipe the output to a pager.This does NOT include inventory variables or internal ‘magic’ variables. See the next question if you need more than just ‘facts’.
Here is the output for my vagrant virtual machine called
scdev:Read the rest at the sourceFrom Stack Overflow: asked by neves, answered by neves (CC BY-SA 4.0)
What's the easy way to auto create non existing dir in ansible?
Right now, this is the only way:
- name: ensures {{ project_root }}/conf dir exists file: path: "{{ project_root }}/conf" state: directory - name: Copy file template: src: code.conf.j2 dest: "{{ project_root }}/conf/code.conf"From Stack Overflow: asked by user1994660, answered by Alexander Jardim (CC BY-SA 4.0)
Ansible Playbooks vs Roles
Playbook vs Role vs [databases] and similar entries in /etc/ansible/hosts
[databases]is a single name for a group of hosts. It allows you to reference multiple hosts by a single name.Role is a set of tasks and additional files to configure host to serve for a certain role.
Playbook is a mapping between hosts and roles.
Example from documentation describes example project. It contains two things:
- Playbooks.
site.yml,webservers.yml,fooservers.ymlare playbooks. - Roles:
roles/common/androles/webservers/contain definitions ofcommonandwebserversroles accordingly.
Inside playbook (
webservers.yml) you have something like:--- - hosts: webservers <- this group of hosts defined in /etc/ansible/hosts, databases and mail_servers in example from your question roles: <- this is list of roles to assign to these hosts - common - webserversIf Playbooks are defined inside of YAML files, then where are Roles defined?
They are defined inside
roles/*directories. Roles are defined mostly using YAML files, but can also contain resources of any types (files/,templates/). According to documentation role definition is structured this way:- If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play
- If roles/x/handlers/main.yml exists, handlers listed therein will be added to the play
- If roles/x/vars/main.yml exists, variables listed therein will be added to the play
- If roles/x/meta/main.yml exists, any role dependencies listed therein will be added to the list of roles (1.3 and later)
- Any copy tasks can reference files in roles/x/files/ without having to path them relatively or absolutely
- Any script tasks can reference scripts in roles/x/files/ without having to path them relatively or absolutely
- Any template tasks can reference files in roles/x/templates/ without having to path them relatively or absolutely
- Any include tasks can reference files in roles/x/tasks/ without having to path them relatively or absolutely
The most important file is
roles/x/tasks/main.yml, here you define tasks, which will be executed, when role is executed.Aside from the ansible.cfg living on the Ansible server, how do I add/configure Ansible with available Playbooks/Roles? For instance, when I run ansible-playbook someplaybook.yaml, how does Ansible know where to find that playbook?
$ ansible-playbook someplaybook.yamlWill look for a playbook inside current directory.
$ ansible-playbook somedir/somedir/someplaybook.yamlWill look for a playbook inside
somedir/somedir/directory.It's your responsibility to put your project with all playbooks and roles on server. Ansible has nothing to do with that.
From Stack Overflow: asked by smeeb, answered by Yaroslav Admin (CC BY-SA 4.0)
- Playbooks.
What is the difference between shell and command in ansible?
According to the documentation :
shell – Execute shell commands on targets
It is almost exactly like the command module but runs the command through a shell (/bin/sh) on the remote node.
and:
command – Execute commands on targets
The command(s) will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use the shell module if you need these features.
From Stack Overflow: asked by prashant, answered by tassinp (CC BY-SA 4.0)
How to create a directory using Ansible?
You want the
ansible.builtin.filemodule. To create a directory, you need to specify the optionstate: directory:- name: Creates directory ansible.builtin.file: path: /src/www state: directoryYou can see other options at https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html
From Stack Overflow: asked by Gaurav Agarwal, answered by leucos (CC BY-SA 4.0)
How can I pass variable to ansible playbook in the command line?
Reading the docs I find the section Passing Variables On The Command Line, that gives this example:
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"Others examples demonstrate how to load from JSON string (≥
1.2) or file (≥1.3)From Stack Overflow: asked by Édouard Lopez, answered by Édouard Lopez (CC BY-SA 4.0)
Specify sudo password for Ansible
You can pass variable on the command line via
--extra-vars "name=value". Sudo password variable isansible_sudo_pass. So your command would look like:ansible-playbook playbook.yml -i inventory.ini --user=username \ --extra-vars "ansible_sudo_pass=yourPassword"Update 2017: Ansible 2.2.1.0 now uses var
ansible_become_pass. Either seems to work.Update 2021: ansible_become_pass is still working, but for now, we should use -e instead of --extra-vars
From Stack Overflow: asked by Slava Fomin, answered by Alexandr Nikitin (CC BY-SA 4.0)
Run command on the Ansible host
Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.
If you want to run an entire play on the Ansible host, then specify
hosts: 127.0.0.1andconnection:localin the play, for example:- name: A play that runs entirely on the Ansible host hosts: 127.0.0.1 connection: local tasks: - name: check out a git repository git: repo: git://foosball.example.org/path/to/repo.git dest: /local/pathSee Local Playbooks in the Ansible documentation for more details.
If you just want to run a single task on your Ansible host, you can use
local_actionto specify that a task should be run locally. For example:- name: An example playbook hosts: webservers tasks: - name: Another task here meta: noop - name: check out a git repository local_action: module: git repo: git://foosball.example.org/path/to/repo.git dest: /local/pathSee "Controlling where tasks run: delegation and local actions" in the Ansible documentation for more details.
You can avoid having to type
connection: localin your play by adding this to your inventory:localhost ansible_connection=local(Here you'd use "
localhost" instead of "127.0.0.1" to refer to the play).In newer versions of Ansible, you no longer need to add the above line to your inventory, Ansible assumes it's already there.
From Stack Overflow: asked by Ross, answered by Lorin Hochstein (CC BY-SA 4.0)
Safely limiting Ansible playbooks to a single machine?
Turns out it is possible to enter a host name directly into the playbook, so running the playbook with
hosts: imac-2.localwill work fine. But it's kind of clunky.A better solution might be defining the playbook's hosts using a variable, then passing in a specific host address via
--extra-vars:# file: user.yml (playbook) --- - hosts: '{{ target }}' user: ...Running the playbook:
ansible-playbook user.yml --extra-vars "target=imac-2.local"If
{{ target }}isn't defined, the playbook does nothing. A group from the hosts file can also be passed through if need be. Overall, this seems like a much safer way to construct a potentially destructive playbook.Playbook targeting a single host:
$ ansible-playbook user.yml --extra-vars "target=imac-2.local" --list-hosts playbook: user.yml play #1 (imac-2.local): host count=1 imac-2.localPlaybook with a group of hosts:
$ ansible-playbook user.yml --extra-vars "target=office" --list-hosts playbook: user.yml play #1 (office): host count=3 imac-1.local imac-2.local imac-3.localForgetting to define hosts is safe!
$ ansible-playbook user.yml --list-hosts playbook: user.yml play #1 ({{target}}): host count=0From Stack Overflow: asked by joemaller, answered by joemaller (CC BY-SA 4.0)
How to move/rename a file using an Ansible task on a remote system?
The file module doesn't copy files on the remote system. The src parameter is only used by the file module when creating a symlink to a file.
If you want to move/rename a file entirely on a remote system then your best bet is to use the command module to just invoke the appropriate command:
- name: Move foo to bar command: mv /path/to/foo /path/to/barIf you want to get fancy then you could first use the stat module to check that foo actually exists:
- name: stat foo stat: path=/path/to/foo register: foo_stat - name: Move foo to bar command: mv /path/to/foo /path/to/bar when: foo_stat.stat.existsFrom Stack Overflow: asked by Christian Berendt, answered by Bruce P (CC BY-SA 3.0)
How to run only one task in ansible playbook?
You should use
tags:as documented in https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.htmlIf you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.
Both plays and tasks support a “tags:” attribute for this reason.
Example:
tasks: - yum: name={{ item }} state=installed with_items: - httpd - memcached tags: - packages - template: src=templates/src.j2 dest=/etc/foo.conf tags: - configurationIf you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:
ansible-playbook example.yml --tags "configuration,packages"On the other hand, if you want to run a playbook without certain tasks, you could do this:
ansible-playbook example.yml --skip-tags "notification"You may also apply tags to roles:
roles: - { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }And you may also tag basic include statements:
- include: foo.yml tags=web,fooBoth of these have the function of tagging every single task inside the include statement.
From Stack Overflow: asked by Billz, answered by Mxx (CC BY-SA 4.0)
How to ignore ansible SSH authenticity checking?
Two options - the first, as you said in your own answer, is setting the environment variable
ANSIBLE_HOST_KEY_CHECKINGto False.The second way to set it is to put it in an ansible.cfg file, and that's a really useful option because you can either set that globally (at system or user level, in
/etc/ansible/ansible.cfgor~/.ansible.cfg), or in an config file in the same directory as the playbook you are running.To do that, make an
ansible.cfgfile in one of those locations, and include this:[defaults] host_key_checking = FalseYou can also set a lot of other handy defaults there, like whether or not to gather facts at the start of a play, whether to merge hashes declared in multiple places or replace one with another, and so on. There's a whole big list of options here in the Ansible docs.
Edit: a note on security.
SSH host key validation is a meaningful security layer for persistent hosts - if you are connecting to the same machine many times, it's valuable to accept the host key locally.
For longer-lived EC2 instances, it would make sense to accept the host key with a task run only once on initial creation of the instance:
- name: Write the new ec2 instance host key to known hosts connection: local shell: "ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts"There's no security value for checking host keys on instances that you stand up dynamically and remove right after playbook execution, but there is security value in checking host keys for persistent machines. So you should manage host key checking differently per logical environment.
- Leave checking enabled by default (in
~/.ansible.cfg) - Disable host key checking in the working directory for playbooks you run against ephemeral instances (
./ansible.cfgalongside the playbook for unit tests against vagrant VMs, automation for short-lived ec2 instances)
From Stack Overflow: asked by Johan, answered by nikobelia (CC BY-SA 4.0)
- Leave checking enabled by default (in
Ansible: How to delete files and folders inside a directory?
- name: Delete content & directory ansible.builtin.file: state: absent path: /home/mydata/web/Note: this will delete the directory too, but you can re-create it
- name: Re-create web directory ansible.builtin.file: state: directory path: /home/mydata/webFrom Stack Overflow: asked by Abbas, answered by Mohan Kumar P (CC BY-SA 4.0)
How to check if a file exists in Ansible?
You can first check that the destination file exists or not and then make a decision based on the output of its result:
tasks: - name: Check that the somefile.conf exists stat: path: /etc/file.txt register: stat_result - name: Create the file, if it doesnt exist already file: path: /etc/file.txt state: touch when: not stat_result.stat.existsFrom Stack Overflow: asked by E Dine Sh, answered by Arbab Nazar (CC BY-SA 4.0)
ansible: lineinfile for several lines?
You can use the
lineinfilebuilt-in in a loop. Here's an example:- name: Set some kernel parameters lineinfile: dest: /etc/sysctl.conf regexp: "{{ item.regexp }}" line: "{{ item.line }}" loop: - { regexp: '^kernel.shmall', line: 'kernel.shmall = 2097152' } - { regexp: '^kernel.shmmax', line: 'kernel.shmmax = 134217728' } - { regexp: '^fs.file-max', line: 'fs.file-max = 65536' }From Stack Overflow: asked by Michael, answered by Ben Whaley (CC BY-SA 4.0)
How to do multiline shell script in Ansible?
Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:
The
>is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:key: > This text has multiple linesWould assign the value
This text has multiple lines\ntokey.The
|character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:key: | This text has multiple linesWould assign the value
This text\nhas multiple\nlines\ntokey.
You can use this for multiline shell scripts like this:
- name: iterate user groups shell: | groupmod -o -g {{ item['guid'] }} {{ item['username'] }} do_some_stuff_here and_some_other_stuff with_items: "{{ users }}"(Update in 2024: the following is no longer true; Ansible is now less janky.)
There is one caveat: Ansible does some janky manipulation of arguments to the
shellcommand, so while the above will generally work as expected, the following won't:- shell: | cat <<EOF This is a test. EOFAnsible will actually render that text with leading spaces, which means the shell will never find the string
EOFat the beginning of a line. You can avoid Ansible's unhelpful heuristics by using thecmdparameter like this:- shell: cmd: | cat <<EOF This is a test. EOF@JKLaiho points out in a comment that the behavior of
>is perhaps unexpected if you include additional indentation in your string. If you write:key: > this is a testYou will get the value:
"this\n is\n a\n test\n"From Stack Overflow: asked by Subtubes, answered by larsks (CC BY-SA 4.0)
How to test provisioning and configuration in Ansible setup?
Some options out there..
Testing tools: Sorted by github stars
- Serverspec - Ruby, most popular tool out there, built on ruby's rspec
- Goss - YAML, simple, <10MB self-contained binary, extremely fast, can generate tests from system state
- Inspec - Ruby, think of it as an improved serverspec, almost same syntax, made by the chef guys. Built to be easier to extend than serverspec
- Testinfra - Python, has the cool feature of being able to use Ansible's inventory/vars
Major differences between them:
Ultimately, I would suggest spending a day experimenting with all of them to get a feel for them before deciding for yourself.
- With the exception of Goss, all the frameworks can run against a remote machine (ex. over ssh). Goss only runs locally or in docker w/ dgoss.
- All frameworks can be run locally on a server, but require Python or Ruby to be installed or embedded. Inspec provides a self-contained <150MB bundle with an embedded version of ruby. Goss is a single <10MB binary with no external dependencies.
- Goss has built in support for nagios/sensu output, this allows for easier integration with monitoring tools.
- Goss tests tend to be simpler, but less flexible since it's based on YAML. Other frameworks allow you to leverage the full power of the underlying language Python/Ruby to write tests or extend the tool's functionality. (simplicity vs flexibility)
- Goss allows you to generate tests from current system state
- Testinfra to my knowledge is the only one that has built-in support for ansible inventory and variables
- Inspec is backed by Chef
Continuous/divergence testing:
- Chef Compliance - works with inspec to continuously test your servers, paid product
- Goss - Can be easily hooked into Nagios or Sensu. Also, supports exposing server tests as an http endpoint.
Testing harnesses for development:
- kitchen - Testing harness tool, launches instance, runs config management code, runs test suite. Made by the chef guys
- Molecule - Similar to test kitchen, but written specifically for ansible
Full Disclosure: I'm the author of goss
UPDATE: InSpec 4.x or above uses a mixed commercial / open source license - see comments.
From DevOps Stack Exchange: asked by Naphta, answered by Ahmed Elsabbahy (CC BY-SA 4.0)
Is there a way to run with_items loops in parallel in Ansible?
As @webKnja mentioned this is possible with
asyncmode. I have recently discovered it myself and learned that you can use it in 3 different ways depending on your needs.Execute and poll the results, notice the
poll:5, This will poll the results every 5 seconds. You may save some time with this method.- name: My long runing task some_module_name: ip: "{{item.fabric}}" username: "{{user}}" password: "{{password}}" secret: "{{secret}}" loop: "{{zoning_list}}" register: _alias_vc_0 async: 60 poll: 5Fire and forget
poll: 0, This is very quick option since Ansible it's just shooting out those tasks. The down side is that we don't know what was the outcome of the task i.e.changed: True/False. Of course it's a downside if you care about the feedback ;).name: My long runing task some_module_name: ip: "{{item.fabric}}" username: "{{user}}" password: "{{password}}" secret: "{{secret}}" loop: "{{zoning_list}}" register: _alias_vc_0 async: 60 poll: 0Fire and forget with
async_status, the syntax for the task is the same as example 2 whowever it will require additional taskasync_status. This is my favorite since it's relatively fast (faster then normal looping or theexecute and poll) and allows you to capture the feedback although will need to deal with newregisterfor yourasync_task.
retries: 20-- how many attempts before failing.delay: 2-- how many second to wait between polls.- name: My long runing task some_module_name: ip: "{{item.fabric}}" username: "{{user}}" password: "{{password}}" secret: "{{secret}}" loop: "{{zoning_list}}" register: _alias_vc_0 async: 60 poll: 0 - name: Wait for My long running task to finish async_status: id: "{{ item.ansible_job_id }}" #jid: "{{ item.ansible_job_id }}" # ansible version > 2.8 register: _jobs_alias_vc_0 retries: 20 delay: 2 until: _jobs_alias_vc_0.finished loop: "{{_alias_vc_0.results}}"A word of caution, depending on the task yo may not be able to use the
asyncoption. I had examples where I was interacting with system which was not able to handle multiple requests for the same resource. I foundasyncoption best working if I have to perform the same task across multiple hosts. That's where I was able to "save" the most time.Since you posted the link to Ansible documentation in the question I'm not going to do that.
From DevOps Stack Exchange: asked by Peter Turner, answered by MMT (CC BY-SA 4.0)
Where to put ansible-vault password?
The idea is to put all our sensitive data [...]
The meaning of "all" in this sentence should be analyzed very carefully before implementing the solution that you plan.
Ansible vault is a very useful tool, but it should be used only to store secrets that are:
- Specifically needed for the ansible deployments
- Easily made useless to owners that should become unaware of them, but that may illegitimately "remember" them (typically off-boarded employees)
The second point is critical.
Many people, and potentially the whole DevOps team, will have access to the ansible vault password and therefore all the secrets.
Therefore, for all the secrets stored in the vault, a condition should hold for which a person or machine with unauthorized access to them should be incapable of making any use of them if so is desired.
In concrete terms, if you use ansible to deploy a database and its users, you can store the passwords in the vault, but you will have to be very careful (and most likely consider another solution) if that service will be available from the Internet and without the need for any VPN authentication!
Users (DevOps) exposed to the secret, should be incapable of using "remembered" passwords if one security barrier is imposed on them (e.g., VPN access revoked). In addition to this, access to the source code repository (where the vault is stored) should be revoked as well before passwords are changed.
Under these conditions, ansible vault is a very useful tool.
Trying to store a secret that could be used by any person or machine on the Internet in the vault would be instead a mistake (e.g., VPN credentials of users).
Is there any other options, which is the best (and secure) way to store ansible-vault password
Under the conditions from the previous paragraph, I think that a good practice would be:
- Store the vault password in an external secure vault (something like Vault from HashiCorp or any SaaS for credentials management)
- Allow access to the external vault item to DevOps (they will need the password for testing) and the CI/CD system or ansible controller
Keep a convention to use secrets! You will not be able to review changes to the secrets and you will not be able to grep for ansible variables in secrets files! So be thorough since the beginning. A good convention is to name all variables stored in the ansible vault with a
secret_prefix. When you will see something like:postgres.yml:
postgres_password: "{{ secret_postgres_password }}"you will know that the value is stored in the ansible vault.
From DevOps Stack Exchange: asked by storm, answered by Vincenzo Pii (CC BY-SA 3.0)
Can I bypass host key checking in Ansible?
This is typically done by setting the following value in
ansible.cfg:[defaults] host_key_checking = FalseIf you don't want to modify
ansible.cfgyou can set an environment variable like so:export ANSIBLE_HOST_KEY_CHECKING=FalseSource: http://docs.ansible.com/ansible/intro_getting_started.html#host-key-checking
From DevOps Stack Exchange: asked by Peter Turner, answered by Zlemini (CC BY-SA 3.0)
Ansible: What's the difference between task, role, play and playbook?
No, each has a different role and way of working.
Starting with the easy ones:
A playbook is simply a list of plays. The highest level of a playbook YAML is a list, and on that list only two things are accepted: a play definition or the keyword
import_playbook, which imports a list of plays from another playbook file, as if they were defined in that place of the calling file.The playbook is also the only thing that can be called directly from
ansible-playbook.A task is, paraphrasing the manual, 'nothing more than a call to an ansible module'. That call definition, however, knows nothing of on which hosts it is supposed to run on.
The play is the element that ties tasks to the servers where they'll run. The key element here is the mandatory keyword
hosts. This is the part of Ansible that tells which hosts are being affected and how.So, the structure and behavior is as follows:
- Playbook: the highest level, just a list of plays
- Play: ties tasks to host lists
- Tasks: definition of a call to a module
- Besides tasks, a play may have pre-tasks, post-tasks and handlers, which are all task-like, and roles.
- Play: ties tasks to host lists
A role is a different thing, as it is not defined within a playbook. Instead, they each have their own subdirectory under the directory
roles. The objective of roles is to organize things. So, under the role's subdir, you can find tasks, handlers, files and templates, variables and defaults. All of these related to that specific role.So, roles are an easy way to encapsulate and share Ansible information. You could have a subdir in
templatesper task, for example. But if you wanted to share that task, you'd have to pick the template as well. With roles, you can just zip the role dir and (almost) everything should be there.Like a play, the role defines tasks and handlers. However, roles do not define on which hosts the role will be run. So roles must be referenced to from a play.
Roles can also declare dependencies (that is, references to other roles that need to be run before the declaring one).
PS1. Most of this information is available piecemeal on SO (except for playbooks, I couldn't find a proper definition of that on the documentation or elsewhere in the Internet), but I haven't found a comparison between them all, and it took me some time to figure this all out, so I'm sharing that by answering my own question.
PS2. I really don't like the fact that roles are named 'roles'. It sounds a bit counter intuitive to me. The word 'role' alone alludes to user roles or server roles, to me. So something more related to Tower (users) or inventory (servers). I think the rationale for that naming is that they define 'one of the roles that a server functions'. Same could be said of plays, but roles are more abstract as they're not tied to specific hosts. Still, I find that naming confusing.
Edit
A handler functions for the most part just like a task. However, it is not executed by default, with the other tasks, during the playbook run. Instead, each individual handler will be executed only if notified by a task.
On a task definition, the keyword
notifyidentifies the handlers the task wants to notify. If the task is executed and reports achangedstate (notoknorfailed), then the handler will be marked for execution.After all roles and tasks have run, each notified handler will be executed, in the order they appear in the file. Check the docs for details.
Read the rest at the sourceFrom DevOps Stack Exchange: asked by caxcaxcoatl, answered by caxcaxcoatl (CC BY-SA 4.0)
- Playbook: the highest level, just a list of plays
Ansible: Other option available for telnet check of open ports?
You can use the Ansible wait_for module which checks a specific TCP port is open.
Since in this case, all ports should be open already, we can use a minimal no. of retries, just enough to cover network issues:
- name: Check all port numbers are accessible from the current host wait_for: host: mywebserver.com port: "{{ item }}" state: started # Port should be open delay: 0 # No wait before first check (sec) timeout: 3 # Stop checking after timeout (sec) ignore_errors: yes with_items: - 443 - 80 - 80443By default, Ansible will check once every second (configurable in Ansible 2.3 using the
sleepattribute), so this will check 3 times per port.Run this in a playbook against your inventory of 400+ hosts - Ansible will check in parallel that all hosts can reach
mywebserver.comon those ports.- the parallelism is subject to the forks setting in your
ansible.cfg.
We use
ignore_errors: yeshere so that any errors are marked in red but do not stop execution.Open ports are reported as
okitems in output and closed ports are reported asfailed(you must use-vvflag onansible-playbookto see this output).Fine-tuning output
If you want more specific output for the success and failure cases, the code must be more complex, adding a second task:
wait_fortask mustregistera variable- the second task produces output using
debugbased on success/failure condition (e.g. using Jinja2 conditional expression) - then you need to put both these tasks in an include file (without any
with_itemsloop), and write a main playbook task that uses aninclude...with_itemsto call the include file once per port.
From DevOps Stack Exchange: asked by AWhitaker, answered by RichVel (CC BY-SA 4.0)
- the parallelism is subject to the forks setting in your
Execute multiple Ansible tasks with the same list of items
Make separate tasks file
make_site.yml:--- - name: Install apache site conf template: src: apache-sites-{{ site }}-conf.j2 dest: /etc/apache2/sites-available/{{ site }}.conf mode: 0644 - name: Enable site apache conf command: a2ensite {{ site }} args: creates: /etc/apache2/sites-enabled/{{ site }}.confAnd in your playbook:
- include_tasks: make_site.yml with_items: - sitea - siteb - sitec - sited loop_control: loop_var: siteFrom DevOps Stack Exchange: asked by Stephen Ostermiller, answered by Konstantin Suvorov (CC BY-SA 3.0)
What is Ansible's config equivalent of `--vault-password-file`?
Here is the definition:
DEFAULT_VAULT_PASSWORD_FILE = get_config(p, DEFAULTS, 'vault_password_file', \ 'ANSIBLE_VAULT_PASSWORD_FILE', None, value_type='path')This means that you either put in ansible.cfg or playbook:
vault_password_file: ~/.vault_pass.txtOr in your shell defined this variable:
export ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass.txtFrom DevOps Stack Exchange: asked by 030, answered by Jiri Klouda (CC BY-SA 3.0)
Git clean/smudge filters for ansible vault secrets
The problem here is caused by the random salt in ansible-vault encryption. You can hack VaultEditor class to pass the salt to it from an argument in ansible-vault. The random salt is generated in
lib/ansible/parsing/vault/__init__.pyon this line. It is called from lib/ansible/cli/vault.py where you can easily add the argument for fixed salt. If you do change it, please submit an upstream patch to Ansible, I'd love to use it.This problem is further discussed here on hacker news. And there are other implementations with tools that take fixed salt, namely gitcrypt, transcrypt. Here is also a link to one more implementation using ansible-vault called ansible-vault-tools, but this one has the same salt issue as far as I know.
From DevOps Stack Exchange: asked by ᴳᵁᴵᴰᴼ, answered by Jiri Klouda (CC BY-SA 3.0)
What are the limitations of Puppet in comparison to Ansible?
There are of course several pro and cons for each of Puppet, Ansible, Chef and add your favorite tool here as well. So I'll try to stay away from opinion, and share what is great in Ansible as a matter of fact.
The main capability that puts Ansible above the others is not having to rely on some custom/additional agent running on the target nodes, instead being founded on ssh connections only. Yes, it still requires an ssh server, Python and a bunch of Python libraries on the nodes, and if your distro of choice (or, good luck, there are some windows nodes) does not ship with them, it will be a little bit painful to bootstrap. But that's unlikely, and may well even make you think again about your distro.
That will simplify monitoring, not eat additional resources, not force the system to run a daemon as root all the time, and in general feels better inside the UNIX philosophy. Chef has
chef-solo, Puppet can be run master-less, but they both work "the other direction," by cloning and via hooks respectively. While with Ansible, a merge in the source repository can trigger the deployment in a fashion we all are comfortable with, be it in Jenkins, in the git master, or in some other tool like Rundeck for instance.From DevOps Stack Exchange: asked by kenorb, answered by ᴳᵁᴵᴰᴼ (CC BY-SA 3.0)
How do I run ansible on one host at a time and break on a failure?
Your playbook will stop when a failure occurs and you're using
serial: 1according to the documentation.By default, Ansible will continue executing actions as long as there are hosts in the group that have not yet failed.
That said there seems to be some confusion in the community over the default behavior, and it seems to have changed--or been buggy--somewhere between 1.8 and 2.1.
So, if
serial: 1doesn't suffice, use this additional setting:max_failure_percentage: 0In some situations, such as with the rolling updates described above, it may be desirable to abort the play when a certain threshold of failures have been reached. To achieve this, as of version 1.3 you can set a maximum failure percentage...
==
As for retrying your playbook, you should be seeing a failure message like this:
to retry, use: --limit @/home/user/site.retryUse that
--limitflag and on your next execution ofansible-playbookand it will continue from where it failed.Retry files will be created unless you've set
retry_files_enabled = Falsein your configuration.Alternatively,
--start-at-taskmay also work.Sources:
https://github.com/ansible/ansible/issues/1663
https://github.com/ansible/ansible/issues/16241
http://docs.ansible.com/ansible/playbooks_delegation.html#rolling-update-batch-size
http://docs.ansible.com/ansible/playbooks_delegation.html#maximum-failure-percentage
http://docs.ansible.com/ansible/intro_configuration.html#retry-files-enabled
http://docs.ansible.com/ansible/playbooks_startnstep.html#start-at-task
From DevOps Stack Exchange: asked by Peter Turner, answered by user132 (CC BY-SA 3.0)
How do I configure SSH keys in a Vagrant multi-machine setup?
Based on techraf's 3rd suggestion I did the following:
vagrant up ansiblessh-keygen(no password just pressed Enter)- copied
.ssh/id_rsaand.ssh/id_rsa.pubto the project directory vagrant destroy ansible- modified the
Vagrantfileto copy theid_rsato all hosts - modified the
Vagrantfileto copy theid_rsa.pubintoauthorized_keyson all hosts - modified the Vagrantfile to disable host checking
Vagrantfile snippet:
config.vm.provision "file", source: "id_rsa", destination: "/home/vagrant/.ssh/id_rsa" public_key = File.read("id_rsa.pub") config.vm.provision :shell, :inline =>" echo 'Copying ansible-vm public SSH Keys to the VM' mkdir -p /home/vagrant/.ssh chmod 700 /home/vagrant/.ssh echo '#{public_key}' >> /home/vagrant/.ssh/authorized_keys chmod -R 600 /home/vagrant/.ssh/authorized_keys echo 'Host 192.168.*.*' >> /home/vagrant/.ssh/config echo 'StrictHostKeyChecking no' >> /home/vagrant/.ssh/config echo 'UserKnownHostsFile /dev/null' >> /home/vagrant/.ssh/config chmod -R 600 /home/vagrant/.ssh/config ", privileged: falseFrom DevOps Stack Exchange: asked by opticyclic, answered by opticyclic (CC BY-SA 4.0)
After the last page: 17 questions more, without answers. Go to the last page
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Tech Vaultby moabukar and contributorsApache 2.016 questions
- Test your Sysadmin Skillsby trimstray and contributorsMIT, © 2017 trimstray1 question
- Linux Sysadmin Interview Questionsby chassing and contributorsPublic domain (Unlicense)1 question
- Stack Overflowby its contributors, named on each answerCC BY-SA17 questions
- DevOps Stack Exchangeby its contributors, named on each answerCC BY-SA15 questions