question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
How do you create a directory www at /srv on a Debian-based system using an Ansible playbook?
| You want the ansible.builtin.file module. To create a directory, you need to specify the option state: directory:
- name: Creates directory
ansible.builtin.file:
path: /src/www
state: directory
You can see other options at https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html
| Ansible | 22,844,905 | 508 |
How do I specify a sudo password for Ansible in non-interactive way?
I'm running Ansible playbook like this:
$ ansible-playbook playbook.yml -i inventory.ini \
--user=username --ask-sudo-pass
But I want to run it like this:
$ ansible-playbook playbook.yml -i inventory.ini \
--user=username` **--sudo-pass=12345... | The docs strongly recommend against setting the sudo password in plaintext:
As a reminder passwords should never be stored in plain text. For information on encrypting your passwords and other secrets with Ansible Vault, see Encrypting content with Ansible Vault.
Instead you should be using --ask-become-pass on the c... | Ansible | 21,870,083 | 297 |
Is it possible to run commands on the Ansible controller node?
My scenario is that I want to take a checkout from a git server that is hosted internally (and isn't accessible outside the company firewall). Then I want to upload the checkout (tarballed) to the production server (hosted externally).
At the moment, I'm lo... | 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.1 and connection:local in the play, for example:
- name: a ... | Ansible | 18,900,236 | 296 |
How can one pass variable to ansible playbook in the command line?
The following command didn't work:
$ ansible-playbook -i '10.0.0.1,' yada-yada.yml --tags 'loaddata' django_fixtures="tile_colors"
Where django_fixtures is my variable.
| 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)
| Ansible | 30,662,069 | 295 |
I'm using Ansible for some simple user management tasks with a small group of computers. Currently, I have my playbooks set to hosts: all and my hosts file is just a single group with all machines listed:
# file: hosts
[office]
imac-1.local
imac-2.local
imac-3.local
I've found myself frequently having to target a sing... | Turns out it is possible to enter a host name directly into the playbook, so running the playbook with hosts: imac-2.local will 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 (play... | Ansible | 18,195,142 | 277 |
How is it possible to move/rename a file/directory using an Ansible module on a remote system? I don't want to use the command/shell tasks and I don't want to copy the file from the local system to the remote system.
| From version 2.0, in copy module you can use remote_src parameter.
If True it will go to the remote/target machine for the src.
- name: Copy files from foo to bar
copy: remote_src=True src=/path/to/foo dest=/path/to/bar
If you want to move file you need to delete old file with file module
- name: Remove old files fo... | Ansible | 24,162,996 | 266 |
Is there a way to only run one task in ansible playbook?
For example, in roles/hadoop_primary/tasks/hadoop_master.yml. I have "start hadoop job tracker services" task. Can I just run that one task?
hadoop_master.yml file:
# Playbook for Hadoop master servers
- name: Install the namenode and jobtracker packages
apt... | You should use tags: as documented in https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html
If 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.
Exa... | Ansible | 23,945,201 | 252 |
Is there a way to ignore the SSH authenticity checking made by Ansible? For example when I've just setup a new server I have to answer yes to this question:
GATHERING FACTS ***************************************************************
The authenticity of host 'xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx)' can't be established.
... | Two options - the first, as you said in your own answer, is setting the environment variable ANSIBLE_HOST_KEY_CHECKING to 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.cfg ... | Ansible | 32,297,456 | 250 |
When creating a new Ansible role, the template creates both a vars and a defaults directory with an empty main.yml file. When defining my role, I can place variable definitions in either of these, and they will be available in my tasks.
What's the difference between putting the definitions into defaults and vars? What ... | 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... | Ansible | 29,127,560 | 212 |
right now I am using a shell script in ansible that would be much more readable if it was on multiple lines
- name: iterate user groups
shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} ....more stuff to do
with_items: "{{ users }}"
Just not sure how to allow multiline script in Ansible shell module ... | 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
lines
Would assign the value This text has multiple lines\n to key.
The | character is a... | Ansible | 40,230,184 | 193 |
A recurring theme that's in my ansible playbooks is that I often must execute a command with sudo privileges (sudo: yes) because I'd like to do it for a certain user. Ideally I'd much rather use sudo to switch to that user and execute the commands normally. Because then I won't have to do my usual post commands clean u... | With Ansible 1.9 or later
Ansible uses the become, become_user, and become_method directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.
- name: checkout repo
git: repo=https://github.com/some/repo.git version=... | Ansible | 21,344,777 | 191 |
I see that Ansible provide some pre-defined variables that we can use in playbooks and template files. For example, the host IP address is ansible_eth0.ipv4.address. Googleing and searching the docs I couldn't find a list of all available variables.
Would someone list them for me?
| 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 setup module as an ad hoc acti... | Ansible | 18,839,509 | 189 |
I'm setting up an Ansible playbook to set up a couple servers. There are a couple of tasks that I only want to run if the current host is my local dev host, named "local" in my hosts file. How can I do this? I can't find it anywhere in the documentation.
I've tried this when statement, but it fails because ansible_host... | The necessary variable is inventory_hostname.
- name: Install this only for local dev machine
pip:
name: pyramid
when: inventory_hostname == "local"
It is somewhat hidden in the documentation at the bottom of this section.
| Ansible | 21,346,390 | 187 |
I'm customizing linux users creation inside my role. I need to let users of my role customize home_directory, group_name, name, password.
I was wondering if there's a more flexible way to cope with default values.
I know that the code below is possible:
- name: Create default
user:
name: "default_name"
when: ... | You can use Jinja's default:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
| Ansible | 35,105,615 | 181 |
I am looking for a way to perform a task when Ansible variable is not registers or undefined.
E.g.:
- name: some task
command: sed -n '5p' "{{app.dirs.includes}}/BUILD.info" | awk '{print $2}'
when: (! deployed_revision) AND ( !deployed_revision.stdout )
register: deployed_revision
| From the ansible documentation:
If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:
- name: Run the command if "foo" is defined
ansible.builtin.shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- name: Fa... | Ansible | 30,119,973 | 177 |
Is there an Ansible variable that has the absolute path to the current playbook that is executing?
Some context: I'm running/creating an Ansible script against localhost to configure a MySQL Docker container and wanting to mount the data volume relative to the Ansible playbook.
For example, let's say I've checkout a re... | You can use the playbook_dir variable.
See the documentation about special variables.
For example, given the file structure:
.
├── foo
│ └── bar.txt
└── playbook.yml
When running playbook.yml, the task:
- ansible.builtin.debug:
var: "(playbook_dir ~ '/foo/bar.txt') is file"
Would give:
TASK [ansible.builtin.de... | Ansible | 30,787,273 | 165 |
How do you get the current host's IP address in a role?
I know you can get the list of groups the host is a member of and the hostname of the host but I am unable to find a solution to getting the IP address.
You can get the hostname by using {{inventory_hostname}} and the group by using {{group_names}}
I have tried th... | A list of all addresses is stored in a fact ansible_all_ipv4_addresses, a default address in ansible_default_ipv4.address.
---
- hosts: localhost
connection: local
tasks:
- debug: var=ansible_all_ipv4_addresses
- debug: var=ansible_default_ipv4.address
Then there are addresses assigned to each network inte... | Ansible | 39,819,378 | 165 |
I would like to use ansible-playbook command instead of 'vagrant provision'. However setting host_key_checking=false in the hosts file does not seem to work.
# hosts file
vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
ansible_ssh_user=vagrant ansible_ssh_port=2222 ansible_ssh_host=127.0.0.1
h... | Due to the fact that I answered this in 2014, I have updated my answer to account for more recent versions of ansible.
Yes, you can do it at the host/inventory level (Which became possible on newer ansible versions) or global level:
inventory:
Add the following.
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
ho... | Ansible | 23,074,412 | 164 |
When Ansible has problems running plays against a host, it will output the name of the host into a file in the user's home directory ending in '.retry'. These are often not used and just cause clutter, is there a way to turn them off or put them in a different directory?
| There are two options that you can add to the [defaults] section of the ansible.cfg file that will control whether or not .retry files are created and where they are created.
[defaults]
...
retry_files_enabled = True # Create them - the default
retry_files_enabled = False # Do not create them
retry_files_save_path = ... | Ansible | 31,318,881 | 161 |
Hi I am trying to find out how to set environment variable with Ansible.
something that a simple shell command like this:
EXPORT LC_ALL=C
tried as shell command and got an error
tried using the environment module and nothing happend.
what am I missing
| There are multiple ways to do this and from your question it's nor clear what you need.
1. If you need environment variable to be defined PER TASK ONLY, you do this:
- hosts: dev
tasks:
- name: Echo my_env_var
shell: "echo $MY_ENV_VARIABLE"
environment:
MY_ENV_VARIABLE: whatever_value
- ... | Ansible | 27,733,511 | 158 |
This is a fragment of a playbook that I'm using (server.yml):
- name: Determine Remote User
hosts: web
gather_facts: false
roles:
- { role: remote-user, tags: [remote-user, always] }
My hosts file has different groups of servers, e.g.
[web]
x.x.x.x
[droplets]
x.x.x.x
Now I want to execute ansible-playbook ... | I don't think Ansible provides this feature, which it should. Here's something that you can do:
hosts: "{{ variable_host | default('web') }}"
and you can pass variable_host from either command-line or from a vars file, e.g.:
ansible-playbook server.yml --extra-vars "variable_host=newtarget(s)"
| Ansible | 33,222,641 | 156 |
What is the easiest way to create an empty file using Ansible? I know I can save an empty file into the files directory and then copy it to the remote host, but I find that somewhat unsatisfactory.
Another way is to touch a file on the remote host:
- name: create fake 'nologin' shell
file: path=/etc/nologin state=tou... | The documentation of the file module says:
If state=file, the file will NOT be created if it does not exist, see the copy or template module if you want that behavior.
So we use the copy module, using force: false to create a new empty file only when the file does not yet exist (if the file exists, its content is pre... | Ansible | 28,347,717 | 153 |
I am pulling JSON via the URI module and want to write the received content out to a file. I am able to get the content and output it to the debugger so I know the content has been received, but I do not know the best practice for writing files.
| An important comment from tmoschou:
As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.
For more details see this and an explanation
... | Ansible | 26,638,180 | 146 |
According to the Ansible docs, a Playbook
is:
...the basis for a really simple configuration management and multi-machine deployment system, unlike any that already exist, and one that is very well suited to deploying complex applications.
And, again, according to those same docs, a Role
are:
...ways of automaticall... |
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 ro... | Ansible | 32,101,001 | 141 |
I have an ansible task which creates a new user on ubuntu 12.04;
- name: Add deployment user
action: user name=deployer password=mypassword
it completes as expected but when I login as that user and try to sudo with the password I set it always says it's incorrect. What am I doing wrong?
| Recently I figured out that Jinja2 filters have the capability to handle the generation of encrypted passwords. In my main.yml I'm generating the encrypted password as:
- name: Creating user "{{ uusername }}" with admin access
user:
name: "{{ uusername }}"
password: "{{ upassword | password_hash('sha512') }}... | Ansible | 19,292,899 | 134 |
I'm using the ec2 module with ansible-playbook I want to set a variable to the contents of a file. Here's how I'm currently doing it.
Var with the filename
shell task to cat the file
use the result of the cat to pass to the ec2 module.
Example contents of my playbook.
vars:
amazon_linux_ami: "ami-fb8e9292"
user_d... | You can use lookups in Ansible in order to get the contents of a file on local machine, e.g.
user_data: "{{ lookup('file', user_data_file) }}"
Caveat: This lookup will work with local files, not remote files.
Here's a complete example from the docs:
- hosts: all
vars:
contents: "{{ lookup('file', '/etc/foo.txt'... | Ansible | 24,003,880 | 133 |
Inside my playbook I'd like to create a variable holding the output of an external command. Afterwards I want to make use of that variable in a couple of templates.
Here are the relevant parts of the playbook:
tasks:
- name: Create variable from command
command: "echo Hello"
register: command_output... | You have to store the content as a fact:
- set_fact:
string_to_echo: "{{ command_output.stdout }}"
| Ansible | 36,059,804 | 133 |
I'd like to able to run an ansible task only if the host of the current playbook does not belong to a certain group. In semi pseudo code:
- name: my command
command: echo stuff
when: "if {{ ansible_hostname }} not in {{ ansible_current_groups }}"
How should I do this?
| Here's another way to do this:
- name: my command
command: echo stuff
when: "'groupname' not in group_names"
group_names is a magic variable as documented here:
List of groups the current host is part of, it always reflects the inventory_hostname and ignores delegation.
| Ansible | 21,008,083 | 131 |
I'm scripting a deployment process that takes the name of the user running the ansible script (e.g. tlau) and creates a deployment directory on the remote system based on that username and the current date/time (e.g. tlau-deploy-2014-10-15-16:52).
You would think this is available in ansible facts (e.g. LOGNAME or SUDO... | If you gather_facts, which is enabled by default for playbooks, there is a built-in variable that is set called ansible_user_id that provides the user name that the tasks are being run as. You can then use this variable in other tasks or templates with {{ ansible_user_id }}. This would save you the step of running a ... | Ansible | 26,394,096 | 124 |
My use case is the following :
I have a template file, and I would like to create 2 different files from that template, with the variables being filled by a different set of variables for each file.
For example, lets say I want to template the file containing the line:
mkdir -p {{myTemplateVariable}}
I would like to... | With Ansible 2.x you can use vars: with tasks.
Template test.j2:
mkdir -p {{myTemplateVariable}}
Playbook:
- template: src=test.j2 dest=/tmp/File1
vars:
myTemplateVariable: myDirName
- template: src=test.j2 dest=/tmp/File2
vars:
myTemplateVariable: myOtherDir
This will pass different myTemplateVariable v... | Ansible | 31,142,369 | 123 |
How to escape double curly braces in Ansible 1.9.2?
For instance, how can I escape double curly braces in the following shell command?
- name: Test
shell: "docker inspect --format '{{ .NetworkSettings.IPAddress }}' instance1"
| Whenever you have problems with conflicting characters in Ansible, a rule of thumb is to output them as a string in a Jinja expression.
So instead of {{ you would use {{ '{{' }}:
- debug: msg="docker inspect --format '{{ '{{' }} .NetworkSettings.IPAddress {{ '}}' }}' instance1"
Topic "Escaping" in the Jinja2 docs.
| Ansible | 32,279,519 | 120 |
Say I execute the following.
$ cat test.sh
#!/bin/bash
echo Hello World
exit 0
$ cat Hello.yml
---
- hosts: MyTestHost
tasks:
- name: Hello yourself
script: test.sh
$ ansible-playbook Hello.yml
PLAY [MyTestHost] ****************************************************************
GATHERING FACTS ************... | If you pass the -v flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:
$ ansible-playbook -v playbook.yaml
Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:
[defaults]
log_path=/path/to/logfile
Ansible will lo... | Ansible | 18,794,808 | 114 |
I have a copy task inside a role and I was expecting that the src location would be relative to the role itself, not the playbook that calls the roles.
How do I make this work and use the files from myfrole/files from a task inside myrole/tasks, I don't want to include the role name as part of the path as it does not m... | If you do not provide any path at all, just the filename, Ansible will pick it automatically from the files directory of the role.
- copy:
src: foo.conf
dest: /etc/foo.conf
Additionally, since Ansible 1.8, there is the variable role_path which you could use in your copy task.
- copy:
src: "{{ role_path }}/... | Ansible | 35,487,756 | 114 |
I tried this:
- command: ./configure chdir=/src/package/
- command: /usr/bin/make chdir=/src/package/
- command: /usr/bin/make install chdir=/src/package/
which works, but I was hoping for something neater.
So I tried this:
from: https://stackoverflow.com/questions/24043561/multiple-commands-in-the-same-line-for-bruke... | To run multiple shell commands with ansible you can use the shell module with a multi-line string (note the pipe after shell:), as shown in this example:
- name: Build nginx
shell: |
cd nginx-1.11.13
sudo ./configure
sudo make
sudo make install
| Ansible | 24,851,575 | 112 |
I have variable named "network" registered in Ansible:
{
"addresses": {
"private_ext": [
{
"type": "fixed",
"addr": "172.16.2.100"
}
],
"private_man": [
{
"type": "... | To filter a list of dicts you can use the selectattr filter together with the equalto test:
network.addresses.private_man | selectattr("type", "equalto", "fixed")
The above requires Jinja2 v2.8 or later (regardless of Ansible version).
Ansible also has the tests match and search, which take regular expressions:
matc... | Ansible | 31,895,602 | 112 |
I can do that with shell using combination of getent and awk like this:
getent passwd $user | awk -F: '{ print $6 }'
For the reference, in Puppet I can use a custom fact, like this:
require 'etc'
Etc.passwd { |user|
Facter.add("home_#{user.name}") do
setcode do
user.dir
end
end
}
which m... | Ansible (from 1.4 onwards) already reveals environment variables for the user under the ansible_env variable.
- hosts: all
tasks:
- name: debug through ansible.env
debug: var=ansible_env.HOME
Unfortunately you can apparently only use this to get environment variables for the connected user as this playbook... | Ansible | 33,343,215 | 104 |
I'm trying to use Ansible to run the following two commands:
sudo apt-get update && sudo apt-get upgrade -y
I know with ansible you can use:
ansible all -m shell -u user -K -a "uptime"
Would running the following command do it? Or do I have to use some sort of raw command
ansible all -m shell -u user -K -a "sudo apt-g... | I wouldn't recommend using shell for this, as Ansible has the apt module designed for just this purpose. I've detailed using apt below.
In a playbook, you can update and upgrade like so:
- name: Update and upgrade apt packages
become: true
apt:
upgrade: yes
update_cache: yes
cache_valid_time: 86400 #One... | Ansible | 41,535,838 | 102 |
- name: Go to the folder
command: chdir=/opt/tools/temp
When I run my playbook, I get:
TASK: [Go to the folder] *****************************
failed: [host] => {"failed": true, "rc": 256}
msg: no command given
Any help is much appreciated.
| There's no concept of current directory in Ansible. You can specify current directory for specific task, like you did in your playbook. The only missing part was the actual command to execute. Try this:
- name: Go to the folder and execute command
command: chdir=/opt/tools/temp ls
| Ansible | 19,369,931 | 97 |
I have been waiting for ansible 2.3 as it was going to introduce encrypt_string feature.
Unfortuately I'm not sure how can I read the encrypted string.
I did try decrypt_string, decrypt (the file), view (the file) and nothing works.
cat test.yml
---
test: !vault |
$ANSIBLE_VAULT;1.1;AES256
373666383633623038... | You can also do with plain ansible command for respective host/group/inventory combination, e.g.:
$ ansible my_server -m debug -a 'var=my_secret'
my_server | SUCCESS => {
"my_secret": "373861663362363036363361663037373661353137303762"
}
| Ansible | 43,467,180 | 97 |
In response to a change, I have multiple related tasks that should run.
How do I write an Ansible handler with multiple tasks?
For example, I would like a handler that restarts a service only if already started:
- name: Restart conditionally
shell: check_is_started.sh
register: result
- name: Restart conditionally... | There is proper solution to this problem as of Ansible 2.2.
handlers can also “listen” to generic topics, and tasks can notify those topics as follows:
handlers:
- name: restart memcached
service: name=memcached state=restarted
listen: "restart web services"
- name: restart apache
service: nam... | Ansible | 31,618,967 | 94 |
In Ansible (1.9.4) or 2.0.0
I ran the following action:
- debug: msg="line1 \n {{ var2 }} \n line3 with var3 = {{ var3 }}"
$ cat roles/setup_jenkins_slave/tasks/main.yml
- debug: msg="Installing swarm slave = {{ slave_name }} at {{ slaves_dir }}/{{ slave_name }}"
tags:
- koba
- debug: msg="1 == Slave properties... | debug module support array, so you can do like this:
debug:
msg:
- "First line"
- "Second line"
The output:
ok: [node1] => {
"msg": [
"First line",
"Second line"
]
}
Or you can use the method from this answer:
In YAML, how do I break a string over multiple lines?
| Ansible | 34,188,167 | 92 |
I'm designing a kind of playbook lib with individual tasks
so in the usual roles repo, I have something like:
roles
├── common
│ └── tasks
│ ├── A.yml
│ ├── B.yml
│ ├── C.yml
│ ├── D.yml
│ ├── login.yml
│ ├── logout.yml
│ └── save.yml
├── custom_stuff_workflow
│ └── tasks
│... | Just in case someone else bumps into this, version 2.2 of Ansible now has include_role. You can now do something like this:
---
- name: do something
include_role:
name: common
tasks_from: login
Check out the documentation here.
| Ansible | 30,192,490 | 91 |
In Ansible I've used register to save the results of a task in the variable people. Omitting the stuff I don't need, it has this structure:
{
"results": [
{
"item": {
"name": "Bob"
},
"stdout": "male"
},
{
"item": {
... | I think I got there in the end.
The task is like this:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
It loops through each of the dicts (item) in the people.results array, each time creating a new dict like ... | Ansible | 35,605,603 | 87 |
I am planning to execute a shell script on a remote server using Ansible playbook.
blank test.sh file:
touch test.sh
Playbook:
---
- name: Transfer and execute a script.
hosts: server
user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
... | you can use script module
Example
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Copy and Execute the script
script: /home/user/userScript.sh
| Ansible | 21,160,776 | 86 |
I'm using Ansible to copy a directory (900 files, 136MBytes) from one host to another:
---
- name: copy a directory
copy: src={{some_directory}} dest={{remote_directory}}
This operation takes an incredible 17 minutes, while a simple scp -r <src> <dest> takes a mere 7 seconds.
I have tried the Accelerated mode, w... | TLDR: use synchronize instead of copy.
Here's the copy command I'm using:
- copy: src=testdata dest=/tmp/testdata/
As a guess, I assume the sync operations are slow. The files module documentation implies this too:
The "copy" module recursively copy facility does not scale to lots (>hundreds) of files. For alternativ... | Ansible | 27,985,334 | 85 |
The settings
Consider an Ansible inventory file similar to the following example:
[san_diego]
host1
host2
[san_francisco]
host3
host4
[west_coast]
san_diego
san_francisco
[west_coast:vars]
db_server=foo.example.com
db_host=5432
db_password=top secret password
The problem
I would like to store some of the vars (like... | Since Ansible 2.3 you can encrypt a Single Encrypted Variable.
IMO, a walkthrough is needed as the doco's seem pretty terse.
Given an example of: mysql_password: password123 (within main.yml)
Run a command such as:
ansible-vault encrypt_string password123 --ask-vault-pass
This will produce:
!vault |
$ANSIBLE_VAULT;... | Ansible | 30,209,062 | 85 |
I am using Ansible to deploy my project and I trying to check if an specified package is installed, but I have a problem with it task, here is the task:
- name: Check if python-apt is installed
command: dpkg -l | grep python-apt
register: python_apt_installed
ignore_errors: True
And here is the problem:
$ ansibl... | From the doc:
command - Executes a command on a remote node
The command module takes the command name followed by a list of
space-delimited arguments. The given command will be executed on all
selected nodes. It will not be processed through the shell, so
variables like $HOME and operations like "<", ">", "|", and "&"... | Ansible | 24,679,591 | 83 |
I am trying to copy the content of dist directory to nginx directory.
- name: copy html file
copy: src=/home/vagrant/dist/ dest=/usr/share/nginx/html/
But when I execute the playbook it throws an error:
TASK [NGINX : copy html file] **************************************************
fatal: [172.16.8.200]: FAILED! =>... | To copy a directory's content to another directory you CAN use ansibles copy module:
- name: Copy content of directory 'files'
copy:
src: files/ # note the '/' <-- !!!
dest: /tmp/files/
From the docs about the src parameter:
If (src!) path is a directory, it is copied recursively...
... if path ends with ... | Ansible | 35,488,433 | 82 |
I wonder if there is a way for Ansible to access local environment variables.
The documentation references accessing variable on the target machine:
{{ lookup('env', 'SOMEVAR') }}
Is there a way to access environment variables on the source machine?
| I have a Linux vm running on osx, and for me:
lookup('env', 'HOME') returns "/Users/Gonzalo" (the HOME variable from osx), while ansible_env.HOME returns "/root" (the HOME variable from the vm).
Worth to mention, that ansible_env.VAR fails if the variable does not exists, while lookup('env', 'VAR') does not fail.
| Ansible | 21,422,158 | 81 |
In ansible, I need to check whether a particular line present in a file or not. Basically, I need to convert the following command to an ansible task. My goal is to only check.
grep -Fxq "127.0.0.1" /tmp/my.conf
| Use check_mode, register and failed_when in concert. This fails the task if the lineinfile module would make any changes to the file being checked. Check_mode ensures nothing will change even if it otherwise would.
- name: "Ensure /tmp/my.conf contains '127.0.0.1'"
lineinfile:
name: /tmp/my.conf
line: "127.0.... | Ansible | 30,786,263 | 81 |
I would like to quickly monitor some hosts using commands like ps,dstat etc using ansible-playbook. The ansible command itself perfectly does what I want, for instance I'd use:
ansible -m shell -a "ps -eo pcpu,user,args | sort -r -k1 | head -n5"
and it nicely prints all std output for every host like this:
localhost |... | The debug module could really use some love, but at the moment the best you can do is use this:
- hosts: all
gather_facts: no
tasks:
- shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
register: ps
- debug: var=ps.stdout_lines
It gives an output like this:
ok: [host1] => {
"ps.stdout_lines":... | Ansible | 20,563,639 | 80 |
I'd like to allow anyone to list and read all files in my directory tree, but I don't want to make the files executable :
dir
\subdir1
file1
\subdir2
file2
...
\subdirX
fileX
The following task makes my directories and files readable, but it makes all the files executable as well:
- name: Mak... | Since version 1.8, Ansible supports symbolic modes. Thus, the following would perform the task you want:
- name: Make my directory tree readable
file:
path: dir
mode: u=rwX,g=rX,o=rX
recurse: yes
Because X (instead of x) only applies to directories or files with at least one x bit set.
| Ansible | 28,778,738 | 80 |
How can I test that stderr is non empty::
- name: Check script
shell: . {{ venv_name }}/bin/activate && myscritp.py
args:
chdir: "{{ home }}"
sudo_user: "{{ user }}"
register: test_myscript
- debug: msg='myscritp is Ok'
when: not test_myscript.stderr
So if there is no error I could read::
TASK: [deplo... | (ansible 2.9.6 ansible-lint 5.3.2)
See ansible-lint rules. The condition below results in error: 'empty-string-compare: Don't compare to empty string'
when: test_myscript.stderr != ""
Correct syntax is
when: test_myscript.stderr | length > 0
Quoting from source code
Use when: var|length > 0 rather than when:... | Ansible | 36,912,726 | 80 |
Recently I started digging into Ansible and writing my own playbooks. However, I have a troubles with understanding difference between become and become_user.
As I understand it become_user is something similar to su <username>, and become means something like sudo su or "perform all commands as a sudo user". But some... | become_user defines the user which is being used for privilege escalation.
become simply is a flag to either activate or deactivate the same.
Here are three examples which should make it clear:
This task will be executed as root, because root is the default user for privilege escalation:
- do: something
become: true... | Ansible | 38,290,143 | 80 |
What is the best way to chmod + x a file with ansible.
Converting the following script to ansible format.
mv /tmp/metadata.sh /usr/local/bin/meta.sh
chmod +x /usr/local/bin/meta.sh
This is what I have so far..
- name: move /tmp/metadata.sh to /usr/local/bin/metadata.sh
command: mv /tmp/metadata.sh /usr/local/bin/met... | ansible has mode parameter in file module exactly for this purpose.
To add execute permission for everyone (i.e. chmod a+x on command line):
- name: Changing perm of "/foo/bar.sh", adding "+x"
file: dest=/foo/bar.sh mode=a+x
Symbolic modes are supported since version 1.8, on a prior version you need to use the octal... | Ansible | 40,505,772 | 80 |
I am learning Ansible. I have a playbook to clean up resources, and I want the playbook to ignore every error and keep going on till the end , and then fail at the end if there were errors.
I can ignore errors with
ignore_errors: yes
If it was one task, I could do something like ( from ansible error catching)
- name... | Use Fail module.
Use ignore_errors with every task that you need to ignore in case of errors.
Set a flag (say, result = false) whenever there is a failure in any task execution
At the end of the playbook, check if flag is set, and depending on that, fail the execution
- fail: msg="The execution has failed because of... | Ansible | 38,876,487 | 79 |
In Ansible 2.1, I have a role being called by a playbook that needs access to a host file variable. Any thoughts on how to access it?
I am trying to access the ansible_ssh_host in the test1 section of the following inventory host file:
[test1]
test-1 ansible_ssh_host=abc.def.ghi.jkl ansible_ssh_port=1212
[test2]
test... | You are on the right track about hostvars.
This magic variable is used to access information about other hosts.
hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'], hostvars['test2-1'], etc.
ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you ... | Ansible | 40,027,847 | 79 |
I have a playbook which should configure on specified IP, and than connect to this app to configure stuff inside.
I've got a problem: I need to restart app after I've changed anything in app config, and if I do not restart app, connection to it failed (no connection because app knows nothing about new config with new I... | If you want to force the handler to run in between the two tasks instead of at the end of the play, you need to put this between the two tasks:
- meta: flush_handlers
Example taken from the ansible documentation :
tasks:
- shell: some tasks go here
- meta: flush_handlers
- shell: some other tasks
Note that th... | Ansible | 34,018,862 | 78 |
Recently I created new roles called spd in my existing project. While other script works fine in the setup. This newly created fails. Please point me to what is going wrong here
ansible/roles
spd
tasks
templates
defaults
deploy-spd.yml
- hosts:
roles:
- spd
inventory file
[kube-... | It is the host machine which needs the sshpass program installed. Again, this error message of:
ERROR! to use the 'ssh' connection type with passwords, you must install the sshpass program
Applies to the HOST (provisioner) not the GUEST (machine(s) being provisioned). Thus install sshpass on the provisioner.
Install ... | Ansible | 42,835,626 | 78 |
In my Ansible play I am restarting database then trying to do some operations on it. Restart command returns as soon as restart is started, not when db is up. Next command tries to connect to the database. That command my fail when db is not up.
I want to retry my second command a few times. If last retry fails, I want... | I don't understand your claim that the "first command execution fails whole play". It wouldn't make sense if Ansible behaved this way.
The following task:
- command: /usr/bin/false
retries: 3
delay: 3
register: result
until: result.rc == 0
produces:
TASK [command] **********************************************... | Ansible | 44,134,642 | 77 |
I am trying to get started with Ansible to provision my Vagrantbox, but I can’t figure out how to deal with host files.
According to the documentation the should be storred in /etc/ansible/hosts, but I can’t find this on my system (Mac OS X). I also seen examples where the host.ini file situated in the document root ad... | While Ansible will try /etc/ansible/hosts by default, there are several ways to tell ansible where to look for an alternate inventory file :
use the -i command line switch and pass your inventory file path
add inventory = path_to_hostfile in the [defaults] section of your ~/.ansible.cfg configuration file
use export A... | Ansible | 21,958,727 | 76 |
I would like to use a system fact for a host times a number/percentage as a base for a variable. What I am trying to do specifically is use the ansible_memtotal_mb value and multiply it by .80 to get a ramsize to then use in setting a Couchbase value. I have been trying different variations of the line below. I'm no... | You're really close! I use calculations to set some default java memory sizes, which is similar to what you are doing. Here's an example:
{{ (ansible_memtotal_mb*0.8-700)|int|abs }}
That shows a couple of things- first, it's using jinja math, so do the calculations inside the {{ jinja }}. Second, int and abs do what y... | Ansible | 33,505,521 | 76 |
Recently, in our company, we decided to use Ansible for deployment and continuous integration. But when I started using Ansible I didn't find modules for building Java projects with Maven, or modules for running JUnit tests, or JMeter tests.
So, I'm in a doubtful state: it may be I'm using Ansible in a wrong way.
Whe... | First, Jenkins and Hudson are basically the same project. I'll refer to it as Jenkins below. See How to choose between Hudson and Jenkins?, Hudson vs Jenkins in 2012, and What is the most notable difference between Jenkins and Hudson from a user perpective? for more.
Second, Ansible isn't meant to be a continuous integ... | Ansible | 25,842,718 | 75 |
Here is my problem I need to use one variable 'target_host' and then append '_host' to it's value to get another variable name whose value I need.
If you look at my playbook. Task nbr 1,2,3 fetch the value of variable however nbr 4 is not able to do what I expect. Is there any other way to achieve the same in ansible?... | If you have a variable like
vars:
myvar: xxx
xxx_var: anothervalue
the working Ansible syntax:
- debug: msg={{ vars[myvar + '_var'] }}
will give you the analogue of:
- debug: msg={{ xxx_var }}
| Ansible | 29,276,198 | 74 |
In my playbook, I need to create a symbolic link for a repo.
With command (shell) it may work like this:
########## Create symbolic link
- name: Create symbolic link
shell : ln -s "{{SOURCE_FOLDER}}" SYMLINK
args :
chdir : "/opt/application/i99/"
when:
- ansible_host in groups['ihm']
-> like this ... | Simply:
- name: Create symbolic link
file:
src: "{{SOURCE_FOLDER}}"
dest: "/opt/application/i99/SYMLINK"
state: link
As you can see in the manual for the file module:
src Will accept absolute, relative and nonexisting paths. Relative paths are not expanded.
| Ansible | 48,560,311 | 74 |
I'm trying to execute ansible2 commands...
When I do:
ansible-playbook -vvv -i my/inventory my/playbook.yml
I get:
Unexpected Exception: name 'basestring' is not defined
the full traceback was:
Traceback (most recent call last):
File "/usr/local/bin/ansible-playbook", line 85, in <module>
sys.exit(cli.run()... | Ansible below version 2.5 requires Python 2.6 or 2.7 on the control host: Control Node Requirements
basestring is no longer available in Python 3. From What’s New In Python 3.0:
The builtin basestring abstract type was removed. Use str instead. The str and bytes types don’t have functionality enough in common to warra... | Ansible | 34,803,467 | 73 |
I'm writing an Ansible playbook and have a task which will always fail in check mode:
hosts: ...
tasks:
- set_fact: filename="{{ansible_date_time.iso8601}}"
- file: state=touch name={{filename}}
- file: state=link src={{filename}} dest=latest
In check mode, the file will not be created so the link task wil... | Ansible 2.1 supports ansible_check_mode magic variable which is set to True in check mode (official docs). This means you will be able to do this:
- file:
state: link
src: '{{ filename }}'
dest: latest
when: not ansible_check_mode
or
- file:
state: link
src: '{{ filename }}'
dest: latest
ig... | Ansible | 28,729,567 | 72 |
I'm currently using Ansible 1.7.2. I have the following test playbook:
---
- hosts: localhost
tasks:
- name: set fact 1
set_fact: foo="[ 'zero' ]"
- name: set fact 2
set_fact: foo="{{ foo }} + [ 'one' ]"
- name: set fact 3
set_fact: foo="{{ foo }} + [ 'two', 'three' ]"
- name: set fact 4
s... | There is a workaround which may help. You may "register" results for each set_fact iteration and then map that results to list:
---
- hosts: localhost
tasks:
- name: set fact
set_fact: foo_item="{{ item }}"
with_items:
- four
- five
- six
register: foo_result
- name: make a list
... | Ansible | 29,399,581 | 72 |
Ansible shows an error:
ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.
What is wrong?
The exact transcript is:
ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.
The error appears to have been in 'p... | Reason #1
You are using an older version of Ansible which did not have the module you try to run.
How to check it?
Open the list of modules module documentation and find the documentation page for your module.
Read the header at the top of the page - it usually shows the Ansible version in which the module was introdu... | Ansible | 47,159,193 | 72 |
How can I make Ansible execute a shell script if a (rpm) package is not installed? Is it somehow possible to leverage the yum module?
| I don't think the yum module would help in this case. It currently has 3 states: absent, present, and latest. Since it sounds like you don't want to actually install or remove the package (at least at this point) then you would need to do this in two manual steps. The first task would check to see if the package exi... | Ansible | 21,892,603 | 71 |
Let's imagine an inventory file like this:
node-01 ansible_ssh_host=192.168.100.101
node-02 ansible_ssh_host=192.168.100.102
node-03 ansible_ssh_host=192.168.100.103
node-04 ansible_ssh_host=192.168.100.104
node-05 ansible_ssh_host=192.168.100.105
[mainnodes]
node-[01:04]
In my playbook I now want to create some va... | I find the magic map extract here.
main_nodes_ips: "{{ groups['mainnodes'] | map('extract', hostvars, ['ansible_host']) | join(',') }}"
main_nodes_ips_with_port: "{{ groups['mainnodes'] | map('extract', hostvars, ['ansible_host']) | join(':3000,') }}:3000"
An alternative(idea comes from here):
main_nodes_ips: "{{ grou... | Ansible | 36,328,907 | 70 |
Is there a way to check playbook syntax and variables?
I'm trying to dry-run(--check) but for some reasons it works really slow. It looks like it tries to perform an action instead of just check the syntax
I want to omit en errors like this:
..."msg": "AnsibleUndefinedVariable: ERROR! 'application_name' is undefined"}
... | This is expected behaviour according to the documentation:
When ansible-playbook is executed with --check it will not make any
changes on remote systems. Instead, any module instrumented to support
‘check mode’ (which contains most of the primary core modules, but it
is not required that all modules do this) will repo... | Ansible | 35,339,512 | 69 |
I'm currently building a role for installing PHP using ansible, and I'm having some difficulty merging dictionaries. I've tried several ways to do so, but I can't get it to work like I want it to:
# A vars file:
my_default_values:
key = value
my_values:
my_key = my_value
# In a playbook, I create a task to attem... | In Ansible 2.0, there is a Jinja filter, combine, for this:
- debug: msg="{{ item.key }} = {{ item.value }}"
with_dict: "{{ my_default_values | combine(my_values) }}"
| Ansible | 25,422,771 | 68 |
How would I save a registered Variable to a file? I took this from the tutorial:
- hosts: web_servers
tasks:
- shell: /usr/bin/foo
register: foo_result
ignore_errors: True
- shell: /usr/bin/bar
when: foo_result.rc == 5
How would I save foo_result variable to a file e.g. foo_result.l... | Thanks to tmoschou for adding this comment to an outdated accepted answer:
As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.
For m... | Ansible | 26,732,241 | 68 |
I have a task, that creates a group.
- name: add user to docker group
user: name=USERNAME groups=docker append=yes
sudo: true
In another playbook I need to run a command that relies on having the new group permission. Unfortunately this does not work because the new group is only loaded after I logout and login a... | You can use an (ansible.builtin.)meta: reset_connection task:
- name: Add user to docker group
ansible.builtin.user:
name: USERNAME
groups: docker
append: true
- name: Reset ssh connection to allow user changes to affect ansible user
ansible.builtin.meta:
reset_connection
Note that you can not use... | Ansible | 26,677,064 | 66 |
How should one go about defining a pretask for role dependencies.
I currently have an apache role that has a user variable so in my own role in <role>/meta/main.yml I do something like:
---
dependencies:
- { role: apache, user: proxy }
The problem at this point is that I still don't have the user I specify and when ... | I use the pre_tasks to do some tasks before roles, thanks for Kashyap.
#!/usr/bin/env ansible-playbook
---
- hosts: all
become: true
pre_tasks:
- name: start tasks and sent notifiaction to HipChat
hipchat:
color: purple
token: "{{ hipchat_token }}"
room: "{{ hipchat_room }}"
... | Ansible | 29,258,759 | 66 |
I have an Ansible playbook for deploying a Java app as an init.d daemon.
Being a beginner in both Ansible and Linux I'm having trouble to conditionally execute tasks on a host based on the host's status.
Namely I have some hosts having the service already present and running where I want to stop it before doing anythin... | See the service_facts module, new in Ansible 2.5.
- name: Populate service facts
service_facts:
- debug:
msg: Docker installed!
when: "'docker' in services"
| Ansible | 30,328,506 | 66 |
I generate files with ansible on remote host and after this generation, I would like to read theses files in another task.
I don't find any module to read remote file with ansible (lookup seems only on local host).
Do you know a module like this ?
Thanks
EDIT:
Here is my use case:
I generate ssh keys and I add it to gi... | Either run with the --diff flag (outputs a diff when the destination file changes) ..
ansible-playbook --diff server.yaml
or slurp it up ..
- name: Slurp hosts file
slurp:
src: /etc/hosts
register: slurpfile
- debug: msg="{{ slurpfile['content'] | b64decode }}"
| Ansible | 34,722,761 | 66 |
I have been developing an Ansible playbook for a couple of weeks, therefore, my experience with such technology is relatively short. Part of my strategy includes using a custom ansible_ssh_user for provisioning hosts throughout the inventory, however, such user will need its own SSH key pair, which would involve some s... | It's a bad idea to store any kind of plaintext secret in revision control, SSH private keys included. Instead, use ansible-vault to store the private key.
ansible-vault can operate on any file type. Just encrypt the file with
ansible-vault encrypt /path/to/local/private_key
then install the key:
- name: Install a priv... | Ansible | 29,392,369 | 65 |
I need to create new variable from contents of other variables. Currently I'm using something like this:
- command: echo "{{ var1 }}-{{ var2 }}-{{ var3 }}"
register: newvar
The problem is:
Usage of {{ var1 }}...{{ varN }} brings too long strings and very ugly code.
Usage of {{ newvar.stdout }} a bit better but conf... | Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 ... | Ansible | 31,186,874 | 65 |
I ran into a configuration problem when coding an Ansible playbook for SSH private key files. In static Ansible inventories, I can define combinations of host servers, IP addresses, and related SSH private keys - but I have no idea how to define those with dynamic inventories.
For example:
---
- hosts: tag_Name_server1... | TL;DR: Specify key file in group variable file, since 'tag_Name_server1' is a group.
Note: I'm assuming you're using the EC2 external inventory script. If you're using some other dynamic inventory approach, you might need to tweak this solution.
This is an issue I've been struggling with, on and off, for months, and I... | Ansible | 33,795,607 | 65 |
I'm trying to learn how to use Ansible facts as variables, and I don't get it. When I run...
$ ansible localhost -m setup
...it lists all of the facts of my system. I selected one at random to try and use it, ansible_facts.ansible_date_time.date, but I can't figure out HOW to use it. When I run...
$ ansible localhost ... | The command ansible localhost -m setup basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.
When you run the echo command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-... | Ansible | 31,323,604 | 64 |
I'm trying to use the result of Ansible find module, which return list of files it find on a specific folder.
The problem is, when I iterate over the result, I do not have the file names, I only have their full paths (including the name).
Is there an easy way to use the find_result items below to provide the file_name ... | basename filter?
{{ item.path | basename }}
There are also dirname, realpath, relpath filters.
| Ansible | 45,564,899 | 64 |
I need something like (ansible inventory file):
[example]
127.0.0.1 timezone="Europe/Amsterdam" locales="en_US","nl_NL"
However, ansible does not recognize 'locales' as a list.
| You can pass a list or object like this:
[example]
127.0.0.1 timezone="Europe/Amsterdam" locales='["en_US", "nl_NL"]'
| Ansible | 18,572,092 | 63 |
The playbook looks like:
- hosts: all
tasks:
- name: "run on all hosts,1"
shell: something1
- name: "run on all hosts,2"
shell: something2
- name: "run on one host, any host would do"
shell: this_command_should_run_on_one_host
- name: "run on all hosts,3"
shell: something3
I k... | For any host (with defaults it will match the first on the list):
- name: "run on first found host"
shell: this_command_should_run_on_one_host
run_once: true
For a specific host:
- name: "run on that_one_host host"
shell: this_command_should_run_on_one_host
when: ansible_hostname == 'that_one_host'
Or invento... | Ansible | 47,342,724 | 63 |
I received the following data from the setup module:
"ansible_nodename": "3d734bc2a391",
"ansible_os_family": "RedHat",
"ansible_pkg_mgr": "yum",
"ansible_processor": [
"AuthenticAMD",
"AMD PRO A10-8700B R6, 10 Compute Cores 4C+6G"
],
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_th... | To get first item of the list:
- debug:
msg: "First item: {{ ansible_processor[0] }}"
Or:
- debug:
msg: "First item: {{ ansible_processor | first }}"
| Ansible | 41,610,207 | 62 |
I want to use Ansible as part of another Python software. in that software I have a hosts list with their user / password.
Is there a way to pass the user / pass of the SSH connection to the Ansible ad-hoc command or write it in any file in encrypted way?
Or do i understand it all wrong, and the only way to do it is ... | The docs say you can specify the password via the command line:
-k, --ask-pass.
ask for connection password
Ansible can also store the password in the ansible_password variable on a per-host basis.
| Ansible | 37,004,686 | 61 |
I have a some Ansible tasks that perform unfortunately long operations - things like running an synchronization operation with an S3 folder. It's not always clear if they're progressing, or just stuck (or the ssh connection has died), so it would be nice to have some sort of progress output displayed. If the command'... | I came across this problem today on OSX, where I was running a docker shell command which took a long time to build and there was no output whilst it built. It was very frustrating to not understand whether the command had hung or was just progressing slowly.
I decided to pipe the output (and error) of the shell comma... | Ansible | 41,194,021 | 61 |
So after reading Ansible docs, I found out that Handlers are only fired when tasks report changes, so for example:
some tasks ...
notify: nginx_restart
# our handler
- name: nginx_restart
vs
some tasks ...
register: nginx_restart
# do this after nginx_restart changes
when: nginx_restart|changed
Is there any differe... | There are some differences and which is better depends on the situation.
Handlers will only be visible in the output if they have actually been executed. Not notified, there will be no skipped tasks in Ansibles output. Tasks always have output no matter if skipped, executed with change or without. (except they are excl... | Ansible | 33,931,610 | 60 |
All I could find was this from the docs:
Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for other mysterious reasons. If you have a long FQDN, inventory_hostna... |
inventory_hostname - As configured in the ansible inventory file (eg: /etc/ansible/hosts). It can be an IP address or a name that can be resolved by the DNS
ansible_hostname - As discovered by ansible. Ansible logs into the host via ssh and gathers some facts. As part of the fact, it also discovers its hostname which ... | Ansible | 45,908,067 | 60 |
Is it possible to run ansible playbook, which looks like this (it is an example from this site: http://docs.ansible.com/playbooks_roles.html):
- name: this is a play at the top level of a file
hosts: all
remote_user: root
tasks:
- name: say hi
tags: foo
shell: echo "hi..."
- include: load_balancers.yml... | As of Ansible 2.0 there seems to be an option called strategy on a playbook. When setting the strategy to free, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.
It looks something like this (taken from the above link):
- hosts: all
str... | Ansible | 21,158,689 | 59 |
I am getting this error in my nginx-error.log file:
2014/02/17 03:42:20 [crit] 5455#0: *1 connect() to unix:/tmp/uwsgi.sock failed (13: Permission denied) while connecting to upstream, client: xx.xx.x.xxx, server: localhost, request: "GET /users HTTP/1.1", upstream: "uwsgi://unix:/tmp/uwsgi.sock:", host: "EC2.amazonaws... | The permission issue occurs because uwsgi resets the ownership and permissions of /tmp/uwsgi.sock to 755 and the user running uwsgi every time uwsgi starts.
The correct way to solve the problem is to make uwsgi change the ownership and/or permission of /tmp/uwsgi.sock such that nginx can write to this socket. Therefore... | Ansible | 21,820,444 | 59 |
I'm running Ansible playbook and it works fine on one machine.
On a new machine when I try for the first time, I get the following error.
17:04:34 PLAY [appservers] *************************************************************
17:04:34
17:04:34 GATHERING FACTS ********************************************************... | The ansible docs have a section on this. Quoting:
Ansible has host key checking enabled by default.
If a host is reinstalled and has a different key in ‘known_hosts’,
this will result in an error message until corrected. If a host is not
initially in ‘known_hosts’ this will result in prompting for
confirmation of the ... | Ansible | 30,226,113 | 59 |
In Ansible, I have a list of strings that I want to join with newline characters to create a string, that when written to a file, becomes a series of lines. However, when I use the join() filter, it works on the inner list, the characters in the strings, and not on the outer list, the strings themselves. Here's my samp... | Solution
join filter works on lists, so apply it to your list:
- name: Concatenate the public keys
set_fact:
my_joined_list: "{{ my_list | join('\n') }}"
Explanation
While my_list in your example is a list, when you use with_items, in each iterationitem is a string. Strings are treated as lists of characters, t... | Ansible | 47,244,834 | 59 |
I've seen the question asked in a round about sort of way but not conclusively answered. What I want to do is straight forward. I want to copy a file index.php to the remote host at /var/www/index.php but only if it doesn't already exist.
I've tried using creates and only_if but I don't think these are intended for the... | Assuming index.php exists in the role's files subdirectory:
- copy:
src: index.php
dest: /var/www/index.php
force: no
The decisive property is force. As the documentation explains, the default is yes, which will replace the remote file when contents are different than the source. If no, the file will on... | Ansible | 21,646,033 | 58 |
So I figured I should start using Ansible Galaxy when possible, instead of writing my own roles. I just installed my first role and it was installed to /etc/local/ansible/roles (I am on OSX). Now I wonder how you install this roles where I actually need it? Do I just copy the role to where I need it or is there an Ansi... | Yes, you would copy them according to a sample project structure:
site.yml
webservers.yml
fooservers.yml
kubernetes.yaml
roles/
common/
files/
templates/
tasks/
handlers/
vars/
meta/
webservers/
files/
templates/
tasks/
handlers/
vars/
meta/
kubernete... | Ansible | 22,201,306 | 58 |
I am using ansible to script a deployment for an API. I would like this to work sequentially through each host in my inventory file so that I can fully deploy to one machine at a time.
With the out box behaviour, each task in my playbook is executed for each host in the inventory file before moving on to the next task... | Have a closer look at Rolling Updates:
What you are searching for is
- hosts: webservers
serial: 1
tasks:
- name: ...
| Ansible | 27,315,469 | 58 |
I'm trying to check if the version supplied is a valid supported version. I've set the list of acceptable versions in a variable, and I want to fail out of the task if the supplied version is not in the list. However, I'm unsure of how to do that.
#/role/vars/main.yml
---
acceptable_versions: [2, 3, 4]
and
#/role/ta... | You do not need {{}} in when conditions. What you are searching for is:
- fail: msg="unsupported version"
when: version not in acceptable_versions
| Ansible | 28,080,145 | 58 |
I have a bunch of servers that have four physical drives on them (/dev/sda, sdb, sdc, and sdd). sda has the OS installed on it.
I need to format each drive except sda. I need to check if each drive has data on it. If it does, then I shouldn't format it.
# This will get all physical disks (sda, sdb, sdc, etc) and assig... | You do not need to register your result with the item salt. When you register the result of a loop (e.g. with_items) the registered value will contain a key results which holds a list of all results of the loop. (See docs)
Instead of looping over your original device list, you can loop over the registered results of th... | Ansible | 32,214,529 | 58 |
I am new to Ansible and I am trying to implement it. I tried all the possible ways present on the Internet and also all questions related to it, but still I can't resolve the error. How can I fix it?
I installed Ansible playbook on my MacBook Pro. I created a VM whose IP address is 10.4.1.141 and host IP address is 10.... | I fixed the issue. The problem was in my /etc/ansible/hosts file.
The content written in /etc/ansible/hosts was 10.4.1.141. But when I changed it to rajat@10.4.1.141, then the issue got fixed.
| Ansible | 33,280,244 | 58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.