question_id
int64
82.3k
79.7M
title_clean
stringlengths
15
158
body_clean
stringlengths
62
28.5k
full_text
stringlengths
95
28.5k
tags
stringlengths
4
80
score
int64
0
1.15k
view_count
int64
22
1.62M
answer_count
int64
0
30
link
stringlengths
58
125
29,127,560
What's the difference between defaults and vars in an Ansible role?
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 should go into defaults , and what should to into vars ? Does it make sense to use both for the same data? I know that there's a difference in precedence/priority between the two, but I would like to understand what should go where. Let's say that my role would create a list of directories on the target system. I would like to provide a list of default directories to be created, but would like to allow the user to override them when using the role. Here's what this would look like: --- - directories: - foo - bar - baz I could place this either into the defaults/main.yml or in the vars/main.yml , from an execution perspective, it wouldn't make any difference - but where should it go?
What's the difference between defaults and vars in an Ansible role? 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 should go into defaults , and what should to into vars ? Does it make sense to use both for the same data? I know that there's a difference in precedence/priority between the two, but I would like to understand what should go where. Let's say that my role would create a list of directories on the target system. I would like to provide a list of default directories to be created, but would like to allow the user to override them when using the role. Here's what this would look like: --- - directories: - foo - bar - baz I could place this either into the defaults/main.yml or in the vars/main.yml , from an execution perspective, it wouldn't make any difference - but where should it go?
ansible
222
100,783
5
https://stackoverflow.com/questions/29127560/whats-the-difference-between-defaults-and-vars-in-an-ansible-role
24,334,115
ansible: lineinfile for several lines?
The same way there is a module lineinfile to add one line in a file, is there a way to add several lines? I do not want to use a template because you have to provide the whole file. I just want to add something to an existing file without necessarily knowing what the file already contains so a template is not an option.
ansible: lineinfile for several lines? The same way there is a module lineinfile to add one line in a file, is there a way to add several lines? I do not want to use a template because you have to provide the whole file. I just want to add something to an existing file without necessarily knowing what the file already contains so a template is not an option.
ansible
217
295,245
11
https://stackoverflow.com/questions/24334115/ansible-lineinfile-for-several-lines
40,230,184
How to do multiline shell script in Ansible
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
How to do multiline shell script in Ansible 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
shell, ansible
198
252,952
7
https://stackoverflow.com/questions/40230184/how-to-do-multiline-shell-script-in-ansible
35,105,615
Use a default if a variable is not defined
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: my_variable is not defined - name: Create custom user: name: "{{my_variable}}" when: my_variable is defined But as I mentioned, there's a lot of optional variables and this creates a lot of possibilities. Is there something like the code above? - user: name: "default_name", "{{my_variable}}" The code should set name="default_name" when my_variable isn't defined. I could set all variables on defaults/main.yml and create the user like that: - name: Create user user: name: "{{my_variable}}" But, those variables are inside a really big hash and there are some hashes inside that hash that can't be a default.
Use a default if a variable is not defined 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: my_variable is not defined - name: Create custom user: name: "{{my_variable}}" when: my_variable is defined But as I mentioned, there's a lot of optional variables and this creates a lot of possibilities. Is there something like the code above? - user: name: "default_name", "{{my_variable}}" The code should set name="default_name" when my_variable isn't defined. I could set all variables on defaults/main.yml and create the user like that: - name: Create user user: name: "{{my_variable}}" But, those variables are inside a really big hash and there are some hashes inside that hash that can't be a default.
ansible, ansible-2.x
197
329,361
9
https://stackoverflow.com/questions/35105615/use-a-default-if-a-variable-is-not-defined
32,429,259
Ansible fails with /bin/sh: 1: /usr/bin/python: not found
I'm running into an error I've never seen before. Here is the command and the error: $ ansible-playbook create_api.yml PLAY [straw] ****************************************************************** GATHERING FACTS *************************************************************** failed: [104.55.47.224] => {"failed": true, "parsed": false} /bin/sh: 1: /usr/bin/python: not found TASK: [typical | install required system packages] ***************************** FATAL: no hosts matched or all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/Users/john/create_api.retry 104.55.47.224 : ok=0 changed=0 unreachable=0 failed=1 Here is the create_api.yml file: --- - hosts: api remote_user: root roles: - api And here is the hosts file: [api] 104.55.47.224 I can remove the roles section and it won't make it to the first TASK, it will instead make it will only make it to the line /bin/sh: 1: /usr/bin/python: not found . What could be going on here? NOTE: In case anyone is pinging the IP address and failing to get a response, you should know I've changed the IP address since pasting code. EDIT python was installed locally, the problem was that it was not installed on the remote machine, which was running Ubuntu 15.04
Ansible fails with /bin/sh: 1: /usr/bin/python: not found I'm running into an error I've never seen before. Here is the command and the error: $ ansible-playbook create_api.yml PLAY [straw] ****************************************************************** GATHERING FACTS *************************************************************** failed: [104.55.47.224] => {"failed": true, "parsed": false} /bin/sh: 1: /usr/bin/python: not found TASK: [typical | install required system packages] ***************************** FATAL: no hosts matched or all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/Users/john/create_api.retry 104.55.47.224 : ok=0 changed=0 unreachable=0 failed=1 Here is the create_api.yml file: --- - hosts: api remote_user: root roles: - api And here is the hosts file: [api] 104.55.47.224 I can remove the roles section and it won't make it to the first TASK, it will instead make it will only make it to the line /bin/sh: 1: /usr/bin/python: not found . What could be going on here? NOTE: In case anyone is pinging the IP address and failing to get a response, you should know I've changed the IP address since pasting code. EDIT python was installed locally, the problem was that it was not installed on the remote machine, which was running Ubuntu 15.04
ansible
196
122,565
20
https://stackoverflow.com/questions/32429259/ansible-fails-with-bin-sh-1-usr-bin-python-not-found
21,344,777
How to switch a user per task or set of tasks?
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 up such as chowning directories. Here's a snippet from one of my playbooks: - name: checkout repo git: repo=[URL] version=master dest={{ dst }} sudo: yes - name: change perms file: dest={{ dst }} state=directory mode=0755 owner=some_user sudo: yes Ideally I could run commands or sets of commands as a different user even if it requires sudo to su to that user.
How to switch a user per task or set of tasks? 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 up such as chowning directories. Here's a snippet from one of my playbooks: - name: checkout repo git: repo=[URL] version=master dest={{ dst }} sudo: yes - name: change perms file: dest={{ dst }} state=directory mode=0755 owner=some_user sudo: yes Ideally I could run commands or sets of commands as a different user even if it requires sudo to su to that user.
ansible
194
293,755
5
https://stackoverflow.com/questions/21344777/how-to-switch-a-user-per-task-or-set-of-tasks
18,839,509
Where can I get a list of Ansible pre-defined variables?
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?
Where can I get a list of Ansible pre-defined variables? 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?
ansible, ansible-facts
191
263,133
10
https://stackoverflow.com/questions/18839509/where-can-i-get-a-list-of-ansible-pre-defined-variables
21,346,390
How to get the host name of the current machine as defined in the Ansible hosts file?
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_hostname resolves to the host name generated when the machine is created, not the one you define in your hosts file. - name: Install this only for local dev machine pip: name: pyramid when: ansible_hostname == "local"
How to get the host name of the current machine as defined in the Ansible hosts file? 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_hostname resolves to the host name generated when the machine is created, not the one you define in your hosts file. - name: Install this only for local dev machine pip: name: pyramid when: ansible_hostname == "local"
ansible
190
241,203
3
https://stackoverflow.com/questions/21346390/how-to-get-the-host-name-of-the-current-machine-as-defined-in-the-ansible-hosts
30,119,973
How to run a task when variable is undefined in ansible?
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
How to run a task when variable is undefined in ansible? 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
ansible
186
398,128
4
https://stackoverflow.com/questions/30119973/how-to-run-a-task-when-variable-is-undefined-in-ansible
22,472,168
What's the easy way to auto create non existing dir in ansible
In my Ansible playbook many times i need to create a file: - name: Copy file template: src: code.conf.j2 dest: "{{ project_root }}/conf/code.conf" Many times conf dir is not there. Then I have to create another task to create that dir first. Is there any easy way to auto create the dir if it doesn't exist with some option?
What's the easy way to auto create non existing dir in ansible In my Ansible playbook many times i need to create a file: - name: Copy file template: src: code.conf.j2 dest: "{{ project_root }}/conf/code.conf" Many times conf dir is not there. Then I have to create another task to create that dir first. Is there any easy way to auto create the dir if it doesn't exist with some option?
ansible
182
213,948
8
https://stackoverflow.com/questions/22472168/whats-the-easy-way-to-auto-create-non-existing-dir-in-ansible
39,819,378
Ansible: get current target host's IP address
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 things like {{ hostvars[{{ inventory_hostname }}]['ansible_ssh_host'] }} and ip="{{ hostvars.{{ inventory_hostname }}.ansible_ssh_host }}"
Ansible: get current target host's IP address 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 things like {{ hostvars[{{ inventory_hostname }}]['ansible_ssh_host'] }} and ip="{{ hostvars.{{ inventory_hostname }}.ansible_ssh_host }}"
ansible, ansible-facts, ansible-template
178
518,829
14
https://stackoverflow.com/questions/39819378/ansible-get-current-target-hosts-ip-address
30,787,273
Variable that has the path to the current ansible-playbook that is executing?
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 repository to ~/branch1/ and then I run ansible-playbook dev.yml I was thinking it should save the volume to ~/branch1/.docker_volume/ . If I ran it from ~/branch2 then it should configure the volume to ~/branch2/.docker_volume/ .
Variable that has the path to the current ansible-playbook that is executing? 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 repository to ~/branch1/ and then I run ansible-playbook dev.yml I was thinking it should save the volume to ~/branch1/.docker_volume/ . If I ran it from ~/branch2 then it should configure the volume to ~/branch2/.docker_volume/ .
ansible
177
234,050
7
https://stackoverflow.com/questions/30787273/variable-that-has-the-path-to-the-current-ansible-playbook-that-is-executing
25,230,376
How to automatically install Ansible Galaxy roles?
All my Ansible playbooks/roles are checked in to my git repo. However, for Ansible Galaxy roles I always have to explicitly download them one by one on every machine I want to run Ansible from. It's even tough to know in advance exactly which Ansible Galaxy roles are needed until Ansible complains about a missing role at runtime. How is one supposed to manage the Ansible Galaxy role dependencies? I would like to either have them checked into my git repo along with the rest of my ansible code or have them automatically be identified and downloaded when I run Ansible on a new machine.
How to automatically install Ansible Galaxy roles? All my Ansible playbooks/roles are checked in to my git repo. However, for Ansible Galaxy roles I always have to explicitly download them one by one on every machine I want to run Ansible from. It's even tough to know in advance exactly which Ansible Galaxy roles are needed until Ansible complains about a missing role at runtime. How is one supposed to manage the Ansible Galaxy role dependencies? I would like to either have them checked into my git repo along with the rest of my ansible code or have them automatically be identified and downloaded when I run Ansible on a new machine.
ansible, ansible-galaxy
170
132,858
15
https://stackoverflow.com/questions/25230376/how-to-automatically-install-ansible-galaxy-roles
23,074,412
How to set host_key_checking=false in ansible inventory file?
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 host_key_checking=false Is there a configuration variable outside of Vagrantfile that can override this value? Also, how would this work if running ansible from a Kubernetes pod?
How to set host_key_checking=false in ansible inventory file? 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 host_key_checking=false Is there a configuration variable outside of Vagrantfile that can override this value? Also, how would this work if running ansible from a Kubernetes pod?
ansible, vagrant, ansible-inventory, vagrantfile
169
370,156
8
https://stackoverflow.com/questions/23074412/how-to-set-host-key-checking-false-in-ansible-inventory-file
44,734,179
Specifying ssh key in ansible playbook file
Ansible playbook can specify the key used for ssh connection using --key-file on the command line. ansible-playbook -i hosts playbook.yml --key-file "~/.ssh/mykey.pem" Is it possible to specify the location of this key in playbook file instead of using --key-file on command line? Because I want to write the location of this key into a var.yaml file, which will be read by ansible playbook with vars_files: . The followings are parts of my configuration: vars.yml file key1: ~/.ssh/mykey1.pem key2: ~/.ssh/mykey2.pem playbook.yml file --- - hosts: myHost remote_user: ubuntu key_file: {{ key1 }} # This is not a valid syntax in ansible. Does there exist this kind of directive which allows me to specify the ssh key used for this connection? vars_files: - vars.yml tasks: - name: Echo a hello message command: echo hello I've tried adding ansible_ssh_private_key_file under vars . But it doesn't work on my machine. vars_files: - vars.yml vars: ansible_ssh_private_key_file: "{{ key1 }}" tasks: - name: Echo a hello message command: echo hello If I run ansible-playbook with the playbook.yml above. I got the following error: TASK [Gathering Facts] ****************************************************************************************************************************** Using module file /usr/local/lib/python2.7/site-packages/ansible/modules/system/setup.py <192.168.5.100> ESTABLISH SSH CONNECTION FOR USER: ubuntu <192.168.5.100> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ubuntu -o ConnectTimeout=10 -o ControlPath=/Users/myName/.ansible/cp/2d18691789 192.168.5.100 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"'' <192.168.5.100> (255, '', 'Permission denied (publickey).\r\n') fatal: [192.168.5.100]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n", "unreachable": true } to retry, use: --limit @/Users/myName/playbook.retry I don't find the name of my key file in the ssh command. It's strange.
Specifying ssh key in ansible playbook file Ansible playbook can specify the key used for ssh connection using --key-file on the command line. ansible-playbook -i hosts playbook.yml --key-file "~/.ssh/mykey.pem" Is it possible to specify the location of this key in playbook file instead of using --key-file on command line? Because I want to write the location of this key into a var.yaml file, which will be read by ansible playbook with vars_files: . The followings are parts of my configuration: vars.yml file key1: ~/.ssh/mykey1.pem key2: ~/.ssh/mykey2.pem playbook.yml file --- - hosts: myHost remote_user: ubuntu key_file: {{ key1 }} # This is not a valid syntax in ansible. Does there exist this kind of directive which allows me to specify the ssh key used for this connection? vars_files: - vars.yml tasks: - name: Echo a hello message command: echo hello I've tried adding ansible_ssh_private_key_file under vars . But it doesn't work on my machine. vars_files: - vars.yml vars: ansible_ssh_private_key_file: "{{ key1 }}" tasks: - name: Echo a hello message command: echo hello If I run ansible-playbook with the playbook.yml above. I got the following error: TASK [Gathering Facts] ****************************************************************************************************************************** Using module file /usr/local/lib/python2.7/site-packages/ansible/modules/system/setup.py <192.168.5.100> ESTABLISH SSH CONNECTION FOR USER: ubuntu <192.168.5.100> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ubuntu -o ConnectTimeout=10 -o ControlPath=/Users/myName/.ansible/cp/2d18691789 192.168.5.100 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"'' <192.168.5.100> (255, '', 'Permission denied (publickey).\r\n') fatal: [192.168.5.100]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n", "unreachable": true } to retry, use: --limit @/Users/myName/playbook.retry I don't find the name of my key file in the ssh command. It's strange.
ansible, ssh-keys
163
402,246
3
https://stackoverflow.com/questions/44734179/specifying-ssh-key-in-ansible-playbook-file
31,318,881
How do you stop Ansible from creating .retry files in the home directory?
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?
How do you stop Ansible from creating .retry files in the home directory? 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?
ansible
162
51,913
5
https://stackoverflow.com/questions/31318881/how-do-you-stop-ansible-from-creating-retry-files-in-the-home-directory
28,347,717
How to create an empty file with Ansible?
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=touch owner=root group=sys mode=0555 But then the file gets touched every time, showing up as a yellow line in the log, which is also unsatisfactory... Is there any better solution to this simple problem?
How to create an empty file with Ansible? 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=touch owner=root group=sys mode=0555 But then the file gets touched every time, showing up as a yellow line in the log, which is also unsatisfactory... Is there any better solution to this simple problem?
file, ansible
159
177,895
10
https://stackoverflow.com/questions/28347717/how-to-create-an-empty-file-with-ansible
33,222,641
Override hosts variable of Ansible playbook from the command line
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 hosts/<env> server.yml and override hosts: web from server.yml to run this playbook for [droplets] . Can I just override as a one time off thing, without editing server.yml directly? Thanks.
Override hosts variable of Ansible playbook from the command line 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 hosts/<env> server.yml and override hosts: web from server.yml to run this playbook for [droplets] . Can I just override as a one time off thing, without editing server.yml directly? Thanks.
ansible
159
237,283
12
https://stackoverflow.com/questions/33222641/override-hosts-variable-of-ansible-playbook-from-the-command-line
36,696,952
Copy multiple files with Ansible
How can I copy more than a single file into remote nodes by Ansible in a task? I've tried to duplicate the copy module line in my task to define files but it only copies the first file.
Copy multiple files with Ansible How can I copy more than a single file into remote nodes by Ansible in a task? I've tried to duplicate the copy module line in my task to define files but it only copies the first file.
ansible
155
280,853
16
https://stackoverflow.com/questions/36696952/copy-multiple-files-with-ansible
26,638,180
Write variable to a file in Ansible
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.
Write variable to a file in Ansible 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.
file, ansible
151
300,571
4
https://stackoverflow.com/questions/26638180/write-variable-to-a-file-in-ansible
38,350,674
Ansible: Can I execute role from command line?
Suppose I have a role called "apache" Now I want to execute that role on host 192.168.0.10 from the command line from Ansible host ansible-playbook -i "192.168.0.10" --role "path to role" Is there a way to do that?
Ansible: Can I execute role from command line? Suppose I have a role called "apache" Now I want to execute that role on host 192.168.0.10 from the command line from Ansible host ansible-playbook -i "192.168.0.10" --role "path to role" Is there a way to do that?
ansible, ansible-role
148
186,135
10
https://stackoverflow.com/questions/38350674/ansible-can-i-execute-role-from-command-line
32,101,001
Ansible Playbooks vs Roles
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 automatically loading certain vars_files, tasks, and handlers based on a known file structure. Grouping content by roles also allows easy sharing of roles with other users. However the distinction between these and their different use cases is not immediately obvious to me. For instance, if I configure my /etc/ansible/hosts file to look like: [databases] mydb01.example.org mydb02.example.org [mail_servers] mymail01.example.org mymail_dr.example.org ...then what is this " [databases] " entry...a role ? Or the name of a playbook YAML file somewhere? Or something else?!? If someone could explain to me the differences on these, my understanding of Ansible would be greatly enhance! Playbook vs Role vs [databases] and similar entries in /etc/ansible/hosts If Playbooks are defined inside of YAML files, then where are Roles defined? 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 Playbooks vs Roles 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 automatically loading certain vars_files, tasks, and handlers based on a known file structure. Grouping content by roles also allows easy sharing of roles with other users. However the distinction between these and their different use cases is not immediately obvious to me. For instance, if I configure my /etc/ansible/hosts file to look like: [databases] mydb01.example.org mydb02.example.org [mail_servers] mymail01.example.org mymail_dr.example.org ...then what is this " [databases] " entry...a role ? Or the name of a playbook YAML file somewhere? Or something else?!? If someone could explain to me the differences on these, my understanding of Ansible would be greatly enhance! Playbook vs Role vs [databases] and similar entries in /etc/ansible/hosts If Playbooks are defined inside of YAML files, then where are Roles defined? 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, ansible-galaxy
145
96,929
6
https://stackoverflow.com/questions/32101001/ansible-playbooks-vs-roles
36,059,804
Ansible: Store command&#39;s stdout in new variable?
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 - debug: msg="{{command_output.stdout}}" - name: Copy test service template: src=../templates/test.service.j2 dest=/tmp/test.service - name: Enable test service shell: systemctl enable /tmp/test.service - name: Start test service shell: systemctl start test.service and let's say this is my template: [Unit] Description=MyApp After=docker.service Requires=docker.service [Service] TimeoutStartSec=0 ExecStartPre=-/usr/bin/docker kill busybox1 ExecStartPre=-/usr/bin/docker rm busybox1 ExecStartPre=/usr/bin/docker pull busybox ExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c "while true; do echo {{ string_to_echo }}; sleep 1; done" [Install] WantedBy=multi-user.target (Notice the {{ string_to_echo }} ) So what I'm basically looking for is a way to store the contents of command_output.stdout (which is generated/retrieved during the first task) in a new variable string_to_echo . That variable I'd like to use in multiple templates afterwards. I guess I could just use {{command_output.stdout}} in my templates, but I want to get rid of that .stdout for readability.
Ansible: Store command&#39;s stdout in new variable? 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 - debug: msg="{{command_output.stdout}}" - name: Copy test service template: src=../templates/test.service.j2 dest=/tmp/test.service - name: Enable test service shell: systemctl enable /tmp/test.service - name: Start test service shell: systemctl start test.service and let's say this is my template: [Unit] Description=MyApp After=docker.service Requires=docker.service [Service] TimeoutStartSec=0 ExecStartPre=-/usr/bin/docker kill busybox1 ExecStartPre=-/usr/bin/docker rm busybox1 ExecStartPre=/usr/bin/docker pull busybox ExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c "while true; do echo {{ string_to_echo }}; sleep 1; done" [Install] WantedBy=multi-user.target (Notice the {{ string_to_echo }} ) So what I'm basically looking for is a way to store the contents of command_output.stdout (which is generated/retrieved during the first task) in a new variable string_to_echo . That variable I'd like to use in multiple templates afterwards. I guess I could just use {{command_output.stdout}} in my templates, but I want to get rid of that .stdout for readability.
ansible
140
362,069
6
https://stackoverflow.com/questions/36059804/ansible-store-commands-stdout-in-new-variable
24,003,880
Ansible: Set variable to file content
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_data_file: "base-ami-userdata.sh" tasks: - name: user_data_contents shell: 'cat {{ user_data_file }}' register: user_data_action - name: launch ec2-instance local_action: ... user_data: '{{ user_data_action.stdout }}' I assume there's a much easier way to do this, but I couldn't find it while searching Ansible docs.
Ansible: Set variable to file content 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_data_file: "base-ami-userdata.sh" tasks: - name: user_data_contents shell: 'cat {{ user_data_file }}' register: user_data_action - name: launch ec2-instance local_action: ... user_data: '{{ user_data_action.stdout }}' I assume there's a much easier way to do this, but I couldn't find it while searching Ansible docs.
ansible
138
234,010
4
https://stackoverflow.com/questions/24003880/ansible-set-variable-to-file-content
19,292,899
Creating a new user and password with Ansible
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?
Creating a new user and password with Ansible 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?
bash, shell, ubuntu, ansible
136
356,299
25
https://stackoverflow.com/questions/19292899/creating-a-new-user-and-password-with-ansible
21,008,083
Run task only if host does not belong to a group
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?
Run task only if host does not belong to a group 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?
ansible
134
196,143
3
https://stackoverflow.com/questions/21008083/run-task-only-if-host-does-not-belong-to-a-group
26,394,096
How do I get a variable with the name of the user running ansible?
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_USER), but those are all set to either "root" or the deployment id being used to ssh into the remote system. None of those contain the local user, the one who is currently running the ansible process. How can I script getting the name of the user running the ansible process and use it in my playbook?
How do I get a variable with the name of the user running ansible? 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_USER), but those are all set to either "root" or the deployment id being used to ssh into the remote system. None of those contain the local user, the one who is currently running the ansible process. How can I script getting the name of the user running the ansible process and use it in my playbook?
variables, ansible
131
169,509
7
https://stackoverflow.com/questions/26394096/how-do-i-get-a-variable-with-the-name-of-the-user-running-ansible
32,279,519
Escaping double curly braces in Ansible
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"
Escaping double curly braces in Ansible 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"
docker, jinja2, ansible
131
98,699
10
https://stackoverflow.com/questions/32279519/escaping-double-curly-braces-in-ansible
25,505,146
How can I copy files between two managed nodes using Ansible?
I need to copy a file between two remote nodes: node A is a managed node where the file exists node B is a managed node where the file should be copied Please note that my control node, from where I run all my Ansible tasks, is none of the above mentioned nodes. I have tried the following: Use scp command in shell module of Ansible - hosts: machine2 user: user2 tasks: - name: Copy file from machine1 to machine2 shell: scp user1@machine1:/path-of-file/file1 /home/user2/file1 This approach just goes on and on never ends. Use the fetch and copy modules - hosts: machine1 user: user1 tasks: - name: copy file from machine1 to local fetch: src: /path-of-file/file1 dest: /path-of-file/file1 - hosts: machine2 user: user2 tasks: - name: copy file from local to machine2 copy: src: /path-of-file/file1 dest: /path-of-file/file1 This approach throws me an error as follows: error while accessing the file /Users//.ansible/cp/ansible-ssh-machine2-22-, error was: [Errno 102] Operation not supported on socket: u'/Users//.ansible/cp/ansible-ssh-machine2-22-' How can I achieve this?
How can I copy files between two managed nodes using Ansible? I need to copy a file between two remote nodes: node A is a managed node where the file exists node B is a managed node where the file should be copied Please note that my control node, from where I run all my Ansible tasks, is none of the above mentioned nodes. I have tried the following: Use scp command in shell module of Ansible - hosts: machine2 user: user2 tasks: - name: Copy file from machine1 to machine2 shell: scp user1@machine1:/path-of-file/file1 /home/user2/file1 This approach just goes on and on never ends. Use the fetch and copy modules - hosts: machine1 user: user1 tasks: - name: copy file from machine1 to local fetch: src: /path-of-file/file1 dest: /path-of-file/file1 - hosts: machine2 user: user2 tasks: - name: copy file from local to machine2 copy: src: /path-of-file/file1 dest: /path-of-file/file1 This approach throws me an error as follows: error while accessing the file /Users//.ansible/cp/ansible-ssh-machine2-22-, error was: [Errno 102] Operation not supported on socket: u'/Users//.ansible/cp/ansible-ssh-machine2-22-' How can I achieve this?
ansible
131
232,806
10
https://stackoverflow.com/questions/25505146/how-can-i-copy-files-between-two-managed-nodes-using-ansible
25,582,740
Missing sudo password in Ansible
Ansible asks for sudo password from following code, it tries to create a new postgres user. Error message: fatal: [xxx.xxx.xxx.xxx] => Missing sudo password main.yml - name: 'Provision a PostgreSQL server' hosts: "dbservers" sudo: yes sudo_user: postgres roles: - postgres create_db.yml - name: Make sure the PostgreSQL users are present postgresql_user: name=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER sudo_user: postgres sudo: yes The remote_user that used to login to this machine is a non-root user, it has no password, and can only login using key auth. For user postgres , this account doesn't have the password as well, because the database was just installed. Since I logged in as non -root user, of course it will ask for password when switch to postgress account in order to create database user. But it won't be need for password if switch to postgres from root account. So, I wonder if there is a way to switch to root, and then switch to user postgres . Note: the root account has no public key, no password, and cannot login from SSH.
Missing sudo password in Ansible Ansible asks for sudo password from following code, it tries to create a new postgres user. Error message: fatal: [xxx.xxx.xxx.xxx] => Missing sudo password main.yml - name: 'Provision a PostgreSQL server' hosts: "dbservers" sudo: yes sudo_user: postgres roles: - postgres create_db.yml - name: Make sure the PostgreSQL users are present postgresql_user: name=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER sudo_user: postgres sudo: yes The remote_user that used to login to this machine is a non-root user, it has no password, and can only login using key auth. For user postgres , this account doesn't have the password as well, because the database was just installed. Since I logged in as non -root user, of course it will ask for password when switch to postgress account in order to create database user. But it won't be need for password if switch to postgres from root account. So, I wonder if there is a way to switch to root, and then switch to user postgres . Note: the root account has no public key, no password, and cannot login from SSH.
ansible
130
298,925
15
https://stackoverflow.com/questions/25582740/missing-sudo-password-in-ansible
31,142,369
How to use template module with different set of variables?
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 find a proper way to get this variable filled by "File1" and "File2". Something like : - name: template test 1 template: src=myTemplateFile dest=result1 - name: template test 2 template: src=myTemplateFile dest=result2 where I could specify for the first templating that the variable to use is a = "File1" and for the second, b = "File2".
How to use template module with different set of variables? 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 find a proper way to get this variable filled by "File1" and "File2". Something like : - name: template test 1 template: src=myTemplateFile dest=result1 - name: template test 2 template: src=myTemplateFile dest=result2 where I could specify for the first templating that the variable to use is a = "File1" and for the second, b = "File2".
ansible, ansible-template
127
180,862
8
https://stackoverflow.com/questions/31142369/how-to-use-template-module-with-different-set-of-variables
17,188,147
How to run Ansible without specifying the inventory but the host directly?
I want to run Ansible in Python without specifying the inventory file through (ANSIBLE_HOST) but just by: ansible.run.Runner( module_name='ping', host='www.google.com' ) I can actually do this in fabric easily but just wonder how to do this in Python. On the other hand, documentation of the Ansible API for python is not really complete.
How to run Ansible without specifying the inventory but the host directly? I want to run Ansible in Python without specifying the inventory file through (ANSIBLE_HOST) but just by: ansible.run.Runner( module_name='ping', host='www.google.com' ) I can actually do this in fabric easily but just wonder how to do this in Python. On the other hand, documentation of the Ansible API for python is not really complete.
python, ansible
117
173,180
6
https://stackoverflow.com/questions/17188147/how-to-run-ansible-without-specifying-the-inventory-but-the-host-directly
24,851,575
ansible : how to pass multiple commands
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: [URL] which give me back "no such file or directory" - command: ./configure;/usr/bin/make;/usr/bin/make install chdir=/src/package/ I tried this too: [URL] but I couldn't find the right syntax to put: - command: "{{ item }}" chdir=/src/package/ with_items: ./configure /usr/bin/make /usr/bin/make install That does not work, saying there is a quote issue.
ansible : how to pass multiple commands 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: [URL] which give me back "no such file or directory" - command: ./configure;/usr/bin/make;/usr/bin/make install chdir=/src/package/ I tried this too: [URL] but I couldn't find the right syntax to put: - command: "{{ item }}" chdir=/src/package/ with_items: ./configure /usr/bin/make /usr/bin/make install That does not work, saying there is a quote issue.
module, command, ansible
116
321,093
6
https://stackoverflow.com/questions/24851575/ansible-how-to-pass-multiple-commands
35,487,756
How to copy files with ansible relatively to the role?
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 make much sense. If I do it will break if I duplicate the role.
How to copy files with ansible relatively to the role? 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 make much sense. If I do it will break if I duplicate the role.
ansible
116
137,871
2
https://stackoverflow.com/questions/35487756/how-to-copy-files-with-ansible-relatively-to-the-role
18,794,808
How do I get logs/details of ansible-playbook module executions?
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 *************************************************************** ok: [MyTestHost] TASK: [Hello yourself] ******************************************************** ok: [MyTestHost] PLAY RECAP ******************************************************************** MyTestHost : ok=2 changed=0 unreachable=0 failed=0 $ I know for sure that it was successful. Where/how do I see the "Hello World" echo'ed/printed by my script on the remote host (MyTestHost)? Or the return/exit code of script? My research shows me it would be possible to write a plugin to intercept module execution callbacks or something on those lines and write a log file. I would prefer to not waste my time with that. E.g. something like the stdout in below (note that I'm running ansible and not ansible-playbook): $ ansible plabb54 -i /project/plab/svn/plab-maintenance/ansible/plab_hosts.txt -m script -a ./test.sh plabb54 | success >> { "rc": 0, "stderr": "", "stdout": "Hello World\n" } $
How do I get logs/details of ansible-playbook module executions? 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 *************************************************************** ok: [MyTestHost] TASK: [Hello yourself] ******************************************************** ok: [MyTestHost] PLAY RECAP ******************************************************************** MyTestHost : ok=2 changed=0 unreachable=0 failed=0 $ I know for sure that it was successful. Where/how do I see the "Hello World" echo'ed/printed by my script on the remote host (MyTestHost)? Or the return/exit code of script? My research shows me it would be possible to write a plugin to intercept module execution callbacks or something on those lines and write a log file. I would prefer to not waste my time with that. E.g. something like the stdout in below (note that I'm running ansible and not ansible-playbook): $ ansible plabb54 -i /project/plab/svn/plab-maintenance/ansible/plab_hosts.txt -m script -a ./test.sh plabb54 | success >> { "rc": 0, "stderr": "", "stdout": "Hello World\n" } $
logging, ansible
116
308,726
7
https://stackoverflow.com/questions/18794808/how-do-i-get-logs-details-of-ansible-playbook-module-executions
31,895,602
Ansible: filter a list by its attributes
I have variable named "network" registered in Ansible: { "addresses": { "private_ext": [ { "type": "fixed", "addr": "172.16.2.100" } ], "private_man": [ { "type": "fixed", "addr": "172.16.1.100" }, { "type": "floating", "addr": "10.90.80.10" } ] } } Is it possible to get the IP address ("addr") with type="floating" doing something like this? - debug: var={{ network.addresses.private_man | filter type="fixed" | get "addr" }} I know the syntax is wrong but you get the idea.
Ansible: filter a list by its attributes I have variable named "network" registered in Ansible: { "addresses": { "private_ext": [ { "type": "fixed", "addr": "172.16.2.100" } ], "private_man": [ { "type": "fixed", "addr": "172.16.1.100" }, { "type": "floating", "addr": "10.90.80.10" } ] } } Is it possible to get the IP address ("addr") with type="floating" doing something like this? - debug: var={{ network.addresses.private_man | filter type="fixed" | get "addr" }} I know the syntax is wrong but you get the idea.
jinja2, ansible
113
175,917
3
https://stackoverflow.com/questions/31895602/ansible-filter-a-list-by-its-attributes
33,896,847
How do I register a variable and persist it between plays targeted on different nodes?
I have an Ansible playbook , where I would like a variable I register in a first play targeted on one node to be available in a second play, targeted on another node. Here is the playbook I am using: --- - hosts: localhost gather_facts: no tasks: - command: echo "hello world" register: foo - hosts: main gather_facts: no tasks: - debug: msg: {{ foo.stdout }} But, when I try to access the variable in the second play, targeted on main , I get this message: The task includes an option with an undefined variable. The error was: 'foo' is undefined How can I access foo , registered on localhost , from main ?
How do I register a variable and persist it between plays targeted on different nodes? I have an Ansible playbook , where I would like a variable I register in a first play targeted on one node to be available in a second play, targeted on another node. Here is the playbook I am using: --- - hosts: localhost gather_facts: no tasks: - command: echo "hello world" register: foo - hosts: main gather_facts: no tasks: - debug: msg: {{ foo.stdout }} But, when I try to access the variable in the second play, targeted on main , I get this message: The task includes an option with an undefined variable. The error was: 'foo' is undefined How can I access foo , registered on localhost , from main ?
ansible
111
173,138
5
https://stackoverflow.com/questions/33896847/how-do-i-register-a-variable-and-persist-it-between-plays-targeted-on-different
41,535,838
How to run apt update and upgrade via Ansible shell
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-get update && sudo apt-get upgrade -y"
How to run apt update and upgrade via Ansible shell 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-get update && sudo apt-get upgrade -y"
ansible
109
201,733
4
https://stackoverflow.com/questions/41535838/how-to-run-apt-update-and-upgrade-via-ansible-shell
22,256,884
Not possible to source .bashrc with Ansible
I can SSH to the remote host and do a source /home/username/.bashrc — everything works fine. However if I do: - name: source bashrc action: command source /home/username/.bashrc I get: failed: [hostname] => {"cmd": ["source", "/home/username/.bashrc"], "failed": true, "rc": 2} msg: [Errno 2] No such file or directory I have no idea what I'm doing wrong.
Not possible to source .bashrc with Ansible I can SSH to the remote host and do a source /home/username/.bashrc — everything works fine. However if I do: - name: source bashrc action: command source /home/username/.bashrc I get: failed: [hostname] => {"cmd": ["source", "/home/username/.bashrc"], "failed": true, "rc": 2} msg: [Errno 2] No such file or directory I have no idea what I'm doing wrong.
ansible
109
105,746
10
https://stackoverflow.com/questions/22256884/not-possible-to-source-bashrc-with-ansible
33,343,215
How to get an arbitrary remote user&#39;s home directory in Ansible?
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 makes the user's home directory available as a home_<user name> fact. How do I get the home directory of an arbitrary remote user?
How to get an arbitrary remote user&#39;s home directory in Ansible? 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 makes the user's home directory available as a home_<user name> fact. How do I get the home directory of an arbitrary remote user?
ansible, ansible-facts
106
156,457
15
https://stackoverflow.com/questions/33343215/how-to-get-an-arbitrary-remote-users-home-directory-in-ansible
43,467,180
How to decrypt string with ansible-vault 2.3.0
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 37366638363362303836383335623066343562666662386233306537333232396637346463376430 3664323265333036663736383837326263376637616466610a383430623562633235616531303861 66313432303063343230613665323930386138613334303839626131373033656463303736366166 6635346135636437360a313031376566303238303835353364313434363163343066363932346165 6136 The error I'm geeting is ERROR! input is not vault encrypted data for test.yml How can I decrypt the string so I know what it's value without the need to run the play?
How to decrypt string with ansible-vault 2.3.0 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 37366638363362303836383335623066343562666662386233306537333232396637346463376430 3664323265333036663736383837326263376637616466610a383430623562633235616531303861 66313432303063343230613665323930386138613334303839626131373033656463303736366166 6635346135636437360a313031376566303238303835353364313434363163343066363932346165 6136 The error I'm geeting is ERROR! input is not vault encrypted data for test.yml How can I decrypt the string so I know what it's value without the need to run the play?
ansible, ansible-vault
105
192,646
22
https://stackoverflow.com/questions/43467180/how-to-decrypt-string-with-ansible-vault-2-3-0
56,663,332
What is the difference between shell and command in ansible?
I am new to the Ansible world. What is the difference between shell and command in ansible ? When to use one over the other? I know that the command module is safer, as it is not affected by the user's environment.
What is the difference between shell and command in ansible? I am new to the Ansible world. What is the difference between shell and command in ansible ? When to use one over the other? I know that the command module is safer, as it is not affected by the user's environment.
ansible
103
114,232
4
https://stackoverflow.com/questions/56663332/what-is-the-difference-between-shell-and-command-in-ansible
35,488,433
How to copy a directory&#39;s content to another directory?
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! => {"changed": false, "failed": true, "msg": "attempted to take checksum of directory:/home/vagrant/dist/"} How can I copy a directory that has another directory and a file inside?
How to copy a directory&#39;s content to another directory? 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! => {"changed": false, "failed": true, "msg": "attempted to take checksum of directory:/home/vagrant/dist/"} How can I copy a directory that has another directory and a file inside?
ansible, ansible-2.x
100
334,932
13
https://stackoverflow.com/questions/35488433/how-to-copy-a-directorys-content-to-another-directory
22,522,985
How can I write variables inside the tasks file in ansible
I have this play.yml --- - hosts: localhost tasks: - include: apache.yml My apache.yml file looks like this: vars: url: [URL] - name: Download apache shell: wget {{ url }} This is giving me an error. If I remove vars then it works. But, I want to keep the variable inside the included tasks file, so that I can keep different variables for different tasks separate.
How can I write variables inside the tasks file in ansible I have this play.yml --- - hosts: localhost tasks: - include: apache.yml My apache.yml file looks like this: vars: url: [URL] - name: Download apache shell: wget {{ url }} This is giving me an error. If I remove vars then it works. But, I want to keep the variable inside the included tasks file, so that I can keep different variables for different tasks separate.
ansible
99
231,558
7
https://stackoverflow.com/questions/22522985/how-can-i-write-variables-inside-the-tasks-file-in-ansible
36,451,793
How do I exit Ansible play without error on a condition
I want to exit without an error (I know about assert and fail modules) when I meet a certain condition. The following code exits but with a failure: tasks: - name: Check if there is something to upgrade shell: if apt-get --dry-run upgrade | grep -q "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"; then echo "no"; else echo "yes"; fi register: upgrading - name: Exit if nothing to upgrade fail: msg="Nothing to upgrade" when: upgrading.stdout == "no"
How do I exit Ansible play without error on a condition I want to exit without an error (I know about assert and fail modules) when I meet a certain condition. The following code exits but with a failure: tasks: - name: Check if there is something to upgrade shell: if apt-get --dry-run upgrade | grep -q "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"; then echo "no"; else echo "yes"; fi register: upgrading - name: Exit if nothing to upgrade fail: msg="Nothing to upgrade" when: upgrading.stdout == "no"
ansible
99
197,642
7
https://stackoverflow.com/questions/36451793/how-do-i-exit-ansible-play-without-error-on-a-condition
19,369,931
Ansible: How to change active directory in Ansible Playbook?
- 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.
Ansible: How to change active directory in Ansible Playbook? - 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.
ansible
99
185,011
4
https://stackoverflow.com/questions/19369931/ansible-how-to-change-active-directory-in-ansible-playbook
34,188,167
Ansible - Print message - debug: msg=&quot;line1 \n {{ var2 }} \n line3 with var3 = {{ var3 }}&quot;
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 = fsroot[ {{ slave_fsroot }} ], master[ {{ slave_master }} ], connectingToMasterAs[ {{ slave_user }} ], description[ {{ slave_desc }} ], No.Of.Executors[ {{ slave_execs }} ], LABELs[ {{ slave_labels }} ], mode[ {{ slave_mode }} ]" tags: - koba - debug: msg="print(2 == Slave properties = \n\nfsroot[ {{ slave_fsroot }} ],\n master[ {{ slave_master }} ],\n connectingToMasterAs[ {{ slave_user }} ],\n description[ {{ slave_desc }} ],\n No.Of.Executors[ {{ slave_execs }} ],\n LABELs[ {{ slave_labels }} ],\n mode[ {{ slave_mode }} ])" tags: - koba But this is not printing the variable with new lines (for the 3rd debug action)?
Ansible - Print message - debug: msg=&quot;line1 \n {{ var2 }} \n line3 with var3 = {{ var3 }}&quot; 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 = fsroot[ {{ slave_fsroot }} ], master[ {{ slave_master }} ], connectingToMasterAs[ {{ slave_user }} ], description[ {{ slave_desc }} ], No.Of.Executors[ {{ slave_execs }} ], LABELs[ {{ slave_labels }} ], mode[ {{ slave_mode }} ]" tags: - koba - debug: msg="print(2 == Slave properties = \n\nfsroot[ {{ slave_fsroot }} ],\n master[ {{ slave_master }} ],\n connectingToMasterAs[ {{ slave_user }} ],\n description[ {{ slave_desc }} ],\n No.Of.Executors[ {{ slave_execs }} ],\n LABELs[ {{ slave_labels }} ],\n mode[ {{ slave_mode }} ])" tags: - koba But this is not printing the variable with new lines (for the 3rd debug action)?
action, newline, roles, ansible
98
188,448
9
https://stackoverflow.com/questions/34188167/ansible-print-message-debug-msg-line1-n-var2-n-line3-with-var3
31,618,967
How do I write an Ansible handler with multiple tasks?
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 step 2 service: name=service state=restarted when: result
How do I write an Ansible handler with multiple tasks? 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 step 2 service: name=service state=restarted when: result
handler, ansible
97
109,676
3
https://stackoverflow.com/questions/31618967/how-do-i-write-an-ansible-handler-with-multiple-tasks
37,333,305
Ansible: create a user with sudo privileges
I have taken over a Ubuntu 14.04 server. It has a user called "deployer" (used with capistrano), and as such, it needs sudo privileges. With this setup, I can log into the server and do stuff like: workstation> ssh deployer@myserver myserver> sudo apt-get install git myserver> exit workstation> I am trying to figure out how to use Ansible (version 2.0.2.0 and python 2.7.3) to create a user called "deployer" and be able to log into the server with that id and then so sudo-ish things like "apt-get install". My playbook looks like this: --- - hosts: example become: yes tasks: - name: Update apt cache apt: update_cache: yes cache_valid_time: 3600 - group: name=sudo state=present - name: Add deployer user and add it to sudo user: name=deployer state=present createhome=yes become: yes become_method: "sudo" - name: Set up authorized keys for the deployer user authorized_key: user=deployer key="{{item}}" with_file: - /home/jaygodse/.ssh/id_rsa.pub After running this playbook, I am able to ssh into the machine as "deployer", (e.g. ssh deployer@myserver) but if I run a sudo command, it always asks me for my sudo password. I understand that the "deployer" user ultimately has to find its way into the visudo users file, but I cannot figure out which magical Ansible incantations to invoke so that I can ssh into the machine as deployer and then run a sudo command (e.g. sudo apt-get install git") without being prompted for a sudo password. I have searched high and low, and I can't seem to find an Ansible playbook fragment which puts the user "deployer" into the sudo group without requiring a password. How is this done?
Ansible: create a user with sudo privileges I have taken over a Ubuntu 14.04 server. It has a user called "deployer" (used with capistrano), and as such, it needs sudo privileges. With this setup, I can log into the server and do stuff like: workstation> ssh deployer@myserver myserver> sudo apt-get install git myserver> exit workstation> I am trying to figure out how to use Ansible (version 2.0.2.0 and python 2.7.3) to create a user called "deployer" and be able to log into the server with that id and then so sudo-ish things like "apt-get install". My playbook looks like this: --- - hosts: example become: yes tasks: - name: Update apt cache apt: update_cache: yes cache_valid_time: 3600 - group: name=sudo state=present - name: Add deployer user and add it to sudo user: name=deployer state=present createhome=yes become: yes become_method: "sudo" - name: Set up authorized keys for the deployer user authorized_key: user=deployer key="{{item}}" with_file: - /home/jaygodse/.ssh/id_rsa.pub After running this playbook, I am able to ssh into the machine as "deployer", (e.g. ssh deployer@myserver) but if I run a sudo command, it always asks me for my sudo password. I understand that the "deployer" user ultimately has to find its way into the visudo users file, but I cannot figure out which magical Ansible incantations to invoke so that I can ssh into the machine as deployer and then run a sudo command (e.g. sudo apt-get install git") without being prompted for a sudo password. I have searched high and low, and I can't seem to find an Ansible playbook fragment which puts the user "deployer" into the sudo group without requiring a password. How is this done?
ansible, sudoers
95
191,787
4
https://stackoverflow.com/questions/37333305/ansible-create-a-user-with-sudo-privileges
30,192,490
include tasks from another role in ansible playbook
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 │ └── main.yml └── other_stuff_workflow └── tasks └── main.yml my main.yml in custom_stuff_workflow then contain something like: --- - include: login.yml - include: A.yml - include: C.yml - include: save.yml - include: logout.yml and this one in the other workflow: --- - include: login.yml - include: B.yml - include: A.yml - include: D.yml - include: save.yml - include: logout.yml I can't find a way to do it in a natural way: one way that worked was having all tasks in a single role and tagging the relevant tasks while including a custom_stuff_workflow The problem I have with that is that tags cannot be set in the calling playbook: it's only to be set at command line as I'm distributing this ansible repo with many people in the company, I can't rely on command line invocations (it would be nice to have a #! header in yml to be processed by ansible-playbook command) I could also copy the relevant tasks (inside common in the above tree) in each workflow, but I don't want to repeat them around Can someone see a solution to achieve what I'd like without repeating the tasks over different roles? I guess the corner stone of my problem is that I define tasks as individual and it looks not natural in ansible... Thanks a lot PS: note that the tasks in the workflow have to be done in specific order and the only natural steps to abstract would be the login and save/logout PPS: I've seen this question How do I call a role from within another role in Ansible? but it does not solve my problem as it's invoking a full role and not a subset of the tasks in a role
include tasks from another role in ansible playbook 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 │ └── main.yml └── other_stuff_workflow └── tasks └── main.yml my main.yml in custom_stuff_workflow then contain something like: --- - include: login.yml - include: A.yml - include: C.yml - include: save.yml - include: logout.yml and this one in the other workflow: --- - include: login.yml - include: B.yml - include: A.yml - include: D.yml - include: save.yml - include: logout.yml I can't find a way to do it in a natural way: one way that worked was having all tasks in a single role and tagging the relevant tasks while including a custom_stuff_workflow The problem I have with that is that tags cannot be set in the calling playbook: it's only to be set at command line as I'm distributing this ansible repo with many people in the company, I can't rely on command line invocations (it would be nice to have a #! header in yml to be processed by ansible-playbook command) I could also copy the relevant tasks (inside common in the above tree) in each workflow, but I don't want to repeat them around Can someone see a solution to achieve what I'd like without repeating the tasks over different roles? I guess the corner stone of my problem is that I define tasks as individual and it looks not natural in ansible... Thanks a lot PS: note that the tasks in the workflow have to be done in specific order and the only natural steps to abstract would be the login and save/logout PPS: I've seen this question How do I call a role from within another role in Ansible? but it does not solve my problem as it's invoking a full role and not a subset of the tasks in a role
ansible
94
134,284
4
https://stackoverflow.com/questions/30192490/include-tasks-from-another-role-in-ansible-playbook
21,160,776
How to execute a shell script on a remote server using Ansible?
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 - name: Execute the script local_action: command sudo sh /home/test_user/test.sh When I run the playbook, the transfer successfully occurs but the script is not executed.
How to execute a shell script on a remote server using Ansible? 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 - name: Execute the script local_action: command sudo sh /home/test_user/test.sh When I run the playbook, the transfer successfully occurs but the script is not executed.
shell, ansible, remote-server
92
381,090
8
https://stackoverflow.com/questions/21160776/how-to-execute-a-shell-script-on-a-remote-server-using-ansible
40,027,847
Accessing inventory host variable in Ansible playbook
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] test2-1 ansible_ssh_host=abc.def.ghi.mno ansible_ssh_port=1212 [test3] test3-1 ansible_ssh_host=abc.def.ghi.pqr ansible_ssh_port=1212 test3-2 ansible_ssh_host=abc.def.ghi.stu ansible_ssh_port=1212 [all:children] test1 test2 test3 I have tried accessing the role in the following fashions: {{ hostvars.ansible_ssh_host }} and {{ hostvars.test1.ansible_ssh_host }} I get this error: fatal: [localhost]: FAILED! => {"failed": true, "msg": "'ansible.vars.hostvars.HostVars object' has no attribute 'ansible'"}
Accessing inventory host variable in Ansible playbook 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] test2-1 ansible_ssh_host=abc.def.ghi.mno ansible_ssh_port=1212 [test3] test3-1 ansible_ssh_host=abc.def.ghi.pqr ansible_ssh_port=1212 test3-2 ansible_ssh_host=abc.def.ghi.stu ansible_ssh_port=1212 [all:children] test1 test2 test3 I have tried accessing the role in the following fashions: {{ hostvars.ansible_ssh_host }} and {{ hostvars.test1.ansible_ssh_host }} I get this error: fatal: [localhost]: FAILED! => {"failed": true, "msg": "'ansible.vars.hostvars.HostVars object' has no attribute 'ansible'"}
ansible, ansible-2.x, ansible-inventory
90
333,223
6
https://stackoverflow.com/questions/40027847/accessing-inventory-host-variable-in-ansible-playbook
35,605,603
Using Ansible set_fact to create a dictionary from register results
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": { "name": "Thelma" }, "stdout": "female" } ] } I'd like to use a subsequent set_fact task to generate a new variable with a dictionary like this: { "Bob": "male", "Thelma": "female" } I guess this might be possible but I'm going round in circles with no luck so far.
Using Ansible set_fact to create a dictionary from register results 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": { "name": "Thelma" }, "stdout": "female" } ] } I'd like to use a subsequent set_fact task to generate a new variable with a dictionary like this: { "Bob": "male", "Thelma": "female" } I guess this might be possible but I'm going round in circles with no luck so far.
ansible
89
181,198
2
https://stackoverflow.com/questions/35605603/using-ansible-set-fact-to-create-a-dictionary-from-register-results
30,209,062
Ansible: How to encrypt some variables in an inventory file in a separate vault file?
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 db_password ) in an Ansible vault , but not the entire file. How can a vault-encrypted ansible file be imported into an unencrypted inventory file? What I've tried I have created an encrypted vars file and tried importing it with: include: secrets To which ansible-playbook responded with: ERROR: variables assigned to group must be in key=value form Probably because it tried to parse the include statement as a variable.
Ansible: How to encrypt some variables in an inventory file in a separate vault file? 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 db_password ) in an Ansible vault , but not the entire file. How can a vault-encrypted ansible file be imported into an unencrypted inventory file? What I've tried I have created an encrypted vars file and tried importing it with: include: secrets To which ansible-playbook responded with: ERROR: variables assigned to group must be in key=value form Probably because it tried to parse the include statement as a variable.
encryption, ansible, ansible-vault
87
121,930
6
https://stackoverflow.com/questions/30209062/ansible-how-to-encrypt-some-variables-in-an-inventory-file-in-a-separate-vault
44,134,642
How to retry Ansible task that may fail?
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 to fail my play. When I do retries as follows retries: 3 delay: 5 Then retries are not executed at all, because first command execution fails whole play. I could add ignore_errors: yes but that way play will pass even if all retries failed. Is there a easy way to retry failures until I have success, but fail when no success from last retry?
How to retry Ansible task that may fail? 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 to fail my play. When I do retries as follows retries: 3 delay: 5 Then retries are not executed at all, because first command execution fails whole play. I could add ignore_errors: yes but that way play will pass even if all retries failed. Is there a easy way to retry failures until I have success, but fail when no success from last retry?
ansible
87
196,197
4
https://stackoverflow.com/questions/44134642/how-to-retry-ansible-task-that-may-fail
27,985,334
Why is copying a directory with Ansible so slow?
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, which according to the ansible docs , but to no avail. can be anywhere from 2-6x faster than SSH with ControlPersist enabled, and 10x faster than paramiko.
Why is copying a directory with Ansible so slow? 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, which according to the ansible docs , but to no avail. can be anywhere from 2-6x faster than SSH with ControlPersist enabled, and 10x faster than paramiko.
scp, ansible
87
53,623
7
https://stackoverflow.com/questions/27985334/why-is-copying-a-directory-with-ansible-so-slow
42,835,626
Ansible: To use the &#39;ssh&#39; connection type with passwords, you must install the sshpass program&quot;
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-master] kubernetes-master-1 ansible_host=10.20.0.225 ansible_user=centos ansible_become=true kubernetes-master-2 ansible_host=10.20.0.226 ansible_user=centos ansible_become=true kubernetes-master-3 ansible_host=10.20.0.227 ansible_user=centos ansible_become=true Failure bash-4.3# ansible-playbook -i inventory/inventory deploy-test-ms.yml --ask-vault-pass Vault password: PLAY [kube-master] ************************************************************* TASK [setup] ******************************************************************* Thursday 16 March 2017 13:32:05 +0000 (0:00:00.026) 0:00:00.026 ******** fatal: [kubernetes-master-1]: FAILED! => {"failed": true, "msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"} fatal: [kubernetes-master-2]: FAILED! => {"failed": true, "msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"} fatal: [kubernetes-master-3]: FAILED! => {"failed": true, "msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"} PLAY RECAP ********************************************************************* kubernetes-master-1 : ok=0 changed=0 unreachable=0 failed=1 kubernetes-master-2 : ok=0 changed=0 unreachable=0 failed=1 kubernetes-master-3 : ok=0 changed=0 unreachable=0 failed=1 UPDATE: **With failed script** Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py <10.20.0.227> ESTABLISH SSH CONNECTION FOR USER: centos Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py <172.23.169.137> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.225> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.226> ESTABLISH SSH CONNECTION FOR USER: centos **With successfull script** Thursday 16 March 2017 14:03:49 +0000 (0:00:00.066) 0:00:00.066 ******** Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py <10.20.0.237> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.237> SSH: EXEC ssh -F ./ssh.cfg -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=centos -o ConnectTimeout=30 -o 'ControlPath=~/.ssh/ansible-%r@%h:%p' 10.20.0.237 '/bin/sh -c '"'"'( umask 77 && mkdir -p " echo $HOME/.ansible/tmp/ansible-tmp-1489673029.48-15997231643297 4 " && echo ansible-tmp-1489673029.48-159972316432974=" echo $HOME/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974 " ) && sleep 0'"'"'' <10.20.0.237> PUT /tmp/tmpnHJPbc TO /home/centos/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/setup.py <10.20.0.237> SSH: EXEC scp -F ./ssh.cfg -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=centos -o ConnectTimeout=30 -o 'ControlPath=~/.ssh/ansible-%r@%h:%p' /tmp/tmpnHJPbc '[10.20.0.237]:/home/centos/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/setup.py' <10.20.0.237> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.237> SSH: EXEC ssh -F ./ssh.cfg -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=centos -o ConnectTimeout=30 -o 'ControlPath=~/.ssh/ansible-%r@%h:%p' 10.20.0.237 '/bin/sh -c '"'"'chmod u+x /home/centos/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/ /home/cento s/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/setup.py && sleep 0'"'"''
Ansible: To use the &#39;ssh&#39; connection type with passwords, you must install the sshpass program&quot; 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-master] kubernetes-master-1 ansible_host=10.20.0.225 ansible_user=centos ansible_become=true kubernetes-master-2 ansible_host=10.20.0.226 ansible_user=centos ansible_become=true kubernetes-master-3 ansible_host=10.20.0.227 ansible_user=centos ansible_become=true Failure bash-4.3# ansible-playbook -i inventory/inventory deploy-test-ms.yml --ask-vault-pass Vault password: PLAY [kube-master] ************************************************************* TASK [setup] ******************************************************************* Thursday 16 March 2017 13:32:05 +0000 (0:00:00.026) 0:00:00.026 ******** fatal: [kubernetes-master-1]: FAILED! => {"failed": true, "msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"} fatal: [kubernetes-master-2]: FAILED! => {"failed": true, "msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"} fatal: [kubernetes-master-3]: FAILED! => {"failed": true, "msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"} PLAY RECAP ********************************************************************* kubernetes-master-1 : ok=0 changed=0 unreachable=0 failed=1 kubernetes-master-2 : ok=0 changed=0 unreachable=0 failed=1 kubernetes-master-3 : ok=0 changed=0 unreachable=0 failed=1 UPDATE: **With failed script** Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py <10.20.0.227> ESTABLISH SSH CONNECTION FOR USER: centos Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py <172.23.169.137> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.225> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.226> ESTABLISH SSH CONNECTION FOR USER: centos **With successfull script** Thursday 16 March 2017 14:03:49 +0000 (0:00:00.066) 0:00:00.066 ******** Using module file /usr/lib/python2.7/site-packages/ansible/modules/core/system/setup.py <10.20.0.237> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.237> SSH: EXEC ssh -F ./ssh.cfg -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=centos -o ConnectTimeout=30 -o 'ControlPath=~/.ssh/ansible-%r@%h:%p' 10.20.0.237 '/bin/sh -c '"'"'( umask 77 && mkdir -p " echo $HOME/.ansible/tmp/ansible-tmp-1489673029.48-15997231643297 4 " && echo ansible-tmp-1489673029.48-159972316432974=" echo $HOME/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974 " ) && sleep 0'"'"'' <10.20.0.237> PUT /tmp/tmpnHJPbc TO /home/centos/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/setup.py <10.20.0.237> SSH: EXEC scp -F ./ssh.cfg -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=centos -o ConnectTimeout=30 -o 'ControlPath=~/.ssh/ansible-%r@%h:%p' /tmp/tmpnHJPbc '[10.20.0.237]:/home/centos/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/setup.py' <10.20.0.237> ESTABLISH SSH CONNECTION FOR USER: centos <10.20.0.237> SSH: EXEC ssh -F ./ssh.cfg -o ControlMaster=auto -o ControlPersist=30m -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=centos -o ConnectTimeout=30 -o 'ControlPath=~/.ssh/ansible-%r@%h:%p' 10.20.0.237 '/bin/sh -c '"'"'chmod u+x /home/centos/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/ /home/cento s/.ansible/tmp/ansible-tmp-1489673029.48-159972316432974/setup.py && sleep 0'"'"''
ansible
86
255,887
11
https://stackoverflow.com/questions/42835626/ansible-to-use-the-ssh-connection-type-with-passwords-you-must-install-the-s
38,290,143
Difference between become and become_user in Ansible
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 sometimes these two directives are mixed. Could you explain the correct meaning of them?
Difference between become and become_user in Ansible 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 sometimes these two directives are mixed. Could you explain the correct meaning of them?
ansible, root, ansible-2.x
86
159,072
4
https://stackoverflow.com/questions/38290143/difference-between-become-and-become-user-in-ansible
26,551,422
ansible: include role in a role?
Is it possible to reuse a role in a role? I do not mean via defining a dependency in the meta/main.yml file of a role but by including the role in the tasks/main.yml of another role directly? For example, I define a couple of basic roles in rolebooks and some more high level roles in roles. I want the high level roles to include some of the basic roles in addition to some specific tasks. playbooks/ rolebooks/ some_role/ roles/ webtier/ tasks/ main.yml In playbooks/roles/webtier/tasks/main.yml: - shell: echo 'hello' - { role: rolebooks/some_role } - shell: echo 'still busy' Thanks
ansible: include role in a role? Is it possible to reuse a role in a role? I do not mean via defining a dependency in the meta/main.yml file of a role but by including the role in the tasks/main.yml of another role directly? For example, I define a couple of basic roles in rolebooks and some more high level roles in roles. I want the high level roles to include some of the basic roles in addition to some specific tasks. playbooks/ rolebooks/ some_role/ roles/ webtier/ tasks/ main.yml In playbooks/roles/webtier/tasks/main.yml: - shell: echo 'hello' - { role: rolebooks/some_role } - shell: echo 'still busy' Thanks
ansible
86
85,510
3
https://stackoverflow.com/questions/26551422/ansible-include-role-in-a-role
38,876,487
Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors
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: this command prints FAILED when it fails command: /usr/bin/example-command -x -y -z register: command_result ignore_errors: True - name: fail the play if the previous command did not succeed fail: msg="the command failed" when: "'FAILED' in command_result.stderr" How do I fail at the end ? I have several tasks, what would my "When" condition be?
Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors 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: this command prints FAILED when it fails command: /usr/bin/example-command -x -y -z register: command_result ignore_errors: True - name: fail the play if the previous command did not succeed fail: msg="the command failed" when: "'FAILED' in command_result.stderr" How do I fail at the end ? I have several tasks, what would my "When" condition be?
ansible
86
308,109
8
https://stackoverflow.com/questions/38876487/ansible-ignore-errors-in-tasks-and-fail-at-end-of-the-playbook-if-any-tasks-had
24,679,591
Ansible Command module says that &#39;|&#39; is illegal character
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: $ ansible-playbook -i hosts idempotent.yml PLAY [lxc-host] *************************************************************** GATHERING FACTS *************************************************************** ok: [10.0.3.240] TASK: [idempotent | Check if python-apt is installed] ************************* failed: [10.0.3.240] => {"changed": true, "cmd": ["dpkg", "-l", "|", "grep", "python-apt"], "delta": "0:00:00.015524", "end": "2014-07-10 14:41:35.207971", "rc": 2, "start": "2014-07-10 14:41:35.192447"} stderr: dpkg-query: error: package name in specifier '|' is illegal: must start with an alphanumeric character ...ignoring PLAY RECAP ******************************************************************** 10.0.3.240 : ok=2 changed=1 unreachable=0 failed=0 Why is illegal this character '|' .
Ansible Command module says that &#39;|&#39; is illegal character 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: $ ansible-playbook -i hosts idempotent.yml PLAY [lxc-host] *************************************************************** GATHERING FACTS *************************************************************** ok: [10.0.3.240] TASK: [idempotent | Check if python-apt is installed] ************************* failed: [10.0.3.240] => {"changed": true, "cmd": ["dpkg", "-l", "|", "grep", "python-apt"], "delta": "0:00:00.015524", "end": "2014-07-10 14:41:35.207971", "rc": 2, "start": "2014-07-10 14:41:35.192447"} stderr: dpkg-query: error: package name in specifier '|' is illegal: must start with an alphanumeric character ...ignoring PLAY RECAP ******************************************************************** 10.0.3.240 : ok=2 changed=1 unreachable=0 failed=0 Why is illegal this character '|' .
shell, dpkg, ansible
85
114,227
2
https://stackoverflow.com/questions/24679591/ansible-command-module-says-that-is-illegal-character
35,407,822
How can I test jinja2 templates in ansible?
Sometimes I need to test some jinja2 templates that I use in my ansible roles. What is the simplest way for doing this? For example, I have a template (test.j2): {% if users is defined and users %} {% for user in users %}{{ user }} {% endfor %} {% endif %} and vars (in group_vars/all): --- users: - Mike - Smith - Klara - Alex
How can I test jinja2 templates in ansible? Sometimes I need to test some jinja2 templates that I use in my ansible roles. What is the simplest way for doing this? For example, I have a template (test.j2): {% if users is defined and users %} {% for user in users %}{{ user }} {% endfor %} {% endif %} and vars (in group_vars/all): --- users: - Mike - Smith - Klara - Alex
jinja2, ansible, ansible-template
85
100,294
5
https://stackoverflow.com/questions/35407822/how-can-i-test-jinja2-templates-in-ansible
31,310,688
Conditionally define variable in Ansible
I want to conditionally define a variable in an Ansible playbook like this: my_var: "{{ 'foo' if my_condition}}" I would like the variable to remain undefined if the condition does not resolve to true . Ansible gives the following error if I try to execute the code: fatal: [foo.local] => {'msg': 'AnsibleUndefinedVariable: One or more undefined variables: the inline if-expression on line 1 evaluated to false and no else section was defined.', 'failed': True} Why is this an error anyway? The complete case looks like this: {role: foo, my_var: "foo"} If my_var is defined, the role does something special. In some cases, I don't want the role to do this. I could use when: condition , but then I would have to copy the whole role block. I could also use an extra bool variable, but I would like a solution without having to change the "interface" to the role. Any ideas?
Conditionally define variable in Ansible I want to conditionally define a variable in an Ansible playbook like this: my_var: "{{ 'foo' if my_condition}}" I would like the variable to remain undefined if the condition does not resolve to true . Ansible gives the following error if I try to execute the code: fatal: [foo.local] => {'msg': 'AnsibleUndefinedVariable: One or more undefined variables: the inline if-expression on line 1 evaluated to false and no else section was defined.', 'failed': True} Why is this an error anyway? The complete case looks like this: {role: foo, my_var: "foo"} If my_var is defined, the role does something special. In some cases, I don't want the role to do this. I could use when: condition , but then I would have to copy the whole role block. I could also use an extra bool variable, but I would like a solution without having to change the "interface" to the role. Any ideas?
ansible
85
215,324
6
https://stackoverflow.com/questions/31310688/conditionally-define-variable-in-ansible
30,786,263
Only check whether a line present in a file (ansible)
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
Only check whether a line present in a file (ansible) 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
ansible
84
147,675
9
https://stackoverflow.com/questions/30786263/only-check-whether-a-line-present-in-a-file-ansible
20,563,639
Ansible playbook shell output
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 | success | rc=0 >> 0.0 root /sbin/init 0.0 root [kthreadd] 0.0 root [ksoftirqd/0] 0.0 root [migration/0] otherhost | success | rc=0 >> 0.0 root /sbin/init 0.0 root [kthreadd] 0.0 root [ksoftirqd/0] 0.0 root [migration/0] However this requires me to keep a bunch of shell scripts around for every task which is not very 'ansible' so I put this in a playbook: --- - hosts: all gather_facts: no tasks: - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5 and run it with -vv , but the output baiscally shows the dictionary content and newlines are not printed as such so this results in an unreadable mess like this: changed: [localhost] => {"changed": true, "cmd": "ps -eo pcpu,user,args | sort -r -k1 head -n5 ", "delta": "0:00:00.015337", "end": "2013-12-13 10:57:25.680708", "rc": 0, "start": "2013-12-13 10:57:25.665371", "stderr": "", "stdout": "47.3 xxx Xvnc4 :24 -desktop xxx:24 (xxx) -auth /home/xxx/.Xauthority -geometry 1920x1200\n .... I also tried adding register: var and the a 'debug' task to show {{ var.stdout }} but the result is of course the same. Is there a way to get nicely formatted output from a command's stdout/stderr when run via a playbook? I can think of a number of possible ways (format output using sed? redirect output to file on the host then get that file back and echo it to the screen?), but with my limited knowledge of the shell/ansible it would take me a day to just try it out.
Ansible playbook shell output 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 | success | rc=0 >> 0.0 root /sbin/init 0.0 root [kthreadd] 0.0 root [ksoftirqd/0] 0.0 root [migration/0] otherhost | success | rc=0 >> 0.0 root /sbin/init 0.0 root [kthreadd] 0.0 root [ksoftirqd/0] 0.0 root [migration/0] However this requires me to keep a bunch of shell scripts around for every task which is not very 'ansible' so I put this in a playbook: --- - hosts: all gather_facts: no tasks: - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5 and run it with -vv , but the output baiscally shows the dictionary content and newlines are not printed as such so this results in an unreadable mess like this: changed: [localhost] => {"changed": true, "cmd": "ps -eo pcpu,user,args | sort -r -k1 head -n5 ", "delta": "0:00:00.015337", "end": "2013-12-13 10:57:25.680708", "rc": 0, "start": "2013-12-13 10:57:25.665371", "stderr": "", "stdout": "47.3 xxx Xvnc4 :24 -desktop xxx:24 (xxx) -auth /home/xxx/.Xauthority -geometry 1920x1200\n .... I also tried adding register: var and the a 'debug' task to show {{ var.stdout }} but the result is of course the same. Is there a way to get nicely formatted output from a command's stdout/stderr when run via a playbook? I can think of a number of possible ways (format output using sed? redirect output to file on the host then get that file back and echo it to the screen?), but with my limited knowledge of the shell/ansible it would take me a day to just try it out.
shell, sed, ansible
84
278,711
9
https://stackoverflow.com/questions/20563639/ansible-playbook-shell-output
36,912,726
Ansible: How to test that a registered variable is not empty?
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: [deploy | debug msg='critp is Ok] ******* ok: [vagrant] => { "msg": "myscritp is Ok" } In case the stderr is not empty a FATAl error occurs.
Ansible: How to test that a registered variable is not empty? 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: [deploy | debug msg='critp is Ok] ******* ok: [vagrant] => { "msg": "myscritp is Ok" } In case the stderr is not empty a FATAl error occurs.
ansible, yaml
83
269,644
3
https://stackoverflow.com/questions/36912726/ansible-how-to-test-that-a-registered-variable-is-not-empty
28,778,738
Ansible - Mode 755 for directories and 644 for files recursively
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: Make my directory tree readable file: path: dir mode: 0755 recurse: yes On the other hand, if I choose mode 0644, then all my files are not executable, but I'm not able to list my directories. Is it possible to set mode 755 for all directories and 644 for all files in a directory tree?
Ansible - Mode 755 for directories and 644 for files recursively 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: Make my directory tree readable file: path: dir mode: 0755 recurse: yes On the other hand, if I choose mode 0644, then all my files are not executable, but I'm not able to list my directories. Is it possible to set mode 755 for all directories and 644 for all files in a directory tree?
file-permissions, ansible
83
82,166
4
https://stackoverflow.com/questions/28778738/ansible-mode-755-for-directories-and-644-for-files-recursively
40,505,772
Ansible: How to chmod +x a file with Ansible?
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/metadata.sh
Ansible: How to chmod +x a file with Ansible? 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/metadata.sh
bash, ansible
83
101,024
4
https://stackoverflow.com/questions/40505772/ansible-how-to-chmod-x-a-file-with-ansible
29,900,096
How to continue execution on failed task after fixing error in playbook?
When writing and debugging Ansible playbooks, typical workflow is as follows: ansible-playbook ./main.yaml Playbook fails on some task Fix this task and repeat line 1, waiting for all previous tasks to execute again. Which takes a lot of time Ideally, i'd like to resume execution on failed task, having inventory and all facts collected by previous tasks. Is it even possible? How to make playbook writing/debugging faster?
How to continue execution on failed task after fixing error in playbook? When writing and debugging Ansible playbooks, typical workflow is as follows: ansible-playbook ./main.yaml Playbook fails on some task Fix this task and repeat line 1, waiting for all previous tasks to execute again. Which takes a lot of time Ideally, i'd like to resume execution on failed task, having inventory and all facts collected by previous tasks. Is it even possible? How to make playbook writing/debugging faster?
ansible
83
99,010
3
https://stackoverflow.com/questions/29900096/how-to-continue-execution-on-failed-task-after-fixing-error-in-playbook
21,422,158
Ansible - accessing local environment variables
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?
Ansible - accessing local environment variables 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?
ansible
82
123,525
4
https://stackoverflow.com/questions/21422158/ansible-accessing-local-environment-variables
34,018,862
How to force handler to run before executing a task in Ansible?
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 IP address I'm trying to access). My current playbook: tasks: - name: Configure app template: src=app.conf.j2 dest=/etc/app.conf notify: restart app - name: Change data in app configure_app: host={{new_ip}} data={{data}} handlers: - name: restart app service: name=app state=restarted I need to force the handler to run if configure_app changed before executing 'Change data in app'.
How to force handler to run before executing a task in Ansible? 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 IP address I'm trying to access). My current playbook: tasks: - name: Configure app template: src=app.conf.j2 dest=/etc/app.conf notify: restart app - name: Change data in app configure_app: host={{new_ip}} data={{data}} handlers: - name: restart app service: name=app state=restarted I need to force the handler to run if configure_app changed before executing 'Change data in app'.
ansible, ansible-handlers
82
68,686
1
https://stackoverflow.com/questions/34018862/how-to-force-handler-to-run-before-executing-a-task-in-ansible
29,276,198
Ansible: how to construct a variable from another variable and then fetch it&#39;s value
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? --- - name: "Play to for dynamic groups" hosts: local vars: - target_host: smtp - smtp_host: smtp.max.com tasks: - name: testing debug: msg={{ target_host }} - name: testing debug: msg={{ smtp_host }} - name: testing debug: msg={{ target_host }}_host - name: testing debug: msg={{ {{ target_host }}_host }} Output: TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp.max.com" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp_host" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "{{{{target_host}}_host}}" }
Ansible: how to construct a variable from another variable and then fetch it&#39;s value 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? --- - name: "Play to for dynamic groups" hosts: local vars: - target_host: smtp - smtp_host: smtp.max.com tasks: - name: testing debug: msg={{ target_host }} - name: testing debug: msg={{ smtp_host }} - name: testing debug: msg={{ target_host }}_host - name: testing debug: msg={{ {{ target_host }}_host }} Output: TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp.max.com" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "smtp_host" } TASK: [testing] *************************************************************** ok: [127.0.0.1] => { "msg": "{{{{target_host}}_host}}" }
ansible
81
184,138
10
https://stackoverflow.com/questions/29276198/ansible-how-to-construct-a-variable-from-another-variable-and-then-fetch-its-v
24,124,140
SSH Agent Forwarding with Ansible
I’m using Ansible 1.5.3 and Git with ssh agent forwarding ( [URL] ). I can log into the server that I am managing with Ansible and test that my connection to git is correctly configured: ubuntu@test:~$ ssh -T git@github.com Hi gituser! You've successfully authenticated, but GitHub does not provide shell access. I can also clone and update one of my repos using this account so my git configuration looks good and uses ssh forwarding when I log into my server directly via ssh. The problem: When I attempt the same test shown above using the Ansible command module. It fails with “Permission denied”. Part of the Ansible output (with verbose logging) looks like this: failed: [xxx.xxxxx.com] => {"changed": true, "cmd": ["ssh", "-T", "git@github.com"], "delta": "0:00:00.585481", "end": "2014-06-09 14:11:37.410907", "rc": 255, "start": "2014-06-09 14:11:36.825426"} stderr: Permission denied (publickey). Here is the simple playbook that runs this command: - hosts: webservers sudo: yes remote_user: ubuntu tasks: - name: Test that git ssh connection is working. command: ssh -T git@github.com The question: why does everything work correctly when I manually log in via ssh and run the command but fail when the same command is run as the same user via Ansible? I will post the answer shortly if no one else beats me to it. Although I am using git to demonstrate the problem, it could occur with any module that depends on ssh agent forwarding. It is not specific to Ansible but I suspect many will first encounter the problem in this scenario.
SSH Agent Forwarding with Ansible I’m using Ansible 1.5.3 and Git with ssh agent forwarding ( [URL] ). I can log into the server that I am managing with Ansible and test that my connection to git is correctly configured: ubuntu@test:~$ ssh -T git@github.com Hi gituser! You've successfully authenticated, but GitHub does not provide shell access. I can also clone and update one of my repos using this account so my git configuration looks good and uses ssh forwarding when I log into my server directly via ssh. The problem: When I attempt the same test shown above using the Ansible command module. It fails with “Permission denied”. Part of the Ansible output (with verbose logging) looks like this: failed: [xxx.xxxxx.com] => {"changed": true, "cmd": ["ssh", "-T", "git@github.com"], "delta": "0:00:00.585481", "end": "2014-06-09 14:11:37.410907", "rc": 255, "start": "2014-06-09 14:11:36.825426"} stderr: Permission denied (publickey). Here is the simple playbook that runs this command: - hosts: webservers sudo: yes remote_user: ubuntu tasks: - name: Test that git ssh connection is working. command: ssh -T git@github.com The question: why does everything work correctly when I manually log in via ssh and run the command but fail when the same command is run as the same user via Ansible? I will post the answer shortly if no one else beats me to it. Although I am using git to demonstrate the problem, it could occur with any module that depends on ssh agent forwarding. It is not specific to Ansible but I suspect many will first encounter the problem in this scenario.
git, ssh, ansible, ssh-agent
80
60,087
4
https://stackoverflow.com/questions/24124140/ssh-agent-forwarding-with-ansible
22,649,333
Ansible notify handlers in another role
Can I notify the handler in another role? What should I do to make ansible find it? The use case is, e.g. I want to configure some service and then restart it if changed. Different OS have probably different files to edit and even the file format can be different. So I would like to put them into different roles (because the file format can be different, it can't be done by setting group_vars). But the way to restart the service is the same, using service module; so I'd like to put the handler to common role. Is anyway to achieve this? Thanks.
Ansible notify handlers in another role Can I notify the handler in another role? What should I do to make ansible find it? The use case is, e.g. I want to configure some service and then restart it if changed. Different OS have probably different files to edit and even the file format can be different. So I would like to put them into different roles (because the file format can be different, it can't be done by setting group_vars). But the way to restart the service is the same, using service module; so I'd like to put the handler to common role. Is anyway to achieve this? Thanks.
ansible
79
66,039
5
https://stackoverflow.com/questions/22649333/ansible-notify-handlers-in-another-role
33,505,521
How to use arithmetic when setting a variable value in Ansible?
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 not ever sure that it is possible, but any help would be appreciated. vars: ramsize: '"{{ ansible_memtotal_mb }}" * .80'
How to use arithmetic when setting a variable value in Ansible? 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 not ever sure that it is possible, but any help would be appreciated. vars: ramsize: '"{{ ansible_memtotal_mb }}" * .80'
ansible
79
118,732
3
https://stackoverflow.com/questions/33505521/how-to-use-arithmetic-when-setting-a-variable-value-in-ansible
26,402,123
Ansible creating a virtualenv
How do you create a virtualenv for a specific python version using ansible. Is there a command in the ansible standard library? I would like something like: - virtualenv: dest=venv python_version:/usr/bin/python3
Ansible creating a virtualenv How do you create a virtualenv for a specific python version using ansible. Is there a command in the ansible standard library? I would like something like: - virtualenv: dest=venv python_version:/usr/bin/python3
python, ansible
78
102,272
4
https://stackoverflow.com/questions/26402123/ansible-creating-a-virtualenv
28,729,567
Skip Ansible task when running in check mode?
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 will always fail. Is there a way to mark such a task to be skipped when running in check mode? Something like: - file: state=link src={{filename}} dest=latest when: not check_mode
Skip Ansible task when running in check mode? 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 will always fail. Is there a way to mark such a task to be skipped when running in check mode? Something like: - file: state=link src={{filename}} dest=latest when: not check_mode
ansible
78
70,667
6
https://stackoverflow.com/questions/28729567/skip-ansible-task-when-running-in-check-mode
21,958,727
Where to store Ansible host file on Mac OS X
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 adjacent to the vagrant file. So my question is where would you store your hostfile for setting up a single vagrant box?
Where to store Ansible host file on Mac OS X 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 adjacent to the vagrant file. So my question is where would you store your hostfile for setting up a single vagrant box?
macos, ansible, ansible-inventory
76
60,154
6
https://stackoverflow.com/questions/21958727/where-to-store-ansible-host-file-on-mac-os-x
48,560,311
How to create a relative symlink in Ansible?
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 my symbolic link is created directly inside i99 repo / SYMLINK -> SOURCE_FOLDER But while doing it with the Ansible file module, like this: ########## Create symbolic link - name: Create symbolic link file: src: "/opt/application/i99/{{SOURCE_FOLDER}}/" dest: "/opt/application/i99/SYMLINK" state: link when: - ansible_host in groups['ihm'] My output is this : SYMLINK -> /opt/application/i99/SOURCE_FOLDER As I don't want that it points to the whole path, and I need to obtain the first format: SYMLINK -> SOURCE_FOLDER How can I do it?
How to create a relative symlink in Ansible? 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 my symbolic link is created directly inside i99 repo / SYMLINK -> SOURCE_FOLDER But while doing it with the Ansible file module, like this: ########## Create symbolic link - name: Create symbolic link file: src: "/opt/application/i99/{{SOURCE_FOLDER}}/" dest: "/opt/application/i99/SYMLINK" state: link when: - ansible_host in groups['ihm'] My output is this : SYMLINK -> /opt/application/i99/SOURCE_FOLDER As I don't want that it points to the whole path, and I need to obtain the first format: SYMLINK -> SOURCE_FOLDER How can I do it?
ansible, ansible-2.x
76
119,469
1
https://stackoverflow.com/questions/48560311/how-to-create-a-relative-symlink-in-ansible
37,427,498
How to escape double and single quotes in YAML within the same string
I need to properly escape single and double quotes in an ansible playbook in order to set the environment variable. None of this works: - name: Set environment variable command: > export EXTRA_CONFIG=“'”{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}“'” - name: Set environment variable command: > export EXTRA_CONFIG=''{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}'' - name: Set environment variable command: > export EXTRA_CONFIG=''{\"client\": {\"subscriptions\": [\"DIND-Worker\"], \"cluster\": \"internal\"}}'' Looked at this: [URL] [URL] The error message I get is: fatal: [ip.address]: FAILED! => {"changed": false, "cmd": "export 'EXTRA_CONFIG={\"client\":' '{\"subscriptions\":' '[\"DIND-Worker\"],' '\"cluster\":' '\"internal\"}}'", "failed": true, "msg": "[Errno 2] No such file or directory", "rc": 2}
How to escape double and single quotes in YAML within the same string I need to properly escape single and double quotes in an ansible playbook in order to set the environment variable. None of this works: - name: Set environment variable command: > export EXTRA_CONFIG=“'”{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}“'” - name: Set environment variable command: > export EXTRA_CONFIG=''{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}'' - name: Set environment variable command: > export EXTRA_CONFIG=''{\"client\": {\"subscriptions\": [\"DIND-Worker\"], \"cluster\": \"internal\"}}'' Looked at this: [URL] [URL] The error message I get is: fatal: [ip.address]: FAILED! => {"changed": false, "cmd": "export 'EXTRA_CONFIG={\"client\":' '{\"subscriptions\":' '[\"DIND-Worker\"],' '\"cluster\":' '\"internal\"}}'", "failed": true, "msg": "[Errno 2] No such file or directory", "rc": 2}
escaping, yaml, ansible
76
141,969
3
https://stackoverflow.com/questions/37427498/how-to-escape-double-and-single-quotes-in-yaml-within-the-same-string
25,842,718
Is Ansible a replacement for a CI tool like Hudson/Jenkins?
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. When I looked at Jenkins, it can do things like build, run tests, deploy. The missing thing in Hudson is creating/deleting an instance in cloud environments like AWS. So, in general, for what purposes do we need to use Ansible/Jenkins? For CI do I need to use a combination of Ansible and Jenkins? Please throw some light on correct usage of Ansible.
Is Ansible a replacement for a CI tool like Hudson/Jenkins? 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. When I looked at Jenkins, it can do things like build, run tests, deploy. The missing thing in Hudson is creating/deleting an instance in cloud environments like AWS. So, in general, for what purposes do we need to use Ansible/Jenkins? For CI do I need to use a combination of Ansible and Jenkins? Please throw some light on correct usage of Ansible.
jenkins, hudson, ansible
75
45,469
2
https://stackoverflow.com/questions/25842718/is-ansible-a-replacement-for-a-ci-tool-like-hudson-jenkins
18,789,545
Displaying output of a remote command with Ansible
In an Ansible role I generate the user's SSH key. After that I want to print it to the screen and pause so the user can copy and paste it somewhere else. So far I have something like this: - name: Generate SSH keys for vagrant user user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048 - name: Show SSH public key command: /bin/cat $home_directory/.ssh/id_rsa.pub - name: Wait for user to copy SSH public key pause: prompt="Please add the SSH public key above to your GitHub account" The 'Show SSH public key' task completes but doesn't show the output. TASK: [Show SSH public key] *************************************************** changed: [default] There may be a better way of going about this. I don't really like the fact that it will always show a 'changed' status. I did find this pull request for ansible - [URL] - but not sure if I can use it without writing my own module.
Displaying output of a remote command with Ansible In an Ansible role I generate the user's SSH key. After that I want to print it to the screen and pause so the user can copy and paste it somewhere else. So far I have something like this: - name: Generate SSH keys for vagrant user user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048 - name: Show SSH public key command: /bin/cat $home_directory/.ssh/id_rsa.pub - name: Wait for user to copy SSH public key pause: prompt="Please add the SSH public key above to your GitHub account" The 'Show SSH public key' task completes but doesn't show the output. TASK: [Show SSH public key] *************************************************** changed: [default] There may be a better way of going about this. I don't really like the fact that it will always show a 'changed' status. I did find this pull request for ansible - [URL] - but not sure if I can use it without writing my own module.
command-line, ssh, configuration-management, ansible
75
117,765
3
https://stackoverflow.com/questions/18789545/displaying-output-of-a-remote-command-with-ansible
34,803,467
Unexpected Exception: name &#39;basestring&#39; is not defined when invoking ansible2
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()) File "/usr/local/lib/python3.4/site-packages/ansible/cli/playbook.py", line 150, in run results = pbex.run() File "/usr/local/lib/python3.4/site-packages/ansible/executor/playbook_executor.py", line 87, in run self._tqm.load_callbacks() File "/usr/local/lib/python3.4/site-packages/ansible/executor/task_queue_manager.py", line 149, in load_callbacks elif isinstance(self._stdout_callback, basestring): NameError: name 'basestring' is not defined Here is ansible --version : ansible 2.0.0.2 config file = /etc/ansible/ansible.cfg configured module search path = Default w/o overrides And here is python --version Python 3.4.3
Unexpected Exception: name &#39;basestring&#39; is not defined when invoking ansible2 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()) File "/usr/local/lib/python3.4/site-packages/ansible/cli/playbook.py", line 150, in run results = pbex.run() File "/usr/local/lib/python3.4/site-packages/ansible/executor/playbook_executor.py", line 87, in run self._tqm.load_callbacks() File "/usr/local/lib/python3.4/site-packages/ansible/executor/task_queue_manager.py", line 149, in load_callbacks elif isinstance(self._stdout_callback, basestring): NameError: name 'basestring' is not defined Here is ansible --version : ansible 2.0.0.2 config file = /etc/ansible/ansible.cfg configured module search path = Default w/o overrides And here is python --version Python 3.4.3
python, python-3.x, ansible, ansible-2.x
74
92,190
7
https://stackoverflow.com/questions/34803467/unexpected-exception-name-basestring-is-not-defined-when-invoking-ansible2
33,857,134
Checking for multiple conditions using &quot;when&quot; on single task in ansible
I want to evaluate multiple condition in ansible using when, here is my playbook: - name: Check that the SSH Key exists local_action: module: stat path: "/home/{{ login_user.stdout }}/{{ ssh_key_location }}" register: sshkey_result - name: Generating a new SSH key for the current user it's not exists already local_action: module: user name: "{{ login_user.stdout }}" generate_ssh_key: yes ssh_key_bits: 2048 when: sshkey_result.rc == 1 and ( github_username is undefined or github_username |lower == 'none' ) here is my var file for reference: --- vpc_region: eu-west-1 key_name: my_github_key ssh_key_location: .ssh/id_rsa.pub When I try to execute this playbook, I am getting this error: TASK: [test | Check that the SSH Key exists] ********************************** ok: [localhost -> 127.0.0.1] TASK: [test | Generating a new SSH key for the current user it's not exists already] *** fatal: [localhost] => error while evaluating conditional: sshkey_result.rc == 1 and ( github_username is undefined or github_username |lower == 'none' ) FATAL: all hosts have already failed -- aborting Can somebody point me out that how we can use multiple conditions with ansible on single task. Thanks
Checking for multiple conditions using &quot;when&quot; on single task in ansible I want to evaluate multiple condition in ansible using when, here is my playbook: - name: Check that the SSH Key exists local_action: module: stat path: "/home/{{ login_user.stdout }}/{{ ssh_key_location }}" register: sshkey_result - name: Generating a new SSH key for the current user it's not exists already local_action: module: user name: "{{ login_user.stdout }}" generate_ssh_key: yes ssh_key_bits: 2048 when: sshkey_result.rc == 1 and ( github_username is undefined or github_username |lower == 'none' ) here is my var file for reference: --- vpc_region: eu-west-1 key_name: my_github_key ssh_key_location: .ssh/id_rsa.pub When I try to execute this playbook, I am getting this error: TASK: [test | Check that the SSH Key exists] ********************************** ok: [localhost -> 127.0.0.1] TASK: [test | Generating a new SSH key for the current user it's not exists already] *** fatal: [localhost] => error while evaluating conditional: sshkey_result.rc == 1 and ( github_username is undefined or github_username |lower == 'none' ) FATAL: all hosts have already failed -- aborting Can somebody point me out that how we can use multiple conditions with ansible on single task. Thanks
ansible
73
350,533
5
https://stackoverflow.com/questions/33857134/checking-for-multiple-conditions-using-when-on-single-task-in-ansible
29,399,581
Using set_facts and with_items together in Ansible
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 set_fact: foo="{{ foo }} + [ '{{ item }}' ]" with_items: - four - five - six - debug: var=foo The first task sets a fact that's a list with one item in it. The subsequent tasks append to that list with more values. The first three tasks work as expected, but the last one doesn't. Here's the output when I run this: PLAY [localhost] ************************************************************** GATHERING FACTS *************************************************************** ok: [localhost] TASK: [set fact 1] ************************************************************ ok: [localhost] TASK: [set fact 2] ************************************************************ ok: [localhost] TASK: [set fact 3] ************************************************************ ok: [localhost] TASK: [set fact 4] ************************************************************ ok: [localhost] => (item=four) ok: [localhost] => (item=five) ok: [localhost] => (item=six) TASK: [debug var=foo] ********************************************************* ok: [localhost] => { "foo": [ "zero", "one", "two", "three", "six" ] } PLAY RECAP ******************************************************************** localhost : ok=6 changed=0 unreachable=0 failed=0 Given the with_items in task 4 and the fact that the output shows the task properly iterated over the items in that list, I would have expected the result to contain all the numbers zero through six. But that last task seems to only be evaluating set_fact with the last item in the list. Is this possibly a bug in Ansible? Edit: I also just tested this on ansible 1.8 and the output was identical.
Using set_facts and with_items together in Ansible 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 set_fact: foo="{{ foo }} + [ '{{ item }}' ]" with_items: - four - five - six - debug: var=foo The first task sets a fact that's a list with one item in it. The subsequent tasks append to that list with more values. The first three tasks work as expected, but the last one doesn't. Here's the output when I run this: PLAY [localhost] ************************************************************** GATHERING FACTS *************************************************************** ok: [localhost] TASK: [set fact 1] ************************************************************ ok: [localhost] TASK: [set fact 2] ************************************************************ ok: [localhost] TASK: [set fact 3] ************************************************************ ok: [localhost] TASK: [set fact 4] ************************************************************ ok: [localhost] => (item=four) ok: [localhost] => (item=five) ok: [localhost] => (item=six) TASK: [debug var=foo] ********************************************************* ok: [localhost] => { "foo": [ "zero", "one", "two", "three", "six" ] } PLAY RECAP ******************************************************************** localhost : ok=6 changed=0 unreachable=0 failed=0 Given the with_items in task 4 and the fact that the output shows the task properly iterated over the items in that list, I would have expected the result to contain all the numbers zero through six. But that last task seems to only be evaluating set_fact with the last item in the list. Is this possibly a bug in Ansible? Edit: I also just tested this on ansible 1.8 and the output was identical.
ansible
73
165,670
7
https://stackoverflow.com/questions/29399581/using-set-facts-and-with-items-together-in-ansible
47,159,193
Why does Ansible show &quot;ERROR! no action detected in task&quot; error?
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 'playbook.yml': line 10, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: --- - name: My task name ^ here
Why does Ansible show &quot;ERROR! no action detected in task&quot; error? 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 'playbook.yml': line 10, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: --- - name: My task name ^ here
ansible
72
112,258
8
https://stackoverflow.com/questions/47159193/why-does-ansible-show-error-no-action-detected-in-task-error
35,339,512
Ansible. Fast way to check syntax?
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 checking the syntax. I want to omit errors like this: ..."msg": "AnsibleUndefinedVariable: ERROR! 'application_name' is undefined"}
Ansible. Fast way to check syntax? 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 checking the syntax. I want to omit errors like this: ..."msg": "AnsibleUndefinedVariable: ERROR! 'application_name' is undefined"}
ansible
72
174,141
4
https://stackoverflow.com/questions/35339512/ansible-fast-way-to-check-syntax
21,892,603
How to make Ansible execute a shell script if a package is not installed
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?
How to make Ansible execute a shell script if a package is not installed 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?
ansible
71
105,713
7
https://stackoverflow.com/questions/21892603/how-to-make-ansible-execute-a-shell-script-if-a-package-is-not-installed
31,186,874
Proper way to concatenate variable strings
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 confusing. Usage of set_fact module caches fact between runs. It isn't appropriate for me. Is there any other solution?
Proper way to concatenate variable strings 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 confusing. Usage of set_fact module caches fact between runs. It isn't appropriate for me. Is there any other solution?
ansible
71
254,564
3
https://stackoverflow.com/questions/31186874/proper-way-to-concatenate-variable-strings
20,798,774
How to detect why Ansible playbook hangs during execution
Some of tasks I wrote start and never end. Ansible does not provide any errors or logs that would explain this, even with -vvvv option. Playbook just hangs and passing hours doesn't change anything. When I try to run my tasks manually (by entering commands via SSH) everything is fine. Example task that hangs: - name: apt upgrade shell: apt-get upgrade Is there any way to see stdout and stderr ? I tried: - name: apt upgrade shell: apt-get upgrade register: hello - debug: msg="{{ hello.stdout }}" - debug: msg="{{ hello.stderr }}" but nothing changed. I do have required permissions and I pass correct sudo password - other tasks that require sudo execute correctly.
How to detect why Ansible playbook hangs during execution Some of tasks I wrote start and never end. Ansible does not provide any errors or logs that would explain this, even with -vvvv option. Playbook just hangs and passing hours doesn't change anything. When I try to run my tasks manually (by entering commands via SSH) everything is fine. Example task that hangs: - name: apt upgrade shell: apt-get upgrade Is there any way to see stdout and stderr ? I tried: - name: apt upgrade shell: apt-get upgrade register: hello - debug: msg="{{ hello.stdout }}" - debug: msg="{{ hello.stderr }}" but nothing changed. I do have required permissions and I pass correct sudo password - other tasks that require sudo execute correctly.
ubuntu, deployment, ansible, provisioning
71
88,560
10
https://stackoverflow.com/questions/20798774/how-to-detect-why-ansible-playbook-hangs-during-execution
58,393,840
fatal error: ffi.h: No such file or directory on pip2 install pyOpenSSL
One of the steps I always use to install / build my Ansible agent on target nodes was pip2 install pyOpenSSL . This is a requirement for your Ansible client in order to use the standard Ansible module for creating self signed certificates for example openssl_certificate Since today this no longer works. I can reproduce this message as follows: vagrant init generic/ubuntu1804 vagrant ssh sudo su - apt-get update && apt-get -y install python python-pip pip2 install pyOpenSSL The last step fails with message below. What is correct way to install pyOpenSSL on Ubuntu 18.04 at the moment? Is there a workaround for this problem? Or beter, is there a Python distribution for Ansible? That includes all dependencies so I don't have to compile build my own Ansible client? root@ubuntu1804:~# pip2 install pyOpenSSL Collecting pyOpenSSL Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fc72409d5d0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /packages/01/c8/ceb170d81bd3941cbeb9940fc6cc2ef2ca4288d0ca8929ea4db5905d904d/pyOpenSSL-19.0.0-py2.py3-none-any.whl Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fc72409d750>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /packages/01/c8/ceb170d81bd3941cbeb9940fc6cc2ef2ca4288d0ca8929ea4db5905d904d/pyOpenSSL-19.0.0-py2.py3-none-any.whl Downloading [URL] (53kB) 100% |################################| 61kB 1.0MB/s Collecting cryptography>=2.3 (from pyOpenSSL) Downloading [URL] (2.3MB) 100% |################################| 2.3MB 427kB/s Requirement already satisfied: six>=1.5.2 in /usr/lib/python2.7/dist-packages (from pyOpenSSL) Requirement already satisfied: asn1crypto>=0.21.0 in /usr/lib/python2.7/dist-packages (from cryptography>=2.3->pyOpenSSL) Requirement already satisfied: enum34; python_version < "3" in /usr/lib/python2.7/dist-packages (from cryptography>=2.3->pyOpenSSL) Requirement already satisfied: ipaddress; python_version < "3" in /usr/lib/python2.7/dist-packages (from cryptography>=2.3->pyOpenSSL) Collecting cffi!=1.11.3,>=1.8 (from cryptography>=2.3->pyOpenSSL) Downloading [URL] (459kB) 100% |################################| 460kB 299kB/s Collecting pycparser (from cffi!=1.11.3,>=1.8->cryptography>=2.3->pyOpenSSL) Downloading [URL] (158kB) 100% |################################| 163kB 280kB/s Building wheels for collected packages: cffi, pycparser Running setup.py bdist_wheel for cffi ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YCu4xd/cffi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmp_m8aI7pip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/cffi copying cffi/verifier.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/__init__.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/model.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/pkgconfig.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cparser.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/api.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/ffiplatform.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/lock.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/error.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/commontypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_gen.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/recompiler.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_include.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/parse_c_type.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_embedding.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-2.7/cffi running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/c x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-PPrPZj/python2.7-2.7.15=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2.7/c/_cffi_backend.o c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory #include <ffi.h> ^~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for cffi Running setup.py clean for cffi Running setup.py bdist_wheel for pycparser ... done Stored in directory: /root/.cache/pip/wheels/f2/9a/90/de94f8556265ddc9d9c8b271b0f63e57b26fb1d67a45564511 Successfully built pycparser Failed to build cffi Installing collected packages: pycparser, cffi, cryptography, pyOpenSSL Running setup.py install for cffi ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YCu4xd/cffi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-FxUNAq-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/cffi copying cffi/verifier.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/__init__.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/model.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/pkgconfig.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cparser.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/api.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/ffiplatform.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/lock.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/error.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/commontypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_gen.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/recompiler.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_include.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/parse_c_type.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_embedding.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-2.7/cffi running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/c x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-PPrPZj/python2.7-2.7.15=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2.7/c/_cffi_backend.o c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory #include <ffi.h> ^~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YCu4xd/cffi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-FxUNAq-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-YCu4xd/cffi/ root@ubuntu1804:~#
fatal error: ffi.h: No such file or directory on pip2 install pyOpenSSL One of the steps I always use to install / build my Ansible agent on target nodes was pip2 install pyOpenSSL . This is a requirement for your Ansible client in order to use the standard Ansible module for creating self signed certificates for example openssl_certificate Since today this no longer works. I can reproduce this message as follows: vagrant init generic/ubuntu1804 vagrant ssh sudo su - apt-get update && apt-get -y install python python-pip pip2 install pyOpenSSL The last step fails with message below. What is correct way to install pyOpenSSL on Ubuntu 18.04 at the moment? Is there a workaround for this problem? Or beter, is there a Python distribution for Ansible? That includes all dependencies so I don't have to compile build my own Ansible client? root@ubuntu1804:~# pip2 install pyOpenSSL Collecting pyOpenSSL Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fc72409d5d0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /packages/01/c8/ceb170d81bd3941cbeb9940fc6cc2ef2ca4288d0ca8929ea4db5905d904d/pyOpenSSL-19.0.0-py2.py3-none-any.whl Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fc72409d750>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /packages/01/c8/ceb170d81bd3941cbeb9940fc6cc2ef2ca4288d0ca8929ea4db5905d904d/pyOpenSSL-19.0.0-py2.py3-none-any.whl Downloading [URL] (53kB) 100% |################################| 61kB 1.0MB/s Collecting cryptography>=2.3 (from pyOpenSSL) Downloading [URL] (2.3MB) 100% |################################| 2.3MB 427kB/s Requirement already satisfied: six>=1.5.2 in /usr/lib/python2.7/dist-packages (from pyOpenSSL) Requirement already satisfied: asn1crypto>=0.21.0 in /usr/lib/python2.7/dist-packages (from cryptography>=2.3->pyOpenSSL) Requirement already satisfied: enum34; python_version < "3" in /usr/lib/python2.7/dist-packages (from cryptography>=2.3->pyOpenSSL) Requirement already satisfied: ipaddress; python_version < "3" in /usr/lib/python2.7/dist-packages (from cryptography>=2.3->pyOpenSSL) Collecting cffi!=1.11.3,>=1.8 (from cryptography>=2.3->pyOpenSSL) Downloading [URL] (459kB) 100% |################################| 460kB 299kB/s Collecting pycparser (from cffi!=1.11.3,>=1.8->cryptography>=2.3->pyOpenSSL) Downloading [URL] (158kB) 100% |################################| 163kB 280kB/s Building wheels for collected packages: cffi, pycparser Running setup.py bdist_wheel for cffi ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YCu4xd/cffi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmp_m8aI7pip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/cffi copying cffi/verifier.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/__init__.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/model.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/pkgconfig.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cparser.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/api.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/ffiplatform.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/lock.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/error.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/commontypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_gen.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/recompiler.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_include.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/parse_c_type.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_embedding.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-2.7/cffi running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/c x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-PPrPZj/python2.7-2.7.15=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2.7/c/_cffi_backend.o c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory #include <ffi.h> ^~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for cffi Running setup.py clean for cffi Running setup.py bdist_wheel for pycparser ... done Stored in directory: /root/.cache/pip/wheels/f2/9a/90/de94f8556265ddc9d9c8b271b0f63e57b26fb1d67a45564511 Successfully built pycparser Failed to build cffi Installing collected packages: pycparser, cffi, cryptography, pyOpenSSL Running setup.py install for cffi ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YCu4xd/cffi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-FxUNAq-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/cffi copying cffi/verifier.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/__init__.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/model.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/pkgconfig.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cparser.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/api.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/ffiplatform.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/lock.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/error.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/commontypes.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/vengine_gen.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/recompiler.py -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_include.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/parse_c_type.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_embedding.h -> build/lib.linux-x86_64-2.7/cffi copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-2.7/cffi running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/c x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-PPrPZj/python2.7-2.7.15=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2.7/c/_cffi_backend.o c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory #include <ffi.h> ^~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-YCu4xd/cffi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-FxUNAq-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-YCu4xd/cffi/ root@ubuntu1804:~#
python, ansible
70
97,047
6
https://stackoverflow.com/questions/58393840/fatal-error-ffi-h-no-such-file-or-directory-on-pip2-install-pyopenssl
26,732,241
Ansible - Save registered variable to file
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.log using ansible?
Ansible - Save registered variable to file 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.log using ansible?
ansible
70
196,387
5
https://stackoverflow.com/questions/26732241/ansible-save-registered-variable-to-file
36,328,907
Ansible: Get all the IP addresses of a group
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 variables containing the IP addresses of the group mainnodes : vars: main_nodes_ips: "192.168.100.101,192.168.100.102,192.168.100.103,192.168.100.104" main_nodes_ips_with_port: "192.168.100.101:3000,192.168.100.102:3000,192.168.100.103:3000,192.168.100.104:3000" This is what I got so far: vars: main_nodes_ips: "{{groups['mainnodes']|join(',')}}" main_nodes_ips_with_port: "{{groups['mainnodes']|join(':3000,')}}" but that would use the host names instead of the IP addresses. Any ideas how this could be done? Update : looking at the docs for a while, I think this would allow me to loop through all the ip adresses: {% for host in groups['mainnodes'] %} {{hostvars[host]['ansible_ssh_host']}} {% endfor %} But I just can't figure out how to create an array that holds all these IPs. So that I can use the |join() command on them. Update2: I just thought I had figured it out... but it turns out that you cannot use the {% %} syntax in the playbook... or can I? Well in the vars section it didn't. :/ vars: {% set main_nodes_ip_arr=[] %} {% for host in groups['mesos-slave'] %} {% if main_nodes_ip_arr.insert(loop.index,hostvars[host]['ansible_ssh_host']) %} {% endif %} {% endfor %} main_nodes_ips: "{{main_nodes_ip_arr|join(',')}}" main_nodes_ips_with_port: "{{main_nodes_ip_arr|join(':3000,')}}"
Ansible: Get all the IP addresses of a group 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 variables containing the IP addresses of the group mainnodes : vars: main_nodes_ips: "192.168.100.101,192.168.100.102,192.168.100.103,192.168.100.104" main_nodes_ips_with_port: "192.168.100.101:3000,192.168.100.102:3000,192.168.100.103:3000,192.168.100.104:3000" This is what I got so far: vars: main_nodes_ips: "{{groups['mainnodes']|join(',')}}" main_nodes_ips_with_port: "{{groups['mainnodes']|join(':3000,')}}" but that would use the host names instead of the IP addresses. Any ideas how this could be done? Update : looking at the docs for a while, I think this would allow me to loop through all the ip adresses: {% for host in groups['mainnodes'] %} {{hostvars[host]['ansible_ssh_host']}} {% endfor %} But I just can't figure out how to create an array that holds all these IPs. So that I can use the |join() command on them. Update2: I just thought I had figured it out... but it turns out that you cannot use the {% %} syntax in the playbook... or can I? Well in the vars section it didn't. :/ vars: {% set main_nodes_ip_arr=[] %} {% for host in groups['mesos-slave'] %} {% if main_nodes_ip_arr.insert(loop.index,hostvars[host]['ansible_ssh_host']) %} {% endif %} {% endfor %} main_nodes_ips: "{{main_nodes_ip_arr|join(',')}}" main_nodes_ips_with_port: "{{main_nodes_ip_arr|join(':3000,')}}"
jinja2, ansible
70
107,705
10
https://stackoverflow.com/questions/36328907/ansible-get-all-the-ip-addresses-of-a-group
26,677,064
Create and use group without restart
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 again. I have tried some stuff like: su -l USERNAME or newgrp docker; newgrp But nothing worked. Is there any change to force Ansible to reconnect to the host and does a relogin? A reboot would be the last option.
Create and use group without restart 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 again. I have tried some stuff like: su -l USERNAME or newgrp docker; newgrp But nothing worked. Is there any change to force Ansible to reconnect to the host and does a relogin? A reboot would be the last option.
ansible
70
21,957
4
https://stackoverflow.com/questions/26677064/create-and-use-group-without-restart
25,617,273
Pass array in --extra-vars
How can I pass YAML array to --extra-vars in Ansible playbook? I mean if I have a playbook: - hosts: "{{ hostName }}" remote_user: admin Then I should call my playbook like ansible-playbook DeployWar.yml \ --extra-vars="hostName=tomcat-webApp" But I want to run this playbook on two servers say tomcat-webApp and tomcat-all , and I want to control it from outside, i.e.: using --extra-vars . What I have tried to do is: ansible-playbook DeployWar.yml \ --extra-vars="hostName=[tomcat-webApp, tomcat-all]" ansible-playbook DeployWar.yml \ --extra-vars="hostName={tomcat-webApp, tomcat-all}" ansible-playbook DeployWar.yml \ --extra-vars="[{hostName: tomcat-webApp}, {hostName: tomcat-all}]" But in all cases my playbook fails declaring a syntax error in my call.
Pass array in --extra-vars How can I pass YAML array to --extra-vars in Ansible playbook? I mean if I have a playbook: - hosts: "{{ hostName }}" remote_user: admin Then I should call my playbook like ansible-playbook DeployWar.yml \ --extra-vars="hostName=tomcat-webApp" But I want to run this playbook on two servers say tomcat-webApp and tomcat-all , and I want to control it from outside, i.e.: using --extra-vars . What I have tried to do is: ansible-playbook DeployWar.yml \ --extra-vars="hostName=[tomcat-webApp, tomcat-all]" ansible-playbook DeployWar.yml \ --extra-vars="hostName={tomcat-webApp, tomcat-all}" ansible-playbook DeployWar.yml \ --extra-vars="[{hostName: tomcat-webApp}, {hostName: tomcat-all}]" But in all cases my playbook fails declaring a syntax error in my call.
yaml, ansible
70
129,343
7
https://stackoverflow.com/questions/25617273/pass-array-in-extra-vars
34,722,761
Ansible: read remote file
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 github. These keys are setting by an object in var files so I loop like this to generate it: tasks: - name: Create ssh key user: name: "{{sshConfigFile.user}}" generate_ssh_key: yes ssh_key_file: ".ssh/{{item.value.file}}" state: present with_dict: "{{sshConfiguration}}" It works very fine but how read these keys to send it to github via the API ?
Ansible: read remote file 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 github. These keys are setting by an object in var files so I loop like this to generate it: tasks: - name: Create ssh key user: name: "{{sshConfigFile.user}}" generate_ssh_key: yes ssh_key_file: ".ssh/{{item.value.file}}" state: present with_dict: "{{sshConfiguration}}" It works very fine but how read these keys to send it to github via the API ?
ansible
69
110,719
6
https://stackoverflow.com/questions/34722761/ansible-read-remote-file
30,328,506
Check if service exists with Ansible
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 anything else. And then there might be new hosts, which don't have the service yet. So I can't simply use service: name={{service_name}} state=stopped , because this will fail on new hosts. How I can I achieve this? Here's what I have so far: - name: Check if Service Exists shell: "if chkconfig --list | grep -q my_service; then echo true; else echo false; fi;" register: service_exists # This should only execute on hosts where the service is present - name: Stop Service service: name={{service_name}} state=stopped when: service_exists register: service_stopped # This too - name: Remove Old App Folder command: rm -rf {{app_target_folder}} when: service_exists # This should be executed on all hosts, but only after the service has stopped, if it was present - name: Unpack App Archive unarchive: src=../target/{{app_tar_name}} dest=/opt
Check if service exists with Ansible 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 anything else. And then there might be new hosts, which don't have the service yet. So I can't simply use service: name={{service_name}} state=stopped , because this will fail on new hosts. How I can I achieve this? Here's what I have so far: - name: Check if Service Exists shell: "if chkconfig --list | grep -q my_service; then echo true; else echo false; fi;" register: service_exists # This should only execute on hosts where the service is present - name: Stop Service service: name={{service_name}} state=stopped when: service_exists register: service_stopped # This too - name: Remove Old App Folder command: rm -rf {{app_target_folder}} when: service_exists # This should be executed on all hosts, but only after the service has stopped, if it was present - name: Unpack App Archive unarchive: src=../target/{{app_tar_name}} dest=/opt
centos, ansible
68
145,141
9
https://stackoverflow.com/questions/30328506/check-if-service-exists-with-ansible
25,422,771
merging dictionaries in ansible
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 attempt merging the # two dictionaries (which doesn't work): - debug: msg="{{ item.key }} = {{ item.value }}" with_dict: my_default_values + my_values # I have also tried: - debug: msg="{{ item.key }} = {{ item.value }}" with_dict: my_default_values|union(my_values) # I have /some/ success with using j2's update, # but you can't use j2 syntax in "with_dict", it appears. # This works: - debug: msg="{{ my_default_values.update(my_values) }}" # But this doesn't: - debug: msg="{{ item.key }} = {{ item.value }}" with_dict: my_default_values.update(my_values) Is there a way to merge two dictionaries, so I can use it with "with_dict"?
merging dictionaries in ansible 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 attempt merging the # two dictionaries (which doesn't work): - debug: msg="{{ item.key }} = {{ item.value }}" with_dict: my_default_values + my_values # I have also tried: - debug: msg="{{ item.key }} = {{ item.value }}" with_dict: my_default_values|union(my_values) # I have /some/ success with using j2's update, # but you can't use j2 syntax in "with_dict", it appears. # This works: - debug: msg="{{ my_default_values.update(my_values) }}" # But this doesn't: - debug: msg="{{ item.key }} = {{ item.value }}" with_dict: my_default_values.update(my_values) Is there a way to merge two dictionaries, so I can use it with "with_dict"?
python, dictionary, merge, ansible
68
115,069
6
https://stackoverflow.com/questions/25422771/merging-dictionaries-in-ansible
41,610,207
How to get the first element of a list from the output of setup module in Ansible?
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_threads_per_core": 1, I want to retrieve the 1st value of ansible_processor and use it in a Jinja2 template. If I use {{ ansible_processor }} , it's giving me both values: "AuthenticAMD", "AMD PRO A10-8700B R6, 10 Compute Cores 4C+6G" But I want only the first one.
How to get the first element of a list from the output of setup module in Ansible? 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_threads_per_core": 1, I want to retrieve the 1st value of ansible_processor and use it in a Jinja2 template. If I use {{ ansible_processor }} , it's giving me both values: "AuthenticAMD", "AMD PRO A10-8700B R6, 10 Compute Cores 4C+6G" But I want only the first one.
ansible, jinja2, ansible-facts, ansible-template
67
158,315
3
https://stackoverflow.com/questions/41610207/how-to-get-the-first-element-of-a-list-from-the-output-of-setup-module-in-ansibl
31,323,604
Ansible date variable
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 -m setup -a "filter=ansible_date_time" localhost | success >> { "ansible_facts": { "ansible_date_time": { "date": "2015-07-09", "day": "09", "epoch": "1436460014", "hour": "10", "iso8601": "2015-07-09T16:40:14Z", "iso8601_micro": "2015-07-09T16:40:14.795637Z", "minute": "40", "month": "07", "second": "14", "time": "10:40:14", "tz": "MDT", "tz_offset": "-0600", "weekday": "Thursday", "year": "2015" } }, "changed": false } So, it's CLEARLY there. But when I run... $ ansible localhost -a "echo {{ ansible_facts.ansible_date_time.date }}" localhost | FAILED => One or more undefined variables: 'ansible_facts' is undefined $ ansible localhost -a "echo {{ ansible_date_time.date }}" localhost | FAILED => One or more undefined variables: 'ansible_date_time' is undefined $ ansible localhost -a "echo {{ date }}" localhost | FAILED => One or more undefined variables: 'date' is undefined What am I not getting here? How do I use Facts as variables?
Ansible date variable 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 -m setup -a "filter=ansible_date_time" localhost | success >> { "ansible_facts": { "ansible_date_time": { "date": "2015-07-09", "day": "09", "epoch": "1436460014", "hour": "10", "iso8601": "2015-07-09T16:40:14Z", "iso8601_micro": "2015-07-09T16:40:14.795637Z", "minute": "40", "month": "07", "second": "14", "time": "10:40:14", "tz": "MDT", "tz_offset": "-0600", "weekday": "Thursday", "year": "2015" } }, "changed": false } So, it's CLEARLY there. But when I run... $ ansible localhost -a "echo {{ ansible_facts.ansible_date_time.date }}" localhost | FAILED => One or more undefined variables: 'ansible_facts' is undefined $ ansible localhost -a "echo {{ ansible_date_time.date }}" localhost | FAILED => One or more undefined variables: 'ansible_date_time' is undefined $ ansible localhost -a "echo {{ date }}" localhost | FAILED => One or more undefined variables: 'date' is undefined What am I not getting here? How do I use Facts as variables?
ansible, fact
67
188,286
6
https://stackoverflow.com/questions/31323604/ansible-date-variable