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
|
|---|---|---|---|---|---|---|---|---|
33,795,607
|
How to define private SSH keys for servers in dynamic inventories
|
I ran into a configuration problem when coding an Ansible playbook for SSH private key files. In static Ansible inventories, I can define combinations of host servers, IP addresses, and related SSH private keys - but I have no idea how to define those with dynamic inventories. For example: --- - hosts: tag_Name_server1 gather_facts: no roles: - role1 - hosts: tag_Name_server2 gather_facts: no roles: - roles2 I use the below command to call that playbook: ansible-playbook test.yml -i ec2.py --private-key ~/.ssh/SSHKEY.pem My questions are: How can I define ~/.ssh/SSHKEY.pem in Ansible files rather than on the command line? Is there a parameter in playbooks (like gather_facts ) to define which private keys should be used which hosts? If there is no way to define private keys in files, what should be called on the command line when different keys are used for different hosts in the same inventory?
|
How to define private SSH keys for servers in dynamic inventories I ran into a configuration problem when coding an Ansible playbook for SSH private key files. In static Ansible inventories, I can define combinations of host servers, IP addresses, and related SSH private keys - but I have no idea how to define those with dynamic inventories. For example: --- - hosts: tag_Name_server1 gather_facts: no roles: - role1 - hosts: tag_Name_server2 gather_facts: no roles: - roles2 I use the below command to call that playbook: ansible-playbook test.yml -i ec2.py --private-key ~/.ssh/SSHKEY.pem My questions are: How can I define ~/.ssh/SSHKEY.pem in Ansible files rather than on the command line? Is there a parameter in playbooks (like gather_facts ) to define which private keys should be used which hosts? If there is no way to define private keys in files, what should be called on the command line when different keys are used for different hosts in the same inventory?
|
ansible
| 67
| 155,716
| 5
|
https://stackoverflow.com/questions/33795607/how-to-define-private-ssh-keys-for-servers-in-dynamic-inventories
|
45,908,067
|
What's the difference between inventory_hostname and ansible_hostname
|
All I could find was this from the docs : Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for other mysterious reasons. If you have a long FQDN, inventory_hostname_short also contains the part up to the first period, without the rest of the domain. Is there any actual difference between inventory_hostname and ansible_hostname variables in Ansible? If so, then which one should I use and when?
|
What's the difference between inventory_hostname and ansible_hostname All I could find was this from the docs : Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for other mysterious reasons. If you have a long FQDN, inventory_hostname_short also contains the part up to the first period, without the rest of the domain. Is there any actual difference between inventory_hostname and ansible_hostname variables in Ansible? If so, then which one should I use and when?
|
ansible
| 67
| 175,747
| 1
|
https://stackoverflow.com/questions/45908067/whats-the-difference-between-inventory-hostname-and-ansible-hostname
|
29,258,759
|
How to specify ansible pretasks for a role?
|
How should one go about defining a pretask for role dependencies. I currently have an apache role that has a user variable so in my own role in <role>/meta/main.yml I do something like: --- dependencies: - { role: apache, user: proxy } The problem at this point is that I still don't have the user I specify and when the role tries to start apache server under a non existent user, I get an error. I tried creating a task in <role>/tasks/main.yml like: --- - user: name=proxy But the user gets created only after running the apache task in dependencies (which is to be expected). So, is there a way to create a task that would create a user before running roles in dependencies?
|
How to specify ansible pretasks for a role? How should one go about defining a pretask for role dependencies. I currently have an apache role that has a user variable so in my own role in <role>/meta/main.yml I do something like: --- dependencies: - { role: apache, user: proxy } The problem at this point is that I still don't have the user I specify and when the role tries to start apache server under a non existent user, I get an error. I tried creating a task in <role>/tasks/main.yml like: --- - user: name=proxy But the user gets created only after running the apache task in dependencies (which is to be expected). So, is there a way to create a task that would create a user before running roles in dependencies?
|
dependencies, ansible, role
| 67
| 118,155
| 6
|
https://stackoverflow.com/questions/29258759/how-to-specify-ansible-pretasks-for-a-role
|
37,004,686
|
How to pass a user / password in ansible command
|
I want to use Ansible as part of another Python software. in that software I have a hosts list with their user / password. Is there a way to pass the user / pass of the SSH connection to the Ansible ad-hoc command or write it in any file in encrypted way? Or do i understand it all wrong, and the only way to do it is with SSH certification?
|
How to pass a user / password in ansible command I want to use Ansible as part of another Python software. in that software I have a hosts list with their user / password. Is there a way to pass the user / pass of the SSH connection to the Ansible ad-hoc command or write it in any file in encrypted way? Or do i understand it all wrong, and the only way to do it is with SSH certification?
|
ssh, ansible, ansible-ad-hoc
| 66
| 364,481
| 5
|
https://stackoverflow.com/questions/37004686/how-to-pass-a-user-password-in-ansible-command
|
45,564,899
|
Extract filename from file result in Ansible
|
I'm trying to use the result of Ansible find module, which return list of files it find on a specific folder. The problem is, when I iterate over the result, I do not have the file names, I only have their full paths (including the name). Is there an easy way to use the find_result item s below to provide the file_name in the second command as shown below? - name: get files find: paths: /home/me file_type: "file" register: find_result - name: Execute docker secret create shell: docker secret create <file_name> {{ item.path }} run_once: true with_items: "{{ find_result.files }}"
|
Extract filename from file result in Ansible I'm trying to use the result of Ansible find module, which return list of files it find on a specific folder. The problem is, when I iterate over the result, I do not have the file names, I only have their full paths (including the name). Is there an easy way to use the find_result item s below to provide the file_name in the second command as shown below? - name: get files find: paths: /home/me file_type: "file" register: find_result - name: Execute docker secret create shell: docker secret create <file_name> {{ item.path }} run_once: true with_items: "{{ find_result.files }}"
|
regex, jenkins, ansible
| 66
| 84,707
| 3
|
https://stackoverflow.com/questions/45564899/extract-filename-from-file-result-in-ansible
|
29,392,369
|
Ansible SSH private key in source control?
|
I have been developing an Ansible playbook for a couple of weeks, therefore, my experience with such technology is relatively short. Part of my strategy includes using a custom ansible_ssh_user for provisioning hosts throughout the inventory, however, such user will need its own SSH key pair, which would involve some sort of a plan for holding/storing its correspondent private key. On a production environment, this playbook would be cloned/pulled and run inside a certain playbook node whose role is to provision the rest of the infrastructure. At first, I was thinking to just put that private key inside the playbook git repository, but I am having second thoughts about it nonetheless, mostly because of somewhat obvious security reasons and common sense around it, hence the reason I need to consult you about this matter. With this set on the table, here are the follow-up questions: In an Ansible-based development environment, is it sane/reasonable to hold a private SSH key in source control? Would this practice be advised only for development environments whereas another local git branch inside the playbook node would be then used to hold the actual production SSH private key? Would it be better to address this case scenario via Ansible Vault instead?, I have not ever used this before, but regardless of that I cannot yet tell whether this would be a proper case for using it. In your experience, what would be your approach around this in a production environment?, what would it be considered as the best practice in this particular scenario?
|
Ansible SSH private key in source control? I have been developing an Ansible playbook for a couple of weeks, therefore, my experience with such technology is relatively short. Part of my strategy includes using a custom ansible_ssh_user for provisioning hosts throughout the inventory, however, such user will need its own SSH key pair, which would involve some sort of a plan for holding/storing its correspondent private key. On a production environment, this playbook would be cloned/pulled and run inside a certain playbook node whose role is to provision the rest of the infrastructure. At first, I was thinking to just put that private key inside the playbook git repository, but I am having second thoughts about it nonetheless, mostly because of somewhat obvious security reasons and common sense around it, hence the reason I need to consult you about this matter. With this set on the table, here are the follow-up questions: In an Ansible-based development environment, is it sane/reasonable to hold a private SSH key in source control? Would this practice be advised only for development environments whereas another local git branch inside the playbook node would be then used to hold the actual production SSH private key? Would it be better to address this case scenario via Ansible Vault instead?, I have not ever used this before, but regardless of that I cannot yet tell whether this would be a proper case for using it. In your experience, what would be your approach around this in a production environment?, what would it be considered as the best practice in this particular scenario?
|
git, ssh, ansible, ssh-keys
| 66
| 59,258
| 2
|
https://stackoverflow.com/questions/29392369/ansible-ssh-private-key-in-source-control
|
18,572,092
|
How specify a list value as variable in ansible inventory file?
|
I need something like (ansible inventory file): [example] 127.0.0.1 timezone="Europe/Amsterdam" locales="en_US","nl_NL" However, ansible does not recognize 'locales' as a list.
|
How specify a list value as variable in ansible inventory file? I need something like (ansible inventory file): [example] 127.0.0.1 timezone="Europe/Amsterdam" locales="en_US","nl_NL" However, ansible does not recognize 'locales' as a list.
|
list, variables, ansible, inventory
| 64
| 115,011
| 7
|
https://stackoverflow.com/questions/18572092/how-specify-a-list-value-as-variable-in-ansible-inventory-file
|
55,463,849
|
How can I escape double curly braces in jinja2?
|
I need to escape double curly braces in a code I'm working on using Ansible. The thing is I have all those parameters that needs to be transformed in variables. Basically I'm working on a template creator. I've tried using {% raw %}{{ name-of-variable }}{% endraw %} but it did not work. When I tried /{/{ name-of-variable \}\} I almost got it, but I am trying to get rid of the backslashes too. Here's a bit of the code: local_action: module: replace path: "/tmp/{{ ambiance }}/{{ seed }}DEFAULT.j2" regexp: "{{ item.regexp1 }}" replace: "{{ item.replace }}" with_items: - { regexp1: '^DBHOST.*$', replace: 'DBHOST = {% raw %}{{ databasehost }}{% endraw %}' } - { regexp1: '^GLOBALHOST.*$', replace: 'GLOBALHOST = {% raw %}{{ global_hostname }}{% endraw %}' } I expect the following result: DBHOST = {{ satabasehost }} GLOBALHOST = {{ global_hostname }} Any suggestions/ideas?
|
How can I escape double curly braces in jinja2? I need to escape double curly braces in a code I'm working on using Ansible. The thing is I have all those parameters that needs to be transformed in variables. Basically I'm working on a template creator. I've tried using {% raw %}{{ name-of-variable }}{% endraw %} but it did not work. When I tried /{/{ name-of-variable \}\} I almost got it, but I am trying to get rid of the backslashes too. Here's a bit of the code: local_action: module: replace path: "/tmp/{{ ambiance }}/{{ seed }}DEFAULT.j2" regexp: "{{ item.regexp1 }}" replace: "{{ item.replace }}" with_items: - { regexp1: '^DBHOST.*$', replace: 'DBHOST = {% raw %}{{ databasehost }}{% endraw %}' } - { regexp1: '^GLOBALHOST.*$', replace: 'GLOBALHOST = {% raw %}{{ global_hostname }}{% endraw %}' } I expect the following result: DBHOST = {{ satabasehost }} GLOBALHOST = {{ global_hostname }} Any suggestions/ideas?
|
ansible, jinja2
| 64
| 63,033
| 3
|
https://stackoverflow.com/questions/55463849/how-can-i-escape-double-curly-braces-in-jinja2
|
47,342,724
|
How to make Ansible run one certain task only on one host?
|
The playbook looks like: - hosts: all tasks: - name: "run on all hosts,1" shell: something1 - name: "run on all hosts,2" shell: something2 - name: "run on one host, any host would do" shell: this_command_should_run_on_one_host - name: "run on all hosts,3" shell: something3 I know with command line option --limit , I can limit to one host. Is it possible to do it in playbook?
|
How to make Ansible run one certain task only on one host? The playbook looks like: - hosts: all tasks: - name: "run on all hosts,1" shell: something1 - name: "run on all hosts,2" shell: something2 - name: "run on one host, any host would do" shell: this_command_should_run_on_one_host - name: "run on all hosts,3" shell: something3 I know with command line option --limit , I can limit to one host. Is it possible to do it in playbook?
|
ansible
| 64
| 84,010
| 3
|
https://stackoverflow.com/questions/47342724/how-to-make-ansible-run-one-certain-task-only-on-one-host
|
41,194,021
|
How can I show progress for a long-running Ansible task?
|
I have a some Ansible tasks that perform unfortunately long operations - things like running an synchronization operation with an S3 folder. It's not always clear if they're progressing, or just stuck (or the ssh connection has died), so it would be nice to have some sort of progress output displayed. If the command's stdout/stderr was directly displayed, I'd see that, but Ansible captures the output. Piping output back is a difficult problem for Ansible to solve in its current form . But are there any Ansible tricks I can use to provide some sort of indication that things are still moving? Current ticket is [URL]
|
How can I show progress for a long-running Ansible task? I have a some Ansible tasks that perform unfortunately long operations - things like running an synchronization operation with an S3 folder. It's not always clear if they're progressing, or just stuck (or the ssh connection has died), so it would be nice to have some sort of progress output displayed. If the command's stdout/stderr was directly displayed, I'd see that, but Ansible captures the output. Piping output back is a difficult problem for Ansible to solve in its current form . But are there any Ansible tricks I can use to provide some sort of indication that things are still moving? Current ticket is [URL]
|
ansible, ansible-2.x
| 64
| 76,661
| 5
|
https://stackoverflow.com/questions/41194021/how-can-i-show-progress-for-a-long-running-ansible-task
|
27,746,077
|
How to include vars file in a vars file with ansible?
|
Is it possible to include a vars file in Ansible into another vars file dynamically? I.e. I have vars file: --- definitions: - { product: web_v2, suite: mysuite, include: default_step.yml } - { product: prod2, suite: mysuite2, include: default_step.yml } I want the contents of default_step.yml to be added to the dictionary. Note this is in a vars file so the documentation on how to include a vars file from a task doesn't seem to apply. All I can think of is to template this file with jinja and use its {% include %} function, and then afterwards use include_vars from the main task but that seems complicated...
|
How to include vars file in a vars file with ansible? Is it possible to include a vars file in Ansible into another vars file dynamically? I.e. I have vars file: --- definitions: - { product: web_v2, suite: mysuite, include: default_step.yml } - { product: prod2, suite: mysuite2, include: default_step.yml } I want the contents of default_step.yml to be added to the dictionary. Note this is in a vars file so the documentation on how to include a vars file from a task doesn't seem to apply. All I can think of is to template this file with jinja and use its {% include %} function, and then afterwards use include_vars from the main task but that seems complicated...
|
ansible
| 64
| 171,783
| 4
|
https://stackoverflow.com/questions/27746077/how-to-include-vars-file-in-a-vars-file-with-ansible
|
47,244,834
|
How to join a list of strings in Ansible?
|
In Ansible, I have a list of strings that I want to join with newline characters to create a string, that when written to a file, becomes a series of lines. However, when I use the join() filter, it works on the inner list, the characters in the strings, and not on the outer list, the strings themselves. Here's my sample code: # Usage: ansible-playbook tst3.yaml --limit <GRP> --- - hosts: all remote_user: root tasks: - name: Create the list set_fact: my_item: "{{ item }}" with_items: - "One fish" - "Two fish" - "Red fish" - "Blue fish" register: my_item_result - name: Extract items and turn into a list set_fact: my_list: "{{ my_item_result.results | map(attribute='ansible_facts.my_item') | list }}" - name: Examine the list debug: msg: "{{ my_list }}" - name: Concatenate the public keys set_fact: my_joined_list: "{{ item | join('\n') }}" with_items: - "{{ my_list }}" - name: Examine the joined string debug: msg: "{{ my_joined_list }}" I want to get output that looks like: One fish Two fish Red fish Blue Fish What I get instead is: TASK: [Examine the joined string] ********************************************* ok: [hana-np-11.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-12.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-13.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-14.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-15.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } How do I properly concatenate a list of strings with the newline character?
|
How to join a list of strings in Ansible? In Ansible, I have a list of strings that I want to join with newline characters to create a string, that when written to a file, becomes a series of lines. However, when I use the join() filter, it works on the inner list, the characters in the strings, and not on the outer list, the strings themselves. Here's my sample code: # Usage: ansible-playbook tst3.yaml --limit <GRP> --- - hosts: all remote_user: root tasks: - name: Create the list set_fact: my_item: "{{ item }}" with_items: - "One fish" - "Two fish" - "Red fish" - "Blue fish" register: my_item_result - name: Extract items and turn into a list set_fact: my_list: "{{ my_item_result.results | map(attribute='ansible_facts.my_item') | list }}" - name: Examine the list debug: msg: "{{ my_list }}" - name: Concatenate the public keys set_fact: my_joined_list: "{{ item | join('\n') }}" with_items: - "{{ my_list }}" - name: Examine the joined string debug: msg: "{{ my_joined_list }}" I want to get output that looks like: One fish Two fish Red fish Blue Fish What I get instead is: TASK: [Examine the joined string] ********************************************* ok: [hana-np-11.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-12.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-13.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-14.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } ok: [hana-np-15.cisco.com] => { "msg": "B\nl\nu\ne\n \nf\ni\ns\nh" } How do I properly concatenate a list of strings with the newline character?
|
ansible
| 63
| 150,646
| 2
|
https://stackoverflow.com/questions/47244834/how-to-join-a-list-of-strings-in-ansible
|
21,646,033
|
Copy a file with Ansible if it doesn't exist
|
I've seen the question asked in a round about sort of way but not conclusively answered. What I want to do is straight forward. I want to copy a file index.php to the remote host at /var/www/index.php but only if it doesn't already exist. I've tried using creates and only_if but I don't think these are intended for the purpose I want here. Can anyone supply some examples of how I would go about this?
|
Copy a file with Ansible if it doesn't exist I've seen the question asked in a round about sort of way but not conclusively answered. What I want to do is straight forward. I want to copy a file index.php to the remote host at /var/www/index.php but only if it doesn't already exist. I've tried using creates and only_if but I don't think these are intended for the purpose I want here. Can anyone supply some examples of how I would go about this?
|
ansible
| 63
| 67,922
| 2
|
https://stackoverflow.com/questions/21646033/copy-a-file-with-ansible-if-it-doesnt-exist
|
42,462,435
|
Ansible provisioning ERROR! Using a SSH password instead of a key is not possible
|
I would like to provision with my three nodes from the last one by using Ansible. My host machine is Windows 10. My Vagrantfile looks like: Vagrant.configure("2") do |config| (1..3).each do |index| config.vm.define "node#{index}" do |node| node.vm.box = "ubuntu" node.vm.box = "../boxes/ubuntu_base.box" node.vm.network :private_network, ip: "192.168.10.#{10 + index}" if index == 3 node.vm.provision :setup, type: :ansible_local do |ansible| ansible.playbook = "playbook.yml" ansible.provisioning_path = "/vagrant/ansible" ansible.inventory_path = "/vagrant/ansible/hosts" ansible.limit = :all ansible.install_mode = :pip ansible.version = "2.0" end end end end end My playbook looks like: --- # my little playbook - name: My little playbook hosts: webservers gather_facts: false roles: - create_user My hosts file looks like: [webservers] 192.168.10.11 192.168.10.12 [dbservers] 192.168.10.11 192.168.10.13 [all:vars] ansible_connection=ssh ansible_ssh_user=vagrant ansible_ssh_pass=vagrant After executing vagrant up --provision I got the following error: Bringing machine 'node1' up with 'virtualbox' provider... Bringing machine 'node2' up with 'virtualbox' provider... Bringing machine 'node3' up with 'virtualbox' provider... ==> node3: Running provisioner: setup (ansible_local)... node3: Running ansible-playbook... PLAY [My little playbook] ****************************************************** TASK [create_user : Create group] ********************************************** fatal: [192.168.10.11]: FAILED! => {"failed": true, "msg": "ERROR! Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."} fatal: [192.168.10.12]: FAILED! => {"failed": true, "msg": "ERROR! Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."} PLAY RECAP ********************************************************************* 192.168.10.11 : ok=0 changed=0 unreachable=0 failed=1 192.168.10.12 : ok=0 changed=0 unreachable=0 failed=1 Ansible failed to complete successfully. Any error output should be visible above. Please fix these errors and try again. I extended my Vagrantfile with ansible.limit = :all and added [all:vars] to the hostfile, but still cannot get through the error. Has anyone encountered the same issue?
|
Ansible provisioning ERROR! Using a SSH password instead of a key is not possible I would like to provision with my three nodes from the last one by using Ansible. My host machine is Windows 10. My Vagrantfile looks like: Vagrant.configure("2") do |config| (1..3).each do |index| config.vm.define "node#{index}" do |node| node.vm.box = "ubuntu" node.vm.box = "../boxes/ubuntu_base.box" node.vm.network :private_network, ip: "192.168.10.#{10 + index}" if index == 3 node.vm.provision :setup, type: :ansible_local do |ansible| ansible.playbook = "playbook.yml" ansible.provisioning_path = "/vagrant/ansible" ansible.inventory_path = "/vagrant/ansible/hosts" ansible.limit = :all ansible.install_mode = :pip ansible.version = "2.0" end end end end end My playbook looks like: --- # my little playbook - name: My little playbook hosts: webservers gather_facts: false roles: - create_user My hosts file looks like: [webservers] 192.168.10.11 192.168.10.12 [dbservers] 192.168.10.11 192.168.10.13 [all:vars] ansible_connection=ssh ansible_ssh_user=vagrant ansible_ssh_pass=vagrant After executing vagrant up --provision I got the following error: Bringing machine 'node1' up with 'virtualbox' provider... Bringing machine 'node2' up with 'virtualbox' provider... Bringing machine 'node3' up with 'virtualbox' provider... ==> node3: Running provisioner: setup (ansible_local)... node3: Running ansible-playbook... PLAY [My little playbook] ****************************************************** TASK [create_user : Create group] ********************************************** fatal: [192.168.10.11]: FAILED! => {"failed": true, "msg": "ERROR! Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."} fatal: [192.168.10.12]: FAILED! => {"failed": true, "msg": "ERROR! Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."} PLAY RECAP ********************************************************************* 192.168.10.11 : ok=0 changed=0 unreachable=0 failed=1 192.168.10.12 : ok=0 changed=0 unreachable=0 failed=1 Ansible failed to complete successfully. Any error output should be visible above. Please fix these errors and try again. I extended my Vagrantfile with ansible.limit = :all and added [all:vars] to the hostfile, but still cannot get through the error. Has anyone encountered the same issue?
|
ssh, vagrant, ansible, ansible-inventory
| 62
| 191,106
| 8
|
https://stackoverflow.com/questions/42462435/ansible-provisioning-error-using-a-ssh-password-instead-of-a-key-is-not-possibl
|
27,315,469
|
Ansible - How to sequentially execute playbook for each host
|
I am using ansible to script a deployment for an API. I would like this to work sequentially through each host in my inventory file so that I can fully deploy to one machine at a time. With the out box behaviour, each task in my playbook is executed for each host in the inventory file before moving on to the next task. How can I change this behaviour to execute all tasks for a host before starting on the next host? Ideally I would like to only have one playbook. Thanks
|
Ansible - How to sequentially execute playbook for each host I am using ansible to script a deployment for an API. I would like this to work sequentially through each host in my inventory file so that I can fully deploy to one machine at a time. With the out box behaviour, each task in my playbook is executed for each host in the inventory file before moving on to the next task. How can I change this behaviour to execute all tasks for a host before starting on the next host? Ideally I would like to only have one playbook. Thanks
|
ansible
| 61
| 84,009
| 3
|
https://stackoverflow.com/questions/27315469/ansible-how-to-sequentially-execute-playbook-for-each-host
|
33,931,610
|
Ansible Handler notify vs register
|
So after reading Ansible docs, I found out that Handlers are only fired when tasks report changes, so for example: some tasks ... notify: nginx_restart # our handler - name: nginx_restart vs some tasks ... register: nginx_restart # do this after nginx_restart changes when: nginx_restart|changed Is there any difference between these 2 methods? When should I use each of them? For me, register seems to have more functionality here, unless I am missing something...
|
Ansible Handler notify vs register So after reading Ansible docs, I found out that Handlers are only fired when tasks report changes, so for example: some tasks ... notify: nginx_restart # our handler - name: nginx_restart vs some tasks ... register: nginx_restart # do this after nginx_restart changes when: nginx_restart|changed Is there any difference between these 2 methods? When should I use each of them? For me, register seems to have more functionality here, unless I am missing something...
|
ansible
| 61
| 70,957
| 3
|
https://stackoverflow.com/questions/33931610/ansible-handler-notify-vs-register
|
33,126,156
|
Is it possible to define playbook-global variables in Ansible?
|
I have a large Ansible playbook where Docker images are built when running it. I am using an increasing number as the tag to version them. Currently, I have to specify this in every hosts: section. I know there are global variables but from what I found by searching for "ansible" "global variables", they have to defined outside of the playbook. Is it possible to define global variables which are global for the playbook?
|
Is it possible to define playbook-global variables in Ansible? I have a large Ansible playbook where Docker images are built when running it. I am using an increasing number as the tag to version them. Currently, I have to specify this in every hosts: section. I know there are global variables but from what I found by searching for "ansible" "global variables", they have to defined outside of the playbook. Is it possible to define global variables which are global for the playbook?
|
ansible
| 61
| 127,221
| 4
|
https://stackoverflow.com/questions/33126156/is-it-possible-to-define-playbook-global-variables-in-ansible
|
30,226,113
|
ansible ssh prompt known_hosts issue
|
I'm running Ansible playbook and it works fine on one machine. On a new machine when I try for the first time, I get the following error. 17:04:34 PLAY [appservers] ************************************************************* 17:04:34 17:04:34 GATHERING FACTS *************************************************************** 17:04:34 fatal: [server02.cit.product-ref.dev] => {'msg': "FAILED: (22, 'Invalid argument')", 'failed': True} 17:04:34 fatal: [server01.cit.product-ref.dev] => {'msg': "FAILED: (22, 'Invalid argument')", 'failed': True} 17:04:34 17:04:34 TASK: [common | remove old ansible-tmp-*] ************************************* 17:04:34 FATAL: no hosts matched or all hosts have already failed -- aborting 17:04:34 17:04:34 17:04:34 PLAY RECAP ******************************************************************** 17:04:34 to retry, use: --limit @/var/lib/jenkins/site.retry 17:04:34 17:04:34 server01.cit.product-ref.dev : ok=0 changed=0 unreachable=1 failed=0 17:04:34 server02.cit.product-ref.dev : ok=0 changed=0 unreachable=1 failed=0 17:04:34 17:04:34 Build step 'Execute shell' marked build as failure 17:04:34 Finished: FAILURE This error can be resolved, if I first go to the source machine (from where I'm running the ansible playbook) and manually ssh to the target machine (as the given user) and enter "yes" for known_hosts file entry. Now, if I run the same ansible playbook second time, it works without an error. Therefore, how can I suppress the prompt what SSH gives while making ssh known_hosts entry for the first time for a given user (~/.ssh folder, file known_hosts)? I found I can do this if I use the following config entries in ~/.ssh/config file. ~/.ssh/config # For vapp virtual machines Host * StrictHostKeyChecking no UserKnownHostsFile=/dev/null User kobaloki LogLevel ERROR i.e. if I place the above code in the user's ~/.ssh/config file of a remote machine and try Ansible playbook for the first time, I won't be prompted for entring "yes" and playbook will run successfully (without requiring the user to manually create a known_hosts file entry from the source machine to the target/remote machine). My questions: 1. What security issues I should take care if I go ~/.ssh/config way 2. How can I pass the settings (what's there in the config file) as parameters/options to ansible at command line so that it will run first time on a new machine (without prompting / depending upon the known_hosts file entry on the source machine for the target machine?
|
ansible ssh prompt known_hosts issue I'm running Ansible playbook and it works fine on one machine. On a new machine when I try for the first time, I get the following error. 17:04:34 PLAY [appservers] ************************************************************* 17:04:34 17:04:34 GATHERING FACTS *************************************************************** 17:04:34 fatal: [server02.cit.product-ref.dev] => {'msg': "FAILED: (22, 'Invalid argument')", 'failed': True} 17:04:34 fatal: [server01.cit.product-ref.dev] => {'msg': "FAILED: (22, 'Invalid argument')", 'failed': True} 17:04:34 17:04:34 TASK: [common | remove old ansible-tmp-*] ************************************* 17:04:34 FATAL: no hosts matched or all hosts have already failed -- aborting 17:04:34 17:04:34 17:04:34 PLAY RECAP ******************************************************************** 17:04:34 to retry, use: --limit @/var/lib/jenkins/site.retry 17:04:34 17:04:34 server01.cit.product-ref.dev : ok=0 changed=0 unreachable=1 failed=0 17:04:34 server02.cit.product-ref.dev : ok=0 changed=0 unreachable=1 failed=0 17:04:34 17:04:34 Build step 'Execute shell' marked build as failure 17:04:34 Finished: FAILURE This error can be resolved, if I first go to the source machine (from where I'm running the ansible playbook) and manually ssh to the target machine (as the given user) and enter "yes" for known_hosts file entry. Now, if I run the same ansible playbook second time, it works without an error. Therefore, how can I suppress the prompt what SSH gives while making ssh known_hosts entry for the first time for a given user (~/.ssh folder, file known_hosts)? I found I can do this if I use the following config entries in ~/.ssh/config file. ~/.ssh/config # For vapp virtual machines Host * StrictHostKeyChecking no UserKnownHostsFile=/dev/null User kobaloki LogLevel ERROR i.e. if I place the above code in the user's ~/.ssh/config file of a remote machine and try Ansible playbook for the first time, I won't be prompted for entring "yes" and playbook will run successfully (without requiring the user to manually create a known_hosts file entry from the source machine to the target/remote machine). My questions: 1. What security issues I should take care if I go ~/.ssh/config way 2. How can I pass the settings (what's there in the config file) as parameters/options to ansible at command line so that it will run first time on a new machine (without prompting / depending upon the known_hosts file entry on the source machine for the target machine?
|
ssh, command-prompt, ansible, hosts-file
| 60
| 114,874
| 9
|
https://stackoverflow.com/questions/30226113/ansible-ssh-prompt-known-hosts-issue
|
28,080,145
|
Check if a list contains an item in Ansible
|
I'm trying to check if the version supplied is a valid supported version. I've set the list of acceptable versions in a variable, and I want to fail out of the task if the supplied version is not in the list. However, I'm unsure of how to do that. #/role/vars/main.yml --- acceptable_versions: [2, 3, 4] and #/role/tasks/main.yml --- - fail: msg: "unsupported version" with_items: "{{acceptable_versions}}" when: "{{item}} != {{version}}" - name: continue with rest of tasks... Above is sort of what I want to do, but I haven't been able to figure out if there's a one line way to construct a "list contains" call for the fail module.
|
Check if a list contains an item in Ansible I'm trying to check if the version supplied is a valid supported version. I've set the list of acceptable versions in a variable, and I want to fail out of the task if the supplied version is not in the list. However, I'm unsure of how to do that. #/role/vars/main.yml --- acceptable_versions: [2, 3, 4] and #/role/tasks/main.yml --- - fail: msg: "unsupported version" with_items: "{{acceptable_versions}}" when: "{{item}} != {{version}}" - name: continue with rest of tasks... Above is sort of what I want to do, but I haven't been able to figure out if there's a one line way to construct a "list contains" call for the fail module.
|
yaml, ansible
| 60
| 136,916
| 2
|
https://stackoverflow.com/questions/28080145/check-if-a-list-contains-an-item-in-ansible
|
31,054,453
|
Ansible - actions BEFORE gathering facts
|
Does anyone know how to do something (like wait for port / boot of the managed node) BEFORE gathering facts? I know I can turn gathering facts off gather_facts: no and THEN wait for port but what if I need the facts while also still need to wait until the node boots up?
|
Ansible - actions BEFORE gathering facts Does anyone know how to do something (like wait for port / boot of the managed node) BEFORE gathering facts? I know I can turn gathering facts off gather_facts: no and THEN wait for port but what if I need the facts while also still need to wait until the node boots up?
|
ansible, ansible-facts
| 60
| 28,354
| 3
|
https://stackoverflow.com/questions/31054453/ansible-actions-before-gathering-facts
|
21,820,444
|
Nginx error: (13: Permission denied) while connecting to upstream
|
I am getting this error in my nginx-error.log file: 2014/02/17 03:42:20 [crit] 5455#0: *1 connect() to unix:/tmp/uwsgi.sock failed (13: Permission denied) while connecting to upstream, client: xx.xx.x.xxx, server: localhost, request: "GET /users HTTP/1.1", upstream: "uwsgi://unix:/tmp/uwsgi.sock:", host: "EC2.amazonaws.com" The browser also shows a 502 Bad Gateway Error. The output of a curl is the same, Bad Gateway html I've tried to fix it by changing permissions for /tmp/uwsgi.sock to 777. That didn't work. I also added myself to the www-data group (a couple questions that looked similar suggested that). Also, no dice. Here is my nginx.conf file: nginx.conf worker_processes 1; worker_rlimit_nofile 8192; events { worker_connections 3000; } error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } I am running a Flask application with Nginsx and Uwsgi, just to be thorough in my explanation. If anyone has any ideas, I would really appreciate them. EDIT I have been asked to provide my uwsgi config file. So, I never personally wrote my nginx or my uwsgi file. I followed the guide here which sets everything up using ansible-playbook. The nginx.conf file was generated automatically, but there was nothing in /etc/uwsgi except a README file in both apps-enabled and apps-available folders. Do I need to create my own config file for uwsgi? I was under the impression that ansible took care of all of those things. I believe that ansible-playbook figured out my uwsgi configuration since when I run this command uwsgi -s /tmp/uwsgi.sock -w my_app:app it starts up and outputs this: *** Starting uWSGI 2.0.1 (64bit) on [Mon Feb 17 20:03:08 2014] *** compiled with version: 4.7.3 on 10 February 2014 18:26:16 os: Linux-3.11.0-15-generic #25-Ubuntu SMP Thu Jan 30 17:22:01 UTC 2014 nodename: ip-10-9-xxx-xxx machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/username/Project detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 4548 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /tmp/uwsgi.sock fd 3 Python version: 2.7.5+ (default, Sep 19 2013, 13:52:09) [GCC 4.8.1] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x1f60260 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72760 bytes (71 KB) for 1 cores *** Operational MODE: single process *** WSGI app 0 (mountpoint='') ready in 3 seconds on interpreter 0x1f60260 pid: 26790 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 26790, cores: 1)
|
Nginx error: (13: Permission denied) while connecting to upstream I am getting this error in my nginx-error.log file: 2014/02/17 03:42:20 [crit] 5455#0: *1 connect() to unix:/tmp/uwsgi.sock failed (13: Permission denied) while connecting to upstream, client: xx.xx.x.xxx, server: localhost, request: "GET /users HTTP/1.1", upstream: "uwsgi://unix:/tmp/uwsgi.sock:", host: "EC2.amazonaws.com" The browser also shows a 502 Bad Gateway Error. The output of a curl is the same, Bad Gateway html I've tried to fix it by changing permissions for /tmp/uwsgi.sock to 777. That didn't work. I also added myself to the www-data group (a couple questions that looked similar suggested that). Also, no dice. Here is my nginx.conf file: nginx.conf worker_processes 1; worker_rlimit_nofile 8192; events { worker_connections 3000; } error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } I am running a Flask application with Nginsx and Uwsgi, just to be thorough in my explanation. If anyone has any ideas, I would really appreciate them. EDIT I have been asked to provide my uwsgi config file. So, I never personally wrote my nginx or my uwsgi file. I followed the guide here which sets everything up using ansible-playbook. The nginx.conf file was generated automatically, but there was nothing in /etc/uwsgi except a README file in both apps-enabled and apps-available folders. Do I need to create my own config file for uwsgi? I was under the impression that ansible took care of all of those things. I believe that ansible-playbook figured out my uwsgi configuration since when I run this command uwsgi -s /tmp/uwsgi.sock -w my_app:app it starts up and outputs this: *** Starting uWSGI 2.0.1 (64bit) on [Mon Feb 17 20:03:08 2014] *** compiled with version: 4.7.3 on 10 February 2014 18:26:16 os: Linux-3.11.0-15-generic #25-Ubuntu SMP Thu Jan 30 17:22:01 UTC 2014 nodename: ip-10-9-xxx-xxx machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/username/Project detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 4548 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /tmp/uwsgi.sock fd 3 Python version: 2.7.5+ (default, Sep 19 2013, 13:52:09) [GCC 4.8.1] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x1f60260 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72760 bytes (71 KB) for 1 cores *** Operational MODE: single process *** WSGI app 0 (mountpoint='') ready in 3 seconds on interpreter 0x1f60260 pid: 26790 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 26790, cores: 1)
|
nginx, flask, uwsgi, ansible
| 60
| 92,155
| 8
|
https://stackoverflow.com/questions/21820444/nginx-error-13-permission-denied-while-connecting-to-upstream
|
21,158,689
|
Ansible: deploy on multiple hosts in the same time
|
Is it possible to run ansible playbook, which looks like this (it is an example from this site: [URL] ): - name: this is a play at the top level of a file hosts: all remote_user: root tasks: - name: say hi tags: foo shell: echo "hi..." - include: load_balancers.yml - include: webservers.yml - include: dbservers.yml in multithread mode? I want to run three "includes" in the same time (it is deploying to different hosts anyway), like in this diagram: [URL] Is it possible?
|
Ansible: deploy on multiple hosts in the same time Is it possible to run ansible playbook, which looks like this (it is an example from this site: [URL] ): - name: this is a play at the top level of a file hosts: all remote_user: root tasks: - name: say hi tags: foo shell: echo "hi..." - include: load_balancers.yml - include: webservers.yml - include: dbservers.yml in multithread mode? I want to run three "includes" in the same time (it is deploying to different hosts anyway), like in this diagram: [URL] Is it possible?
|
ansible
| 60
| 162,676
| 6
|
https://stackoverflow.com/questions/21158689/ansible-deploy-on-multiple-hosts-in-the-same-time
|
32,214,529
|
Ansible - using with_items and when conditional to
|
I have a bunch of servers that have four physical drives on them (/dev/sda, sdb, sdc, and sdd). sda has the OS installed on it. I need to format each drive except sda. I need to check if each drive has data on it. If it does, then I shouldn't format it. # This will get all physical disks (sda, sdb, sdc, etc) and assign them to disk_var - name: Get disks set_fact: disk_var="{{hostvars[inventory_hostname]["ansible_devices"].keys()|list}}" - name: Check if the disk is partitioned and also ignore sda stat: path=/dev/{{item}}1 with_items: disk_var when: item != 'sda' register: base_secondary_partition_{{item}} - name: Create GPT partition table command: /sbin/parted -s /dev/{{item}} mklabel gpt with_items: disk_var when: item != 'sda' and base_secondary_partition_{{item}}.stat.exists == false There's clearly more steps involved into formatting these drives but it fails at the last task when creating the GPT partition table. Here's what it looks like when it runs. You'll see that it fails at the last task: TASK: [role | Get disks] ****************************************************** ok: [server1.com] TASK: [role | Check if the disk is partitioned] ******************************* skipping: [server1.com] => (item=sda) ok: [server1.com] => (item=sdd) ok: [server1.com] => (item=sdb) ok: [server1.com] => (item=sdc) TASK: [role | Create GPT partition table] ************************************* fatal: [server1.com] => error while evaluating conditional: base_secondary_partition_sdd.stat.exists == false FATAL: all hosts have already failed -- aborting Any idea how I can check the conditional base_secondary_partition_{{item}}.stat.exists ? I need to make sure that if there's data on the drive, it will not format it.
|
Ansible - using with_items and when conditional to I have a bunch of servers that have four physical drives on them (/dev/sda, sdb, sdc, and sdd). sda has the OS installed on it. I need to format each drive except sda. I need to check if each drive has data on it. If it does, then I shouldn't format it. # This will get all physical disks (sda, sdb, sdc, etc) and assign them to disk_var - name: Get disks set_fact: disk_var="{{hostvars[inventory_hostname]["ansible_devices"].keys()|list}}" - name: Check if the disk is partitioned and also ignore sda stat: path=/dev/{{item}}1 with_items: disk_var when: item != 'sda' register: base_secondary_partition_{{item}} - name: Create GPT partition table command: /sbin/parted -s /dev/{{item}} mklabel gpt with_items: disk_var when: item != 'sda' and base_secondary_partition_{{item}}.stat.exists == false There's clearly more steps involved into formatting these drives but it fails at the last task when creating the GPT partition table. Here's what it looks like when it runs. You'll see that it fails at the last task: TASK: [role | Get disks] ****************************************************** ok: [server1.com] TASK: [role | Check if the disk is partitioned] ******************************* skipping: [server1.com] => (item=sda) ok: [server1.com] => (item=sdd) ok: [server1.com] => (item=sdb) ok: [server1.com] => (item=sdc) TASK: [role | Create GPT partition table] ************************************* fatal: [server1.com] => error while evaluating conditional: base_secondary_partition_sdd.stat.exists == false FATAL: all hosts have already failed -- aborting Any idea how I can check the conditional base_secondary_partition_{{item}}.stat.exists ? I need to make sure that if there's data on the drive, it will not format it.
|
ansible
| 60
| 160,819
| 2
|
https://stackoverflow.com/questions/32214529/ansible-using-with-items-and-when-conditional-to
|
20,176,957
|
user vs sudo vs sudo_user in ansible playbooks
|
I have read the Ansible documentation but I am still a bit confused about the three following parameters in ansible playbooks: user, sudo, sudo_user. I have tried the following playbooks with different combination of the parameters: user:deploy => Works user:deploy and sudo: True => Hangs on the git task user:deploy, sudo: True and sudo_user: deploy => Works What does sudo_user actually do? When and why should I use each of these combinations? - hosts: all user: deploy sudo: True sudo_user: deploy tasks: - name: Ensure code directory file: dest=/home/deploy/code state=directory - name: Deploy app git: repo=git@bitbucket.org:YAmikep/djangotutorial.git dest=/home/deploy/code Thanks
|
user vs sudo vs sudo_user in ansible playbooks I have read the Ansible documentation but I am still a bit confused about the three following parameters in ansible playbooks: user, sudo, sudo_user. I have tried the following playbooks with different combination of the parameters: user:deploy => Works user:deploy and sudo: True => Hangs on the git task user:deploy, sudo: True and sudo_user: deploy => Works What does sudo_user actually do? When and why should I use each of these combinations? - hosts: all user: deploy sudo: True sudo_user: deploy tasks: - name: Ensure code directory file: dest=/home/deploy/code state=directory - name: Deploy app git: repo=git@bitbucket.org:YAmikep/djangotutorial.git dest=/home/deploy/code Thanks
|
sudo, ansible
| 60
| 66,427
| 1
|
https://stackoverflow.com/questions/20176957/user-vs-sudo-vs-sudo-user-in-ansible-playbooks
|
39,183,100
|
Define `become=yes' per role with Ansible
|
In my system provisioning with Ansible, I don't want to specify become=yes in every task, so I created the following ansible.cfg in the project main directory, and Ansible automatically runs everything as root: [privilege_escalation] become = True But as the project kept growing, some new roles should not be run as root. I would like to know if it is possible to have some instruction inside the role that all tasks whithin that role should be run as root (eg. something in vars/), instead of the global ansible.cfg solution above!
|
Define `become=yes' per role with Ansible In my system provisioning with Ansible, I don't want to specify become=yes in every task, so I created the following ansible.cfg in the project main directory, and Ansible automatically runs everything as root: [privilege_escalation] become = True But as the project kept growing, some new roles should not be run as root. I would like to know if it is possible to have some instruction inside the role that all tasks whithin that role should be run as root (eg. something in vars/), instead of the global ansible.cfg solution above!
|
ansible
| 59
| 69,948
| 7
|
https://stackoverflow.com/questions/39183100/define-become-yes-per-role-with-ansible
|
22,201,306
|
Ansible Galaxy roles install in to a specific directory?
|
So I figured I should start using Ansible Galaxy when possible, instead of writing my own roles. I just installed my first role and it was installed to /etc/local/ansible/roles (I am on OSX). Now I wonder how you install this roles where I actually need it? Do I just copy the role to where I need it or is there an Ansible way of doing it?
|
Ansible Galaxy roles install in to a specific directory? So I figured I should start using Ansible Galaxy when possible, instead of writing my own roles. I just installed my first role and it was installed to /etc/local/ansible/roles (I am on OSX). Now I wonder how you install this roles where I actually need it? Do I just copy the role to where I need it or is there an Ansible way of doing it?
|
ansible, ansible-galaxy
| 59
| 62,193
| 6
|
https://stackoverflow.com/questions/22201306/ansible-galaxy-roles-install-in-to-a-specific-directory
|
35,021,384
|
How can I run a ansible task only if a file or directory does NOT exist?
|
In an Ansible playbook I want to run tasks if a directory does not exists. - name: Check for java exists in /opt stat: path=/opt/jdk1.8.0_71 register: p when: p.stat.isdir is defined and p.stat.isdir But what must I do to ensure that the following tasks runs only if this dir does not exist? - name: Extract java if dir not existing command: tar xzf /tmp/jdk1.8.0_71 chdir=/opt
|
How can I run a ansible task only if a file or directory does NOT exist? In an Ansible playbook I want to run tasks if a directory does not exists. - name: Check for java exists in /opt stat: path=/opt/jdk1.8.0_71 register: p when: p.stat.isdir is defined and p.stat.isdir But what must I do to ensure that the following tasks runs only if this dir does not exist? - name: Extract java if dir not existing command: tar xzf /tmp/jdk1.8.0_71 chdir=/opt
|
ansible
| 59
| 89,807
| 2
|
https://stackoverflow.com/questions/35021384/how-can-i-run-a-ansible-task-only-if-a-file-or-directory-does-not-exist
|
22,758,925
|
Abort execution of remaining task if certain condition is failed
|
I want to abort execution of remaining task if certain condition is failed. and display proper error message. So instead of skipping remaining task I want to show error message and stop execution of ansible playbook. Lets say I am running below command $ ansible-playbook playbook.yml -e "param1=value1 param2=value" My playbook look like this:- playbook.yml:- --- - hosts: local user: roop gather_facts: no vars: {param1: "", param2: ""} tasks: #check whether param1 defined - name: 'Check for valid param1' shell: echo {{ param1 }} register: isValidParam1 when: param1 !="" #check if param1 is null or invalid - name: 'check if param1 is null or invalid' debug: msg="Please enter correct param1" when: param1 == "" #check whether param2 defined - name: 'Check for valid param2' shell: echo {{ param2 }} register: isValidParam2 when: param2 != "" #check if param2 is null or invalid - name: 'check if param2 is null or invalid' debug: msg="Please enter correct param2" when: param2 == "" #check params is valid and defined - name: 'Check for valid params' shell: echo "param1={{ param1 }} param2={{ param2 }} register: validParams when: isValidParam1 is defined and isValidParam2 is defined #check if params are invalid then abort below all tasks. - name: 'check if validParams is null or invalid' debug: msg="Please enter correct Params" when: validParams is not defined # based on validParams, and different value of param1 more than 10 task executing. As I have mentioned in my last task comment. I am executing more than 10 task based on validParams and param1 different value. What I need here if validParams is undefined then abort all execution and show error messages. Is there any efficient way to do this . Please suggest me.
|
Abort execution of remaining task if certain condition is failed I want to abort execution of remaining task if certain condition is failed. and display proper error message. So instead of skipping remaining task I want to show error message and stop execution of ansible playbook. Lets say I am running below command $ ansible-playbook playbook.yml -e "param1=value1 param2=value" My playbook look like this:- playbook.yml:- --- - hosts: local user: roop gather_facts: no vars: {param1: "", param2: ""} tasks: #check whether param1 defined - name: 'Check for valid param1' shell: echo {{ param1 }} register: isValidParam1 when: param1 !="" #check if param1 is null or invalid - name: 'check if param1 is null or invalid' debug: msg="Please enter correct param1" when: param1 == "" #check whether param2 defined - name: 'Check for valid param2' shell: echo {{ param2 }} register: isValidParam2 when: param2 != "" #check if param2 is null or invalid - name: 'check if param2 is null or invalid' debug: msg="Please enter correct param2" when: param2 == "" #check params is valid and defined - name: 'Check for valid params' shell: echo "param1={{ param1 }} param2={{ param2 }} register: validParams when: isValidParam1 is defined and isValidParam2 is defined #check if params are invalid then abort below all tasks. - name: 'check if validParams is null or invalid' debug: msg="Please enter correct Params" when: validParams is not defined # based on validParams, and different value of param1 more than 10 task executing. As I have mentioned in my last task comment. I am executing more than 10 task based on validParams and param1 different value. What I need here if validParams is undefined then abort all execution and show error messages. Is there any efficient way to do this . Please suggest me.
|
ansible
| 59
| 116,638
| 3
|
https://stackoverflow.com/questions/22758925/abort-execution-of-remaining-task-if-certain-condition-is-failed
|
29,003,420
|
Reload Ansible's dynamic inventory
|
I'm using Ansible to setup EC2 instances and deploy an application. There's a hosts script which gathers tags related servers and groups info. I'd like to run these actions as a single playbook, so New instances are created if needed Hosts script loads inventory (including servers' facts) Deployment playbook works However, the inventory is loaded in advance, so, there is no servers/groups data if servers are created/updated during the play. I can separate provision and deployment playbooks use add_host trick to emulate dynamic inventory when servers are updated But, there are drawbacks in those approaches. Can I force Ansible to reload inventory? My test files are: hosts script: #!/bin/sh echo date >> log.log echo "{\"standalone\":[\"localhost\"]}" Sample playbook.yml : --- - hosts: all tasks: - name: show inventory_hostname command: echo {{ inventory_hostname }} I run it with the command ansible-playbook -i hosts playbook.yml -v and see two runs: $> cat log.log Thu Mar 12 09:43:16 SAMT 2015 Thu Mar 12 09:43:16 SAMT 2015 but I haven't found a command to double it.
|
Reload Ansible's dynamic inventory I'm using Ansible to setup EC2 instances and deploy an application. There's a hosts script which gathers tags related servers and groups info. I'd like to run these actions as a single playbook, so New instances are created if needed Hosts script loads inventory (including servers' facts) Deployment playbook works However, the inventory is loaded in advance, so, there is no servers/groups data if servers are created/updated during the play. I can separate provision and deployment playbooks use add_host trick to emulate dynamic inventory when servers are updated But, there are drawbacks in those approaches. Can I force Ansible to reload inventory? My test files are: hosts script: #!/bin/sh echo date >> log.log echo "{\"standalone\":[\"localhost\"]}" Sample playbook.yml : --- - hosts: all tasks: - name: show inventory_hostname command: echo {{ inventory_hostname }} I run it with the command ansible-playbook -i hosts playbook.yml -v and see two runs: $> cat log.log Thu Mar 12 09:43:16 SAMT 2015 Thu Mar 12 09:43:16 SAMT 2015 but I haven't found a command to double it.
|
ansible, ansible-inventory
| 58
| 38,103
| 7
|
https://stackoverflow.com/questions/29003420/reload-ansibles-dynamic-inventory
|
33,280,244
|
SSH Error: Permission denied (publickey,password) in Ansible
|
I am new to Ansible and I am trying to implement it. I tried all the possible ways present on the Internet and also all questions related to it, but still I can't resolve the error. How can I fix it? I installed Ansible playbook on my MacBook Pro. I created a VM whose IP address is 10.4.1.141 and host IP address is 10.4.1.140. I tried to connect to my VM using the host via SSH. It connected by the following command: ssh user@10.4.1.141 And I got the shell access. This means my SSH connection is working fine. Now I tried the following command for Ansible: ansible all -m ping And the content in the /etc/ansible/host is 10.4.1.141 . Then it shows the following error: 10.4.1.141 | FAILED => SSH Error: Permission denied (publickey,password). while connecting to 10.4.1.141:22 It is sometimes useful to rerun the command using -vvvv , which prints SSH debug output to help diagnose the issue. Then I tried creating the config file in .ssh/ folder on the host machine, but the error is still the same. The content of the config file is: IdentityFile ~/.ssh/id_rsa which is the path to my private key. Then I ran the same command ansible all -m ping and got the same error again. When I tried another command, ansible all -m ping -u user --ask-pass Then it asked for the SSH password. I gave it (I am very sure the password is correct), but I got this error: 10.4.1.141 | FAILED => FAILED: Authentication failed. This is the log using -vvvv : <10.4.1.141> ESTABLISH CONNECTION FOR USER: rajatg <10.4.1.141> REMOTE_MODULE ping <10.4.1.141> EXEC ssh -C -tt -vvv -o ControlMaster=auto -o ControlPersist=60s -o ControlPath="/Users/rajatg/.ansible/cp/ansible-ssh-%h-%p-%r" -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 10.4.1.141 /bin/sh -c 'mkdir -p $HOME/.ansible/tmp/ansible-tmp-1445512455.7-116096114788007 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1445512455.7-116096114788007 && echo $HOME/.ansible/tmp/ansible-tmp-1445512455.7-116096114788007' 10.4.1.141 | FAILED => SSH Error: Permission denied (publickey,password). while connecting to 10.4.1.141:22 It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue. I am still not able to figure it out what the problem is. It is my last choice to ask it here after doing my all research. This is the link I referred to .
|
SSH Error: Permission denied (publickey,password) in Ansible I am new to Ansible and I am trying to implement it. I tried all the possible ways present on the Internet and also all questions related to it, but still I can't resolve the error. How can I fix it? I installed Ansible playbook on my MacBook Pro. I created a VM whose IP address is 10.4.1.141 and host IP address is 10.4.1.140. I tried to connect to my VM using the host via SSH. It connected by the following command: ssh user@10.4.1.141 And I got the shell access. This means my SSH connection is working fine. Now I tried the following command for Ansible: ansible all -m ping And the content in the /etc/ansible/host is 10.4.1.141 . Then it shows the following error: 10.4.1.141 | FAILED => SSH Error: Permission denied (publickey,password). while connecting to 10.4.1.141:22 It is sometimes useful to rerun the command using -vvvv , which prints SSH debug output to help diagnose the issue. Then I tried creating the config file in .ssh/ folder on the host machine, but the error is still the same. The content of the config file is: IdentityFile ~/.ssh/id_rsa which is the path to my private key. Then I ran the same command ansible all -m ping and got the same error again. When I tried another command, ansible all -m ping -u user --ask-pass Then it asked for the SSH password. I gave it (I am very sure the password is correct), but I got this error: 10.4.1.141 | FAILED => FAILED: Authentication failed. This is the log using -vvvv : <10.4.1.141> ESTABLISH CONNECTION FOR USER: rajatg <10.4.1.141> REMOTE_MODULE ping <10.4.1.141> EXEC ssh -C -tt -vvv -o ControlMaster=auto -o ControlPersist=60s -o ControlPath="/Users/rajatg/.ansible/cp/ansible-ssh-%h-%p-%r" -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 10.4.1.141 /bin/sh -c 'mkdir -p $HOME/.ansible/tmp/ansible-tmp-1445512455.7-116096114788007 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1445512455.7-116096114788007 && echo $HOME/.ansible/tmp/ansible-tmp-1445512455.7-116096114788007' 10.4.1.141 | FAILED => SSH Error: Permission denied (publickey,password). while connecting to 10.4.1.141:22 It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue. I am still not able to figure it out what the problem is. It is my last choice to ask it here after doing my all research. This is the link I referred to .
|
ssh, ansible
| 58
| 216,655
| 13
|
https://stackoverflow.com/questions/33280244/ssh-error-permission-denied-publickey-password-in-ansible
|
34,333,058
|
Ansible change ssh port in playbook
|
Here is the inventory file --- [de-servers] 192.26.32.32 [uk-servers] 172.21.1.23 172.32.2.11 and my playbook is look like this: - name: Install de-servers configurations hosts: de-servers roles: - de-server-setup - name: Install uk-servers configurations hosts: uk-servers roles: - uk-server-setup - name: Do some other job on de-servers (cannot be done until uk-servers is installed) hosts: de-servers roles: - de-servers-rest-of-jobs In role de-servers-setup role the ssh port is changed from 22 to 8888, so when the last task is called it fails because it cannot connect to host through 22 port. How to overcome this ssh port change?
|
Ansible change ssh port in playbook Here is the inventory file --- [de-servers] 192.26.32.32 [uk-servers] 172.21.1.23 172.32.2.11 and my playbook is look like this: - name: Install de-servers configurations hosts: de-servers roles: - de-server-setup - name: Install uk-servers configurations hosts: uk-servers roles: - uk-server-setup - name: Do some other job on de-servers (cannot be done until uk-servers is installed) hosts: de-servers roles: - de-servers-rest-of-jobs In role de-servers-setup role the ssh port is changed from 22 to 8888, so when the last task is called it fails because it cannot connect to host through 22 port. How to overcome this ssh port change?
|
ansible
| 57
| 153,640
| 8
|
https://stackoverflow.com/questions/34333058/ansible-change-ssh-port-in-playbook
|
23,946,112
|
How to prevent 'changed' flag when 'register'-ing a variable?
|
I have a register task to test for the installation of a package: tasks: - name: test for nginx command: dpkg -s nginx-common register: nginx_installed Every run it gets reported as a "change": TASK: [test for nginx] ******************************************************** changed: [vm1] I don't regard this as a change... it was installed last run and is still installed this run. Yeah, not a biggy, just one of those untidy OCD type issues. So am I doing it wrong? Is there some way to use register without it always being regarded as a change? The [verbose] output is untidy, but the only way I've found to get the correct return code. TASK: [test for nginx] ******************************************************** changed: [vm1] => {"changed": true, "cmd": ["dpkg", "-s", "nginx-common"], "delta": "0:00:00.010231", "end": "2014-05-30 12:16:40.604405", "rc": 0, "start": "2014-05-30 12:16:40.594174", "stderr": "", "stdout": "Package: nginx-common\nStatus: install ok ... \nHomepage: [URL]
|
How to prevent 'changed' flag when 'register'-ing a variable? I have a register task to test for the installation of a package: tasks: - name: test for nginx command: dpkg -s nginx-common register: nginx_installed Every run it gets reported as a "change": TASK: [test for nginx] ******************************************************** changed: [vm1] I don't regard this as a change... it was installed last run and is still installed this run. Yeah, not a biggy, just one of those untidy OCD type issues. So am I doing it wrong? Is there some way to use register without it always being regarded as a change? The [verbose] output is untidy, but the only way I've found to get the correct return code. TASK: [test for nginx] ******************************************************** changed: [vm1] => {"changed": true, "cmd": ["dpkg", "-s", "nginx-common"], "delta": "0:00:00.010231", "end": "2014-05-30 12:16:40.604405", "rc": 0, "start": "2014-05-30 12:16:40.594174", "stderr": "", "stdout": "Package: nginx-common\nStatus: install ok ... \nHomepage: [URL]
|
ansible
| 57
| 49,660
| 2
|
https://stackoverflow.com/questions/23946112/how-to-prevent-changed-flag-when-register-ing-a-variable
|
32,994,002
|
Is there a yaml editing module for ansible?
|
I need to modify a yaml file ( schleuder configuration ) and I'd like to do this from an ansible playbook - is there a module to do so? Hard to google for this, everything that turns up is how to write playbooks.
|
Is there a yaml editing module for ansible? I need to modify a yaml file ( schleuder configuration ) and I'd like to do this from an ansible playbook - is there a module to do so? Hard to google for this, everything that turns up is how to write playbooks.
|
ansible
| 57
| 48,452
| 7
|
https://stackoverflow.com/questions/32994002/is-there-a-yaml-editing-module-for-ansible
|
37,841,914
|
How do I pass username and password while using Ansible Git module?
|
While doing clone, push or pull of a private git repository hosted internally (e.g. on a GitLab instance) with Ansible's Git module, how do I specify username and password to authenticate with the Git server? I don't see any way to do this in the documentation .
|
How do I pass username and password while using Ansible Git module? While doing clone, push or pull of a private git repository hosted internally (e.g. on a GitLab instance) with Ansible's Git module, how do I specify username and password to authenticate with the Git server? I don't see any way to do this in the documentation .
|
ansible, ansible-2.x
| 56
| 82,592
| 6
|
https://stackoverflow.com/questions/37841914/how-do-i-pass-username-and-password-while-using-ansible-git-module
|
39,640,654
|
Using True False with Ansible When Clause
|
I'm running into the silliest issue. I cannot figure out how to test for boolean in an Ansible 2.2 task file. In vars/main.yml , I have: destroy: false In the playbook, I have: roles: - {'role': 'vmdeploy','destroy': true} In the task file, I have the following: - include: "create.yml" when: "{{ destroy|bool }} == 'false'" I've tried various combinations below: when: "{{ destroy|bool }} == false" when: "{{ destroy|bool }} == 'false'" when: "{{ destroy|bool == false}}" when: "{{ destroy == false}}" when: "{{ destroy == 'false'}}" when: destroy|bool == false when: destroy|bool == 'false' when: not destroy|bool In all the above cases, I still get: statically included: .../vmdeploy/tasks/create.yml Debug output: - debug: msg: "{{ destroy }}" --- ok: [atlcicd009] => { "msg": true } The desired result, is that it would skip the include.
|
Using True False with Ansible When Clause I'm running into the silliest issue. I cannot figure out how to test for boolean in an Ansible 2.2 task file. In vars/main.yml , I have: destroy: false In the playbook, I have: roles: - {'role': 'vmdeploy','destroy': true} In the task file, I have the following: - include: "create.yml" when: "{{ destroy|bool }} == 'false'" I've tried various combinations below: when: "{{ destroy|bool }} == false" when: "{{ destroy|bool }} == 'false'" when: "{{ destroy|bool == false}}" when: "{{ destroy == false}}" when: "{{ destroy == 'false'}}" when: destroy|bool == false when: destroy|bool == 'false' when: not destroy|bool In all the above cases, I still get: statically included: .../vmdeploy/tasks/create.yml Debug output: - debug: msg: "{{ destroy }}" --- ok: [atlcicd009] => { "msg": true } The desired result, is that it would skip the include.
|
boolean, ansible, ansible-2.x
| 56
| 211,188
| 5
|
https://stackoverflow.com/questions/39640654/using-true-false-with-ansible-when-clause
|
39,533,532
|
Ansible Timeout (12s) waiting for privilege escalation prompt
|
I'm having trouble running my Ansible playbook on AWS instance. Here is my version: $ ansible --version ansible 2.0.0.2 I created an inventory file as: [my_ec2_instance] default ansible_host=MY_EC2_ADDRESS ansible_user='ubuntu' ansible_ssh_private_key_file='/home/MY_USER/MY_KEYS/MY_KEY.pem' Testing connection to my server: $ ansible -i provisioner/inventory my_ec2_instance -m ping default | SUCCESS => { "changed": false, "ping": "pong" } Now when running my playbook on this inventory I get the error Timeout (12s) waiting for privilege escalation prompt as follows: $ ansible-playbook -i provisioner/inventory -l my_ec2_instance provisioner/playbook.yml PLAY [Ubuntu14/Python3/Postgres/Nginx/Gunicorn/Django stack] ***** TASK [setup] ******************************************************************* fatal: [default]: FAILED! => {"failed": true, "msg": "ERROR! Timeout (12s) waiting for privilege escalation prompt: "} NO MORE HOSTS LEFT ************************************************************* PLAY RECAP ********************************************************************* default : ok=0 changed=0 unreachable=0 failed=1 If I run the same playbook using the .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as the inventory parameter it works perfectly on my Vagrant instance.(I believe, proving there is nothing wrong in the playbook/roles itself) Also, if I run it with an -vvvv , copy the exec ssh line and run it manually it indeed connects to AWS without problems. Do I need to add any other parameter on my inventory file to connect an EC2 instance? What am I missing?
|
Ansible Timeout (12s) waiting for privilege escalation prompt I'm having trouble running my Ansible playbook on AWS instance. Here is my version: $ ansible --version ansible 2.0.0.2 I created an inventory file as: [my_ec2_instance] default ansible_host=MY_EC2_ADDRESS ansible_user='ubuntu' ansible_ssh_private_key_file='/home/MY_USER/MY_KEYS/MY_KEY.pem' Testing connection to my server: $ ansible -i provisioner/inventory my_ec2_instance -m ping default | SUCCESS => { "changed": false, "ping": "pong" } Now when running my playbook on this inventory I get the error Timeout (12s) waiting for privilege escalation prompt as follows: $ ansible-playbook -i provisioner/inventory -l my_ec2_instance provisioner/playbook.yml PLAY [Ubuntu14/Python3/Postgres/Nginx/Gunicorn/Django stack] ***** TASK [setup] ******************************************************************* fatal: [default]: FAILED! => {"failed": true, "msg": "ERROR! Timeout (12s) waiting for privilege escalation prompt: "} NO MORE HOSTS LEFT ************************************************************* PLAY RECAP ********************************************************************* default : ok=0 changed=0 unreachable=0 failed=1 If I run the same playbook using the .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as the inventory parameter it works perfectly on my Vagrant instance.(I believe, proving there is nothing wrong in the playbook/roles itself) Also, if I run it with an -vvvv , copy the exec ssh line and run it manually it indeed connects to AWS without problems. Do I need to add any other parameter on my inventory file to connect an EC2 instance? What am I missing?
|
amazon-ec2, ansible, ansible-2.x
| 55
| 156,327
| 17
|
https://stackoverflow.com/questions/39533532/ansible-timeout-12s-waiting-for-privilege-escalation-prompt
|
36,668,756
|
Ansible remote_user vs ansible_user
|
The question is simple: what is the difference between ansible_user (former ansible_ssh_user ) and remote_user in Ansible, besides that the first one is set if configuration file and the latter one is set in plays / roles? How do they relate to -u / --user command line options?
|
Ansible remote_user vs ansible_user The question is simple: what is the difference between ansible_user (former ansible_ssh_user ) and remote_user in Ansible, besides that the first one is set if configuration file and the latter one is set in plays / roles? How do they relate to -u / --user command line options?
|
ansible, ansible-2.x
| 55
| 105,022
| 2
|
https://stackoverflow.com/questions/36668756/ansible-remote-user-vs-ansible-user
|
42,673,045
|
[WARNING]: when statements should not include jinja2 templating delimiters
|
I was wondering what is the correct syntax for when statements? I have this playbook: - set_fact: sh_vlan_id: "{{ output.response|map(attribute='vlan_id')|list|join(',') }}" - name: create vlans ios_config: provider: "{{ provider }}" parents: vlan {{ item.id }} lines: name {{ item.name }} with_items: "{{ vlans }}" register: result when: '"{{ item.id }}" not in sh_vlan_id' And, running it, gives me a warning but it still runs through. I am not sure if this is correct or not. TASK [set_fact] ************************************************ ok: [acc_sw_01] TASK [create vlans] *********************************************** [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: "{{ item.id }}" not in sh_vlan_id skipping: [acc_sw_01] => (item={u'id': 10, u'name': u'voice-1'}) skipping: [acc_sw_01] => (item={u'id': 101, u'name': u'data-2'}) skipping: [acc_sw_01] => (item={u'id': 100, u'name': u'data-1'}) changed: [acc_sw_01] => (item={u'id': 11, u'name': u'voice-2'}) If I remove the curly braces around item.id in the when statement: when: item.id not in sh_vlan_id It gives me an error: TASK [set_fact] *************************************************** ok: [acc_sw_01] TASK [create vlans] *********************************************** fatal: [acc_sw_01]: FAILED! => {"failed": true, "msg": "The conditional check 'item.id not in sh_vlan_id' failed. The error was: Unexpected templating type error occurred on ({% if item.id not in sh_vlan_id %} True {% else %} False {% endif %}): coercing to Unicode: need string or buffer, int found\n\nThe error appears to have been in '/ansible/cisco-ansible/config_tasks/vlan.yml': line 16, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: create vlans\n ^ here\n"} I'm using ansible 2.3.0 (devel cbedc4a12a).
|
[WARNING]: when statements should not include jinja2 templating delimiters I was wondering what is the correct syntax for when statements? I have this playbook: - set_fact: sh_vlan_id: "{{ output.response|map(attribute='vlan_id')|list|join(',') }}" - name: create vlans ios_config: provider: "{{ provider }}" parents: vlan {{ item.id }} lines: name {{ item.name }} with_items: "{{ vlans }}" register: result when: '"{{ item.id }}" not in sh_vlan_id' And, running it, gives me a warning but it still runs through. I am not sure if this is correct or not. TASK [set_fact] ************************************************ ok: [acc_sw_01] TASK [create vlans] *********************************************** [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: "{{ item.id }}" not in sh_vlan_id skipping: [acc_sw_01] => (item={u'id': 10, u'name': u'voice-1'}) skipping: [acc_sw_01] => (item={u'id': 101, u'name': u'data-2'}) skipping: [acc_sw_01] => (item={u'id': 100, u'name': u'data-1'}) changed: [acc_sw_01] => (item={u'id': 11, u'name': u'voice-2'}) If I remove the curly braces around item.id in the when statement: when: item.id not in sh_vlan_id It gives me an error: TASK [set_fact] *************************************************** ok: [acc_sw_01] TASK [create vlans] *********************************************** fatal: [acc_sw_01]: FAILED! => {"failed": true, "msg": "The conditional check 'item.id not in sh_vlan_id' failed. The error was: Unexpected templating type error occurred on ({% if item.id not in sh_vlan_id %} True {% else %} False {% endif %}): coercing to Unicode: need string or buffer, int found\n\nThe error appears to have been in '/ansible/cisco-ansible/config_tasks/vlan.yml': line 16, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: create vlans\n ^ here\n"} I'm using ansible 2.3.0 (devel cbedc4a12a).
|
ansible
| 54
| 91,241
| 3
|
https://stackoverflow.com/questions/42673045/warning-when-statements-should-not-include-jinja2-templating-delimiters
|
25,674,649
|
Ansible: In a playbook, filter a role by tag(s) without passing at the command-line
|
In Ansible 1.7, I can use --tags from the command-line to only run a subset of that playbooks tasks. But I'm wanting to bake into my playbook to run a set of roles with only tasks that match tags. That is, I don't want to have to pass this in via the command-line since it will be the same every time. At first I thought it was this command, but this does the opposite: tagging tasks with these tags instead of filtering them out based on this. roles: - { role: webserver, port: 5000, tags: [ 'web', 'foo' ] } I can imagine implementing this using conditionals but tags would be a much more elegant way of achieving this.
|
Ansible: In a playbook, filter a role by tag(s) without passing at the command-line In Ansible 1.7, I can use --tags from the command-line to only run a subset of that playbooks tasks. But I'm wanting to bake into my playbook to run a set of roles with only tasks that match tags. That is, I don't want to have to pass this in via the command-line since it will be the same every time. At first I thought it was this command, but this does the opposite: tagging tasks with these tags instead of filtering them out based on this. roles: - { role: webserver, port: 5000, tags: [ 'web', 'foo' ] } I can imagine implementing this using conditionals but tags would be a much more elegant way of achieving this.
|
ansible
| 54
| 18,110
| 2
|
https://stackoverflow.com/questions/25674649/ansible-in-a-playbook-filter-a-role-by-tags-without-passing-at-the-command-l
|
32,016,123
|
How to remove the line breaker character '\n' from the result of lookup() module in Ansible?
|
I am using [file lookup] which reads the whole file and stores the content in a variable. My play looks something like this: - name: Store foo.xml contents in a variable set_fact: foo_content: "{{ lookup('file', 'foo.xml' ) | replace('\n', '')}}" So the above code reads the foo.xml file and stores it in the variable, but the problem is when the foo.xml has line breaks in it, it also includes the line break in the variable. My foo.xml is this file: <?xml version="1.0" encoding="utf-8"?> <initialize_param> <secrets> <my_secret id="99">3VMjII6Hw+pd1zHV5THSI712y421USUS8124487128745812sajfhsakjfasbfvcasvnjasjkvbhasdfasgfsfaj5G8A9+n8CkLxk7Dqu0G8Jclg0eb1A5xeFzR3rrJHrb2GBBa7PJNVx8tFJP3AtF6ek/F/WvlBIs2leX2fq+/bGryKlySuFmbcwBsThmPJC5Z5AwPJgGZx</my_secret> </secrets> </initialize_param> The output removes line break \n but also incudes the tabs \r & \t I need to got rid of the \n , need to get rid of extra formatting too (\r & \t), Moreover after the replace filter I get the error while firing a DB Update query as stderr: /bin/sh: 1: cannot open ?xml: No such file
|
How to remove the line breaker character '\n' from the result of lookup() module in Ansible? I am using [file lookup] which reads the whole file and stores the content in a variable. My play looks something like this: - name: Store foo.xml contents in a variable set_fact: foo_content: "{{ lookup('file', 'foo.xml' ) | replace('\n', '')}}" So the above code reads the foo.xml file and stores it in the variable, but the problem is when the foo.xml has line breaks in it, it also includes the line break in the variable. My foo.xml is this file: <?xml version="1.0" encoding="utf-8"?> <initialize_param> <secrets> <my_secret id="99">3VMjII6Hw+pd1zHV5THSI712y421USUS8124487128745812sajfhsakjfasbfvcasvnjasjkvbhasdfasgfsfaj5G8A9+n8CkLxk7Dqu0G8Jclg0eb1A5xeFzR3rrJHrb2GBBa7PJNVx8tFJP3AtF6ek/F/WvlBIs2leX2fq+/bGryKlySuFmbcwBsThmPJC5Z5AwPJgGZx</my_secret> </secrets> </initialize_param> The output removes line break \n but also incudes the tabs \r & \t I need to got rid of the \n , need to get rid of extra formatting too (\r & \t), Moreover after the replace filter I get the error while firing a DB Update query as stderr: /bin/sh: 1: cannot open ?xml: No such file
|
string, replace, ansible
| 53
| 131,034
| 3
|
https://stackoverflow.com/questions/32016123/how-to-remove-the-line-breaker-character-n-from-the-result-of-lookup-module
|
32,878,795
|
Run Command Inside of Docker Container Using Ansible
|
what I'm trying to accomplish is to run commands inside of a Docker container that has already been created on a Digital Ocean Ubuntu/Docker Droplet using Ansible. Can't seem to find anything on this, or I'm majorly missing something. This is my Ansible task in my play book. I'm very new to Ansible so any advice or wisdom would be greatly appreciated. - name: Test Deploy hosts: [my-cluster-of-servers] tasks: - name: Go Into Docker Container And Run Multiple Commands docker: name: [container-name] image: [image-ive-created-container-with-on-server] state: present command: docker exec -it [container-name] bash
|
Run Command Inside of Docker Container Using Ansible what I'm trying to accomplish is to run commands inside of a Docker container that has already been created on a Digital Ocean Ubuntu/Docker Droplet using Ansible. Can't seem to find anything on this, or I'm majorly missing something. This is my Ansible task in my play book. I'm very new to Ansible so any advice or wisdom would be greatly appreciated. - name: Test Deploy hosts: [my-cluster-of-servers] tasks: - name: Go Into Docker Container And Run Multiple Commands docker: name: [container-name] image: [image-ive-created-container-with-on-server] state: present command: docker exec -it [container-name] bash
|
docker, ansible
| 53
| 73,093
| 8
|
https://stackoverflow.com/questions/32878795/run-command-inside-of-docker-container-using-ansible
|
50,277,495
|
How to run an ansible-playbook with a passphrase-protected-ssh-private-key?
|
I have created an autoscaling group for Amazon EC2 and I have added my public key when I created the AMI with packer , I can run ansible-playbook and ssh to the hosts. But there is a problem when I run the playbook like this ansible-playbook load.yml I am getting this message that I need to write my password Enter passphrase for key '/Users/XXX/.ssh/id_rsa': Enter passphrase for key '/Users/XXX/.ssh/id_rsa': Enter passphrase for key '/Users/XXX/.ssh/id_rsa': The problem is it doesn't accept my password (I am sure I am typing my password correctly). I found that I can send my password with ask-pass flag, so I have changed my command to ansible-playbook load.yml --ask-pass and I got some progress but again for some other task it asks for the password again and it didn't accept my password [WARNING]: Unable to parse /etc/ansible/hosts as an inventory source [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] ************************************************************************************************************* TASK [ec2_instance_facts] **************************************************************************************************** ok: [localhost] TASK [add_host] ************************************************************************************************************** changed: [localhost] => (item=xx.xxx.xx.xxx) changed: [localhost] => (item=yy.yyy.yyy.yyy) PLAY [instances] ************************************************************************************************************* TASK [Copy gatling.conf] ***************************************************************************************************** ok: [xx.xxx.xx.xxx] ok: [yy.yyy.yyy.yyy] Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': If I don't use ask-pass flag even the task [Copy gatling.conf] doesn't complete and complaining about could not access the hosts. By adding the flag this part passes, but my next task again asks for pass. How should I solve this issue? What am I doing wrong here?
|
How to run an ansible-playbook with a passphrase-protected-ssh-private-key? I have created an autoscaling group for Amazon EC2 and I have added my public key when I created the AMI with packer , I can run ansible-playbook and ssh to the hosts. But there is a problem when I run the playbook like this ansible-playbook load.yml I am getting this message that I need to write my password Enter passphrase for key '/Users/XXX/.ssh/id_rsa': Enter passphrase for key '/Users/XXX/.ssh/id_rsa': Enter passphrase for key '/Users/XXX/.ssh/id_rsa': The problem is it doesn't accept my password (I am sure I am typing my password correctly). I found that I can send my password with ask-pass flag, so I have changed my command to ansible-playbook load.yml --ask-pass and I got some progress but again for some other task it asks for the password again and it didn't accept my password [WARNING]: Unable to parse /etc/ansible/hosts as an inventory source [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] ************************************************************************************************************* TASK [ec2_instance_facts] **************************************************************************************************** ok: [localhost] TASK [add_host] ************************************************************************************************************** changed: [localhost] => (item=xx.xxx.xx.xxx) changed: [localhost] => (item=yy.yyy.yyy.yyy) PLAY [instances] ************************************************************************************************************* TASK [Copy gatling.conf] ***************************************************************************************************** ok: [xx.xxx.xx.xxx] ok: [yy.yyy.yyy.yyy] Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': Enter passphrase for key '/Users/ccc/.ssh/id_rsa': If I don't use ask-pass flag even the task [Copy gatling.conf] doesn't complete and complaining about could not access the hosts. By adding the flag this part passes, but my next task again asks for pass. How should I solve this issue? What am I doing wrong here?
|
ssh, ansible
| 53
| 89,638
| 6
|
https://stackoverflow.com/questions/50277495/how-to-run-an-ansible-playbook-with-a-passphrase-protected-ssh-private-key
|
32,786,122
|
Ansible condition when string not matching
|
I am trying to write an Ansible playbook that only compiles Nginx if it's not already present and at the current version. However it compiles every time which is undesirable. This is what I have: - shell: /usr/local/nginx/sbin/nginx -v 2>&1 register: nginxVersion - debug: var=nginxVersion - name: install nginx shell: /var/local/ansible/nginx/makenginx.sh when: "not nginxVersion == 'nginx version: nginx/1.8.0'" become: yes The script all works apart from the fact that it runs the shell script every time to compile Nginx. The debug output for nginxVersion is: ok: [server] => { "var": { "nginxVersion": { "changed": true, "cmd": "/usr/local/nginx/sbin/nginx -v 2>&1", "delta": "0:00:00.003752", "end": "2015-09-25 16:45:26.500409", "invocation": { "module_args": "/usr/local/nginx/sbin/nginx -v 2>&1", "module_name": "shell" }, "rc": 0, "start": "2015-09-25 16:45:26.496657", "stderr": "", "stdout": "nginx version: nginx/1.8.0", "stdout_lines": [ "nginx version: nginx/1.8.0" ], "warnings": [] } } } According to the documentation I am on the right lines, what simple trick am I missing?
|
Ansible condition when string not matching I am trying to write an Ansible playbook that only compiles Nginx if it's not already present and at the current version. However it compiles every time which is undesirable. This is what I have: - shell: /usr/local/nginx/sbin/nginx -v 2>&1 register: nginxVersion - debug: var=nginxVersion - name: install nginx shell: /var/local/ansible/nginx/makenginx.sh when: "not nginxVersion == 'nginx version: nginx/1.8.0'" become: yes The script all works apart from the fact that it runs the shell script every time to compile Nginx. The debug output for nginxVersion is: ok: [server] => { "var": { "nginxVersion": { "changed": true, "cmd": "/usr/local/nginx/sbin/nginx -v 2>&1", "delta": "0:00:00.003752", "end": "2015-09-25 16:45:26.500409", "invocation": { "module_args": "/usr/local/nginx/sbin/nginx -v 2>&1", "module_name": "shell" }, "rc": 0, "start": "2015-09-25 16:45:26.496657", "stderr": "", "stdout": "nginx version: nginx/1.8.0", "stdout_lines": [ "nginx version: nginx/1.8.0" ], "warnings": [] } } } According to the documentation I am on the right lines, what simple trick am I missing?
|
ansible
| 53
| 207,197
| 2
|
https://stackoverflow.com/questions/32786122/ansible-condition-when-string-not-matching
|
16,385,507
|
ansible - delete unmanaged files from directory?
|
I want to recursively copy over a directory and render all .j2 files in there as templates. For this I am currently using the following lines: - template: > src=/src/conf.d/{{ item }} dest=/dest/conf.d/{{ item|replace('.j2','') }} with_lines: find /src/conf.d/ -type f -printf "%P\n" Now I'm looking for a way to remove unmanaged files from this directory. For example if I remove a file/template from /src/conf.d/ I want Ansible to remove it from /dest/conf.d/ as well. Is there some way to do this? I tried fiddling around with rsync --delete , but there I got a problem with the templates which get their suffix .j2 removed.
|
ansible - delete unmanaged files from directory? I want to recursively copy over a directory and render all .j2 files in there as templates. For this I am currently using the following lines: - template: > src=/src/conf.d/{{ item }} dest=/dest/conf.d/{{ item|replace('.j2','') }} with_lines: find /src/conf.d/ -type f -printf "%P\n" Now I'm looking for a way to remove unmanaged files from this directory. For example if I remove a file/template from /src/conf.d/ I want Ansible to remove it from /dest/conf.d/ as well. Is there some way to do this? I tried fiddling around with rsync --delete , but there I got a problem with the templates which get their suffix .j2 removed.
|
ansible, ansible-template
| 53
| 44,401
| 10
|
https://stackoverflow.com/questions/16385507/ansible-delete-unmanaged-files-from-directory
|
32,830,428
|
Where should I be organizing host-specific files/templates?
|
I'm trying to organize my playbooks according to the Directory Layout structure. The documentation doesn't seem to have a recommendation for host-specific files/templates. I have 2 plays for a single site example.com-provision.yml example.com-deploy.yml These files are located in the root of my structure. The provisioning playbook simply includes other roles --- - hosts: example.com roles: - common - application - database become: true become_method: su become_user: root The deployment playbook doesn't include roles, but has it's own vars and tasks sections. I have a couple template and copy tasks, and am wondering what the 'best practice' is for where to put these host-specific templates/files within this directory structure. Right now I have them at ./roles/example.com/templates/ and ./roles/example.com/files/ , but need to reference the files with their full path from my deployment playbook, like - name: deployment | copy httpd config template: src: ./roles/example.com/templates/{{ host }}.conf.j2 # ... instead of - name: deployment | copy httpd config template: src: {{ host }}.conf.j2 # ...
|
Where should I be organizing host-specific files/templates? I'm trying to organize my playbooks according to the Directory Layout structure. The documentation doesn't seem to have a recommendation for host-specific files/templates. I have 2 plays for a single site example.com-provision.yml example.com-deploy.yml These files are located in the root of my structure. The provisioning playbook simply includes other roles --- - hosts: example.com roles: - common - application - database become: true become_method: su become_user: root The deployment playbook doesn't include roles, but has it's own vars and tasks sections. I have a couple template and copy tasks, and am wondering what the 'best practice' is for where to put these host-specific templates/files within this directory structure. Right now I have them at ./roles/example.com/templates/ and ./roles/example.com/files/ , but need to reference the files with their full path from my deployment playbook, like - name: deployment | copy httpd config template: src: ./roles/example.com/templates/{{ host }}.conf.j2 # ... instead of - name: deployment | copy httpd config template: src: {{ host }}.conf.j2 # ...
|
ansible
| 53
| 22,701
| 1
|
https://stackoverflow.com/questions/32830428/where-should-i-be-organizing-host-specific-files-templates
|
35,083,756
|
Ansible: Set variable only if undefined
|
I would like to set an ansible variable to some default value but only if the variable is undefined. Otherwise I would like to keep it unchanged. I tried these two approaches and both of them produce recursive loop: namespace: "{{namespace|default(default_namespace)}}" namespace: "{% if namespace is defined %}{{namespace}}{% else %}{{default_namespace}}{% endif %}"
|
Ansible: Set variable only if undefined I would like to set an ansible variable to some default value but only if the variable is undefined. Otherwise I would like to keep it unchanged. I tried these two approaches and both of them produce recursive loop: namespace: "{{namespace|default(default_namespace)}}" namespace: "{% if namespace is defined %}{{namespace}}{% else %}{{default_namespace}}{% endif %}"
|
ansible
| 52
| 128,987
| 5
|
https://stackoverflow.com/questions/35083756/ansible-set-variable-only-if-undefined
|
41,908,715
|
Ansible with_subelements
|
I am having a hard time understanding the logic of ansible with_subelements syntax, what exactly does with_subelements do? i took a look at ansible documentation on with_subelements here [URL] and was not very helpful. I also saw a playbook with with_subelements example on a blog --- - hosts: cent vars: users: - name: jagadish comments: - 'Jagadish is Good' - name: srini comments: - 'Srini is Bad' tasks: - name: User Creation shell: useradd -c "{{ item.1 }}" "{{ item.0.name }}" with_subelements: - users - comments what do item.1 and item.0 refer to?
|
Ansible with_subelements I am having a hard time understanding the logic of ansible with_subelements syntax, what exactly does with_subelements do? i took a look at ansible documentation on with_subelements here [URL] and was not very helpful. I also saw a playbook with with_subelements example on a blog --- - hosts: cent vars: users: - name: jagadish comments: - 'Jagadish is Good' - name: srini comments: - 'Srini is Bad' tasks: - name: User Creation shell: useradd -c "{{ item.1 }}" "{{ item.0.name }}" with_subelements: - users - comments what do item.1 and item.0 refer to?
|
ansible
| 52
| 60,692
| 1
|
https://stackoverflow.com/questions/41908715/ansible-with-subelements
|
41,791,055
|
Conditional substring in a Jinja2 template
|
When deploying with ansible, There's 1 specific case where I need to strip a string of a trailing -p substring. The string somemachine-prod-p should become somemachine-prod only if the -p is at the end. The substring function I saw I can use with Jinja does not fulfill my needs as I need to strip the end of the string, not the start. Ideas?
|
Conditional substring in a Jinja2 template When deploying with ansible, There's 1 specific case where I need to strip a string of a trailing -p substring. The string somemachine-prod-p should become somemachine-prod only if the -p is at the end. The substring function I saw I can use with Jinja does not fulfill my needs as I need to strip the end of the string, not the start. Ideas?
|
substring, ansible, jinja2
| 51
| 115,446
| 4
|
https://stackoverflow.com/questions/41791055/conditional-substring-in-a-jinja2-template
|
40,059,745
|
NGINX: connect() to unix:/var/run/php7.0-fpm.sock failed (2: No such file or directory)
|
I'm trying to follow this Ansible tutorial while adjusting it for Ubuntu 16.04 with php7. Below this message you'll find my Ansible file. After running it and trying to visit the page in the browser I get a 404, and the following in the nginx error logs: 2016/10/15 13:13:20 [crit] 28771#28771: *7 connect() to unix:/var/run/php7.0-fpm.sock failed (2: No such file or directory) while connecting to upstream, client: 93.xxx.xxx.xx, server: 95.xx.xx.xx, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php7.0-fpm.sock:", host: "95.xx.xx.xx" So I checked if the socket file exists, and it seems to exist, but ls behaves weird: $ sudo ls -l /var/run/php total 4 -rw-r--r-- 1 root root 5 Oct 15 13:00 php7.0-fpm.pid srw-rw---- 1 www-data www-data 0 Oct 15 13:00 php7.0-fpm.sock $ sudo ls -l /var/run/php7 ls: cannot access '/var/run/php7': No such file or directory $ sudo ls -l /var/run/php7.0-fpm.sock ls: cannot access '/var/run/php7.0-fpm.sock': No such file or directory Why can ls find the socket file if I search it by part of the name php while it cannot find the socket file when I list more than that php7 or even the full name php7.0-fpm.sock ? And most importantly, how can I make this work with nginx? All tips are welcome! below I pasted my Ansible file --- - hosts: php become: true tasks: - name: install packages apt: name={{ item }} update_cache=yes state=latest with_items: - git - mcrypt - nginx - php-cli - php-curl - php-fpm - php-intl - php-json - php-mcrypt - php-mbstring - php-sqlite3 - php-xml - sqlite3 - name: enable mbstring shell: phpenmod mbstring notify: - restart php7.0-fpm - restart nginx - name: create /var/www/ directory file: dest=/var/www/ state=directory owner=www-data group=www-data mode=0700 - name: Clone git repository git: > dest=/var/www/laravel repo=[URL] update=no become: true become_user: www-data register: cloned - name: install composer shell: curl -sS [URL] | php -- --install-dir=/usr/local/bin --filename=composer args: creates: /usr/local/bin/composer - name: composer create-project composer: command=create-project working_dir=/var/www/laravel optimize_autoloader=no become: true become_user: www-data when: cloned|changed - name: set APP_DEBUG=false lineinfile: dest=/var/www/laravel/.env regexp='^APP_DEBUG=' line=APP_DEBUG=false - name: set APP_ENV=production lineinfile: dest=/var/www/laravel/.env regexp='^APP_ENV=' line=APP_ENV=production - name: Configure nginx template: src=nginx.conf dest=/etc/nginx/sites-available/default notify: - restart php5-fpm - restart nginx handlers: - name: restart php7.0-fpm service: name=php7.0-fpm state=restarted - name: restart nginx service: name=nginx state=restarted - name: reload nginx service: name=nginx state=reloaded
|
NGINX: connect() to unix:/var/run/php7.0-fpm.sock failed (2: No such file or directory) I'm trying to follow this Ansible tutorial while adjusting it for Ubuntu 16.04 with php7. Below this message you'll find my Ansible file. After running it and trying to visit the page in the browser I get a 404, and the following in the nginx error logs: 2016/10/15 13:13:20 [crit] 28771#28771: *7 connect() to unix:/var/run/php7.0-fpm.sock failed (2: No such file or directory) while connecting to upstream, client: 93.xxx.xxx.xx, server: 95.xx.xx.xx, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php7.0-fpm.sock:", host: "95.xx.xx.xx" So I checked if the socket file exists, and it seems to exist, but ls behaves weird: $ sudo ls -l /var/run/php total 4 -rw-r--r-- 1 root root 5 Oct 15 13:00 php7.0-fpm.pid srw-rw---- 1 www-data www-data 0 Oct 15 13:00 php7.0-fpm.sock $ sudo ls -l /var/run/php7 ls: cannot access '/var/run/php7': No such file or directory $ sudo ls -l /var/run/php7.0-fpm.sock ls: cannot access '/var/run/php7.0-fpm.sock': No such file or directory Why can ls find the socket file if I search it by part of the name php while it cannot find the socket file when I list more than that php7 or even the full name php7.0-fpm.sock ? And most importantly, how can I make this work with nginx? All tips are welcome! below I pasted my Ansible file --- - hosts: php become: true tasks: - name: install packages apt: name={{ item }} update_cache=yes state=latest with_items: - git - mcrypt - nginx - php-cli - php-curl - php-fpm - php-intl - php-json - php-mcrypt - php-mbstring - php-sqlite3 - php-xml - sqlite3 - name: enable mbstring shell: phpenmod mbstring notify: - restart php7.0-fpm - restart nginx - name: create /var/www/ directory file: dest=/var/www/ state=directory owner=www-data group=www-data mode=0700 - name: Clone git repository git: > dest=/var/www/laravel repo=[URL] update=no become: true become_user: www-data register: cloned - name: install composer shell: curl -sS [URL] | php -- --install-dir=/usr/local/bin --filename=composer args: creates: /usr/local/bin/composer - name: composer create-project composer: command=create-project working_dir=/var/www/laravel optimize_autoloader=no become: true become_user: www-data when: cloned|changed - name: set APP_DEBUG=false lineinfile: dest=/var/www/laravel/.env regexp='^APP_DEBUG=' line=APP_DEBUG=false - name: set APP_ENV=production lineinfile: dest=/var/www/laravel/.env regexp='^APP_ENV=' line=APP_ENV=production - name: Configure nginx template: src=nginx.conf dest=/etc/nginx/sites-available/default notify: - restart php5-fpm - restart nginx handlers: - name: restart php7.0-fpm service: name=php7.0-fpm state=restarted - name: restart nginx service: name=nginx state=restarted - name: reload nginx service: name=nginx state=reloaded
|
php, linux, sockets, nginx, ansible
| 51
| 159,464
| 6
|
https://stackoverflow.com/questions/40059745/nginx-connect-to-unix-var-run-php7-0-fpm-sock-failed-2-no-such-file-or-dir
|
33,450,240
|
clone a specific branch from git through ansible playbook
|
I am using ansible to deploy my app. I am cloning the app from github using the following: - name: Deploy site files from Github repository sudo: yes git: repo=git@github.com:xyz/abc.git dest=/home/{{deploy_user}}/{{app_name}} key_file=/home/ubuntu/.ssh/id_rsa accept_hostkey=yes force=yes I want to clone a specific branch from the repository. I read the documentation of ansible but couldn't find any option to clone a specific branch. It has an option to clone a version but not branch.
|
clone a specific branch from git through ansible playbook I am using ansible to deploy my app. I am cloning the app from github using the following: - name: Deploy site files from Github repository sudo: yes git: repo=git@github.com:xyz/abc.git dest=/home/{{deploy_user}}/{{app_name}} key_file=/home/ubuntu/.ssh/id_rsa accept_hostkey=yes force=yes I want to clone a specific branch from the repository. I read the documentation of ansible but couldn't find any option to clone a specific branch. It has an option to clone a version but not branch.
|
github, ansible
| 51
| 54,327
| 2
|
https://stackoverflow.com/questions/33450240/clone-a-specific-branch-from-git-through-ansible-playbook
|
30,763,709
|
ansible playbook execute in this order: task, role, task, role, task
|
Forgive my newbie question, but I would like to execute three tasks and use two roles in a playbook, in the order: task role task role task This is what I have so far (task, role, task): --- - name: Task Role Task hosts: 127.0.0.1 connection: local gather_facts: false pre_tasks: - name: Do this task first foo: roles: - role: this role second foo: post_tasks: - name: Do this task third foo: Is this possible or should I be changing my tasks into roles?
|
ansible playbook execute in this order: task, role, task, role, task Forgive my newbie question, but I would like to execute three tasks and use two roles in a playbook, in the order: task role task role task This is what I have so far (task, role, task): --- - name: Task Role Task hosts: 127.0.0.1 connection: local gather_facts: false pre_tasks: - name: Do this task first foo: roles: - role: this role second foo: post_tasks: - name: Do this task third foo: Is this possible or should I be changing my tasks into roles?
|
ansible
| 51
| 42,487
| 3
|
https://stackoverflow.com/questions/30763709/ansible-playbook-execute-in-this-order-task-role-task-role-task
|
33,359,404
|
Ansible: best practice for maintaining list of sudoers
|
In the documentation , there is an example of using the lineinfile module to edit /etc/sudoers . - lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'" Feels a bit hackish. I assumed there would be something in the user module to handle this but there doesn't appear to be any options. What are the best practices for adding and removing users to /etc/sudoers ?
|
Ansible: best practice for maintaining list of sudoers In the documentation , there is an example of using the lineinfile module to edit /etc/sudoers . - lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'" Feels a bit hackish. I assumed there would be something in the user module to handle this but there doesn't appear to be any options. What are the best practices for adding and removing users to /etc/sudoers ?
|
python, unix, ansible, user-management
| 51
| 67,477
| 2
|
https://stackoverflow.com/questions/33359404/ansible-best-practice-for-maintaining-list-of-sudoers
|
37,184,699
|
Ansible SSH ERROR connection in localhost
|
I have this error when I launch my playbook against the localhost host. TASK [setup] ******************************************************************* fatal: [127.0.0.1]: UNREACHABLE! => {"changed": false, "msg": "SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue", "unreachable": true} to retry, use: --limit @deploy-test-env.retry PLAY RECAP ********************************************************************* 127.0.0.1 : ok=0 changed=0 unreachable=1 failed=0 And my hosts file have this config: [local] 127.0.0.1 What is the problem? Thanks!
|
Ansible SSH ERROR connection in localhost I have this error when I launch my playbook against the localhost host. TASK [setup] ******************************************************************* fatal: [127.0.0.1]: UNREACHABLE! => {"changed": false, "msg": "SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue", "unreachable": true} to retry, use: --limit @deploy-test-env.retry PLAY RECAP ********************************************************************* 127.0.0.1 : ok=0 changed=0 unreachable=1 failed=0 And my hosts file have this config: [local] 127.0.0.1 What is the problem? Thanks!
|
ssh, ansible
| 50
| 55,636
| 3
|
https://stackoverflow.com/questions/37184699/ansible-ssh-error-connection-in-localhost
|
22,129,422
|
Running an Ansible Playbook on a particular group of servers
|
I have the following /etc/ansible/hosts: [ESNodes] isk-vsrv643 isk-vsrv644 isk-vsrv645 [PerfSetup] isk-dsrv613 isk-dsrv614 I know there is an option to run a playbook on particular hosts with -l Is there a way to run a playbook only on the PerfSetup group?
|
Running an Ansible Playbook on a particular group of servers I have the following /etc/ansible/hosts: [ESNodes] isk-vsrv643 isk-vsrv644 isk-vsrv645 [PerfSetup] isk-dsrv613 isk-dsrv614 I know there is an option to run a playbook on particular hosts with -l Is there a way to run a playbook only on the PerfSetup group?
|
ansible
| 50
| 86,509
| 1
|
https://stackoverflow.com/questions/22129422/running-an-ansible-playbook-on-a-particular-group-of-servers
|
25,629,933
|
Ansible copy ssh key from one host to another
|
I have 2 app servers with a loadbalancer in front of them and 1 database server in my system. I'm provisioning them using Ansible. App servers has Nginx + Passenger and running for a Rails app. Will use capistrano for deployment but I have an issue about ssh keys. My git repo is in another server and I have to generate ssh public keys on appservers and add them to the Git server(To authorized_keys file). How can I do this in ansible playbook? PS: I may have more than 2 app servers.
|
Ansible copy ssh key from one host to another I have 2 app servers with a loadbalancer in front of them and 1 database server in my system. I'm provisioning them using Ansible. App servers has Nginx + Passenger and running for a Rails app. Will use capistrano for deployment but I have an issue about ssh keys. My git repo is in another server and I have to generate ssh public keys on appservers and add them to the Git server(To authorized_keys file). How can I do this in ansible playbook? PS: I may have more than 2 app servers.
|
ssh, capistrano3, ansible
| 50
| 94,742
| 7
|
https://stackoverflow.com/questions/25629933/ansible-copy-ssh-key-from-one-host-to-another
|
38,847,824
|
How do you get service status with Ansible?
|
I want to get the service status with Ansible, such as redis-server . I know how to use Ansible service module to stop or start system services, but how can I get the current service status?
|
How do you get service status with Ansible? I want to get the service status with Ansible, such as redis-server . I know how to use Ansible service module to stop or start system services, but how can I get the current service status?
|
ansible
| 49
| 245,174
| 13
|
https://stackoverflow.com/questions/38847824/how-do-you-get-service-status-with-ansible
|
37,160,668
|
Check if strings are equals and ternary operator in Ansible
|
In my playbook, I have this: #More things - include: deploy_new.yml vars: service_type: "{{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }}" when: service_up|failed When expose_service is true, I want service_type to be set to NodePort , and ClusterIP otherwise. However, service_type is set to False in all cases. What am I doing wrong?
|
Check if strings are equals and ternary operator in Ansible In my playbook, I have this: #More things - include: deploy_new.yml vars: service_type: "{{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }}" when: service_up|failed When expose_service is true, I want service_type to be set to NodePort , and ClusterIP otherwise. However, service_type is set to False in all cases. What am I doing wrong?
|
ansible, jinja2
| 49
| 65,730
| 3
|
https://stackoverflow.com/questions/37160668/check-if-strings-are-equals-and-ternary-operator-in-ansible
|
42,883,909
|
Passing variables to ansible roles
|
I have my directory structure as this . ├── README.md ├── play.yml └── roles ├── bootstrap_server │ └── tasks │ └── main.yml ├── create_new_user │ └── tasks │ └── main.yml ├── update │ └── tasks │ └── main.yml └── vimserver ├── files │ └── vimrc_server └── tasks └── main.yml When I create a user under the role create_new_user , I was hardcoding the username as --- - name: Creating a user named username on the specified web server. user: name: username state: present shell: /bin/bash groups: admin generate_ssh_key: yes ssh_key_bits: 2048 ssh_key_file: .ssh/id_rsa - name: Copy .ssh/id_rsa from host box to the remote box for user username become: true copy: src: ~/.ssh/id_rsa.pub dest: /home/usernmame/.ssh/authorized_keys mode: 0600 owner: username group: username One way of solving this may be to create a var/main.yml and put the username there. But I wanted something through which I can specify the username at play.yml level. As I am also using the username in the role vimrcserver . I am calling the roles using play.yml --- - hosts: testdroplets roles: - update - bootstrap_server - create_new_user - vimserver Would a template work here in this case? Couldn't find much from those other question: Ansible best practice for passing vars to nested playbooks? Ansible passing variables to roles
|
Passing variables to ansible roles I have my directory structure as this . ├── README.md ├── play.yml └── roles ├── bootstrap_server │ └── tasks │ └── main.yml ├── create_new_user │ └── tasks │ └── main.yml ├── update │ └── tasks │ └── main.yml └── vimserver ├── files │ └── vimrc_server └── tasks └── main.yml When I create a user under the role create_new_user , I was hardcoding the username as --- - name: Creating a user named username on the specified web server. user: name: username state: present shell: /bin/bash groups: admin generate_ssh_key: yes ssh_key_bits: 2048 ssh_key_file: .ssh/id_rsa - name: Copy .ssh/id_rsa from host box to the remote box for user username become: true copy: src: ~/.ssh/id_rsa.pub dest: /home/usernmame/.ssh/authorized_keys mode: 0600 owner: username group: username One way of solving this may be to create a var/main.yml and put the username there. But I wanted something through which I can specify the username at play.yml level. As I am also using the username in the role vimrcserver . I am calling the roles using play.yml --- - hosts: testdroplets roles: - update - bootstrap_server - create_new_user - vimserver Would a template work here in this case? Couldn't find much from those other question: Ansible best practice for passing vars to nested playbooks? Ansible passing variables to roles
|
ansible, ansible-template
| 49
| 154,336
| 7
|
https://stackoverflow.com/questions/42883909/passing-variables-to-ansible-roles
|
47,877,464
|
How Exactly Does Ansible Parse Boolean Variables?
|
In Ansible, there are several places where variables can be defined: in the inventory, in a playbook, in variable files, etc. Can anyone explain the following observations that I have made? When defining a Boolean variable in an inventory, it MUST be capitalized (i.e., True/False), otherwise (i.e., true/false) it will not be interpreted as a Boolean but as a String. In any of the YAML formatted files (playbooks, roles, etc.) both True/False and true/false are interpreted as Booleans. For example, I defined two variables in an inventory: abc=false xyz=False And when debugging the type of these variables inside a role... - debug: msg: "abc={{ abc | type_debug }} xyz={{ xyz | type_debug }}" ... then abc becomes unicode but xyz is interpreted as a bool : ok: [localhost] => { "msg": "abc=unicode xyz=bool" } However, when defining the same variables in a playbook, like this: vars: abc: false xyz: False ... then both variables are recognized as bool . I had to realize this the hard way after executing a playbook on production, running something that should not have run because of a variable set to 'false' instead of 'False' in an inventory. Thus, I'd really like to find a clear answer about how Ansible understands Booleans and how it depends on where/how the variable is defined. Should I simply always use capitalized True/False to be on the safe side? Is it valid to say that booleans in YAML files (with format key: value ) are case-insensitive, while in properties files (with format key=value ) they are case-sensitive? Any deeper insights would be highly appreciated.
|
How Exactly Does Ansible Parse Boolean Variables? In Ansible, there are several places where variables can be defined: in the inventory, in a playbook, in variable files, etc. Can anyone explain the following observations that I have made? When defining a Boolean variable in an inventory, it MUST be capitalized (i.e., True/False), otherwise (i.e., true/false) it will not be interpreted as a Boolean but as a String. In any of the YAML formatted files (playbooks, roles, etc.) both True/False and true/false are interpreted as Booleans. For example, I defined two variables in an inventory: abc=false xyz=False And when debugging the type of these variables inside a role... - debug: msg: "abc={{ abc | type_debug }} xyz={{ xyz | type_debug }}" ... then abc becomes unicode but xyz is interpreted as a bool : ok: [localhost] => { "msg": "abc=unicode xyz=bool" } However, when defining the same variables in a playbook, like this: vars: abc: false xyz: False ... then both variables are recognized as bool . I had to realize this the hard way after executing a playbook on production, running something that should not have run because of a variable set to 'false' instead of 'False' in an inventory. Thus, I'd really like to find a clear answer about how Ansible understands Booleans and how it depends on where/how the variable is defined. Should I simply always use capitalized True/False to be on the safe side? Is it valid to say that booleans in YAML files (with format key: value ) are case-insensitive, while in properties files (with format key=value ) they are case-sensitive? Any deeper insights would be highly appreciated.
|
boolean, ansible, yaml, ansible-inventory
| 49
| 69,316
| 2
|
https://stackoverflow.com/questions/47877464/how-exactly-does-ansible-parse-boolean-variables
|
28,709,501
|
How to list all currently targeted hosts in an Ansible play
|
I am running an Ansible play and would like to list all the hosts targeted by it. Ansible docs mentions that this is possible , but their method doesn't seem to work with a complex targeted group (targeting like hosts: web_servers:&data_center_primary) I'm sure this is doable, but cant seem to find any further documentation on it. Is there a var with all the currently targeted hosts?
|
How to list all currently targeted hosts in an Ansible play I am running an Ansible play and would like to list all the hosts targeted by it. Ansible docs mentions that this is possible , but their method doesn't seem to work with a complex targeted group (targeting like hosts: web_servers:&data_center_primary) I'm sure this is doable, but cant seem to find any further documentation on it. Is there a var with all the currently targeted hosts?
|
ansible
| 49
| 92,244
| 3
|
https://stackoverflow.com/questions/28709501/how-to-list-all-currently-targeted-hosts-in-an-ansible-play
|
53,253,879
|
ansible vars_files vs include_vars
|
What is the difference between vars_files directive and include_vars module Which should be used when, is any of above deprecated, discouraged?
|
ansible vars_files vs include_vars What is the difference between vars_files directive and include_vars module Which should be used when, is any of above deprecated, discouraged?
|
ansible
| 49
| 78,280
| 3
|
https://stackoverflow.com/questions/53253879/ansible-vars-files-vs-include-vars
|
29,937,195
|
How to diff ansible vault changes?
|
I'd like to see the actual git commit changes in the ansible vault file. Is there an easy way how to achieve this?
|
How to diff ansible vault changes? I'd like to see the actual git commit changes in the ansible vault file. Is there an easy way how to achieve this?
|
git, diff, ansible, ansible-vault
| 48
| 15,970
| 5
|
https://stackoverflow.com/questions/29937195/how-to-diff-ansible-vault-changes
|
49,619,445
|
how to append to a list in jinja2 for ansible
|
Below is the jinja2 template that i wrote to use in ansible. {% set port = 1234 %} {% set server_ip = [] %} {% for ip in host_ip %} {% do server_ip.append({{ ip }}:{{ port }}) %} {% endfor %} {% server_ip|join(', ') %} Below is the my desired output: devices = 192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234 But when i am running the ansible playbook, it is throwing the error as below: "AnsibleError: teme templating string: Encountered unknown tag 'do'. Jinja was looking for th: 'endfor' or 'else' Any help would be appreciated..
|
how to append to a list in jinja2 for ansible Below is the jinja2 template that i wrote to use in ansible. {% set port = 1234 %} {% set server_ip = [] %} {% for ip in host_ip %} {% do server_ip.append({{ ip }}:{{ port }}) %} {% endfor %} {% server_ip|join(', ') %} Below is the my desired output: devices = 192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234 But when i am running the ansible playbook, it is throwing the error as below: "AnsibleError: teme templating string: Encountered unknown tag 'do'. Jinja was looking for th: 'endfor' or 'else' Any help would be appreciated..
|
templates, ansible, jinja2, ansible-template
| 48
| 153,313
| 7
|
https://stackoverflow.com/questions/49619445/how-to-append-to-a-list-in-jinja2-for-ansible
|
31,912,748
|
how to run a particular task on specific host in ansible
|
my inventory file's contents - [webservers] x.x.x.x ansible_ssh_user=ubuntu [dbservers] x.x.x.x ansible_ssh_user=ubuntu in my tasks file which is in common role i.e. it will run on both hosts but I want to run a following task on host webservers not in dbservers which is defined in inventory file - name: Install required packages apt: name={{ item }} state=present with_items: - '{{ programs }}' become: yes tags: programs is when module helpful or there is any other way? How could I do this ?
|
how to run a particular task on specific host in ansible my inventory file's contents - [webservers] x.x.x.x ansible_ssh_user=ubuntu [dbservers] x.x.x.x ansible_ssh_user=ubuntu in my tasks file which is in common role i.e. it will run on both hosts but I want to run a following task on host webservers not in dbservers which is defined in inventory file - name: Install required packages apt: name={{ item }} state=present with_items: - '{{ programs }}' become: yes tags: programs is when module helpful or there is any other way? How could I do this ?
|
ansible
| 48
| 120,083
| 3
|
https://stackoverflow.com/questions/31912748/how-to-run-a-particular-task-on-specific-host-in-ansible
|
47,709,563
|
Check if arrays are defined and not empty in ansible
|
I have the following code - set_fact: MY_HOSTNAME: "SOME VALUE" MY_SERVER: "00.00.00.00" - name: Get MY server set_fact: MY_SERVER: "{{ groups[MY_HOSTNAME][0] }}" when: groups[MY_HOSTNAME] is defined In the above code, groups[MY_HOSTNAME] is an array. What is the best way to check that groups[MY_HOSTNAME] is defined and also that it is not empty If it is either of that I want the value 00.00.00.00 to be assigned to MY_SERVER
|
Check if arrays are defined and not empty in ansible I have the following code - set_fact: MY_HOSTNAME: "SOME VALUE" MY_SERVER: "00.00.00.00" - name: Get MY server set_fact: MY_SERVER: "{{ groups[MY_HOSTNAME][0] }}" when: groups[MY_HOSTNAME] is defined In the above code, groups[MY_HOSTNAME] is an array. What is the best way to check that groups[MY_HOSTNAME] is defined and also that it is not empty If it is either of that I want the value 00.00.00.00 to be assigned to MY_SERVER
|
ansible, ansible-facts
| 48
| 152,377
| 3
|
https://stackoverflow.com/questions/47709563/check-if-arrays-are-defined-and-not-empty-in-ansible
|
22,350,175
|
How do I get an Ansible template to honor new lines after a conditional
|
The template looks like this: solr.replication.master= {% if ansible_eth0.ipv4.address == servermaster.eth0 %} false {% else %} true {% endif %} solr.replication.slave=false And the output should look like this: solr.replication.master=true solr.replication.slave=false What I am actually getting is: solr.replication.master=truesolr.replication.slave=false I understand that Jinja2 strips whitespace, and that ansible is probably configuring this by default. But it does not seem to honor -/+ whitespace tags. Is there a way to force a line break?
|
How do I get an Ansible template to honor new lines after a conditional The template looks like this: solr.replication.master= {% if ansible_eth0.ipv4.address == servermaster.eth0 %} false {% else %} true {% endif %} solr.replication.slave=false And the output should look like this: solr.replication.master=true solr.replication.slave=false What I am actually getting is: solr.replication.master=truesolr.replication.slave=false I understand that Jinja2 strips whitespace, and that ansible is probably configuring this by default. But it does not seem to honor -/+ whitespace tags. Is there a way to force a line break?
|
templates, jinja2, ansible
| 48
| 36,152
| 5
|
https://stackoverflow.com/questions/22350175/how-do-i-get-an-ansible-template-to-honor-new-lines-after-a-conditional
|
19,688,885
|
In Ansible, how do I add a line to the end of a file?
|
I would expect this to be pretty simple. I'm using the lineinfile module like so: - name: Update bashrc for PythonBrew for foo user lineinfile: dest=/home/foo/.bashrc backup=yes line="[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}" owner=foo regexp='^' state=present insertafter=EOF create=True The problem I'm having is that it's replacing the last line in the file (which is fi ) with my new line rather than appending the line. This produces a syntax error. Do I have the parameters correct? I've tried setting regexp to both '^' and '' (blank). Is there another way to go about this? I'm using Ansible 1.3.3.
|
In Ansible, how do I add a line to the end of a file? I would expect this to be pretty simple. I'm using the lineinfile module like so: - name: Update bashrc for PythonBrew for foo user lineinfile: dest=/home/foo/.bashrc backup=yes line="[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}" owner=foo regexp='^' state=present insertafter=EOF create=True The problem I'm having is that it's replacing the last line in the file (which is fi ) with my new line rather than appending the line. This produces a syntax error. Do I have the parameters correct? I've tried setting regexp to both '^' and '' (blank). Is there another way to go about this? I'm using Ansible 1.3.3.
|
ansible
| 48
| 98,371
| 2
|
https://stackoverflow.com/questions/19688885/in-ansible-how-do-i-add-a-line-to-the-end-of-a-file
|
21,670,747
|
What user will Ansible run my commands as?
|
Background My question seems simple, but it gets more complex really fast. Basically, I got really tired of maintaining my servers manually (screams in background) and I decided it was time to find a way to make being a server admin much more liveable. That's when I found Ansible. Great huh? Sure beats making bash scripts (louder scream) for everything I wanted to automate. What's the problem? I'm having a lot of trouble figuring out what user my Ansible playbook will run certain things as. I also need the ability to specify what user certain tasks will run as. Here are some specific use cases: Cloning a repo as another user: My purpose with this is it run my node.js webapp from another user, who we'll call bill (that can only use sudo to run a script that I made that starts the node server, as opposed to root or my user that can use sudo for all commands). To do this, I need the ability to have Ansible's git module clone my git repo as bill . How would I do that? Knowing how Ansible will gain root: As far as I understand, you can set what user Ansible will connect to the server you're maintaining by defining 'user' and the beginning of the playbook file. Here's what I don't understand: if I tell it to connect via my username, joe , and ask it to update a package via the apt module, how will it gain root? Sudo usually prompts me for my password, and I'd prefer keeping it that way (for security). Final request I've scoured the Ansible docs, done some (what I thought was thorough) Googling, and generally just tried to figure it out on my own, but this information continues to elude me. I am very new to Ansible, and while it's mostly straight-forwards, I would benefit greatly if I could understand exactly how Ansible runs, on which users it runs, and how/where I can specify what user to use at different times. Thank you tons in advance
|
What user will Ansible run my commands as? Background My question seems simple, but it gets more complex really fast. Basically, I got really tired of maintaining my servers manually (screams in background) and I decided it was time to find a way to make being a server admin much more liveable. That's when I found Ansible. Great huh? Sure beats making bash scripts (louder scream) for everything I wanted to automate. What's the problem? I'm having a lot of trouble figuring out what user my Ansible playbook will run certain things as. I also need the ability to specify what user certain tasks will run as. Here are some specific use cases: Cloning a repo as another user: My purpose with this is it run my node.js webapp from another user, who we'll call bill (that can only use sudo to run a script that I made that starts the node server, as opposed to root or my user that can use sudo for all commands). To do this, I need the ability to have Ansible's git module clone my git repo as bill . How would I do that? Knowing how Ansible will gain root: As far as I understand, you can set what user Ansible will connect to the server you're maintaining by defining 'user' and the beginning of the playbook file. Here's what I don't understand: if I tell it to connect via my username, joe , and ask it to update a package via the apt module, how will it gain root? Sudo usually prompts me for my password, and I'd prefer keeping it that way (for security). Final request I've scoured the Ansible docs, done some (what I thought was thorough) Googling, and generally just tried to figure it out on my own, but this information continues to elude me. I am very new to Ansible, and while it's mostly straight-forwards, I would benefit greatly if I could understand exactly how Ansible runs, on which users it runs, and how/where I can specify what user to use at different times. Thank you tons in advance
|
node.js, linux, git, ansible
| 48
| 54,792
| 4
|
https://stackoverflow.com/questions/21670747/what-user-will-ansible-run-my-commands-as
|
31,152,102
|
Is it a good idea to make Ansible and Rundeck work together, or using either one is enough?
|
Recently I'm looking at Ansible and want to use it in projects. And also there's another tool Rundeck can be used to do all kinds of Operations works. I have experience with neither tool and this is my current understanding about them: Similar points Both tools are agent-less and use SSH to execute commands on remote servers Rundeck's main concept is Node, the same as Ansible's inventory, the key idea is to define/manage/group the target servers Rundeck can execute ad-hoc commands on selected nodes, Ansible can also do this very conveniently. Rundeck can define workflow and do the execution on selected nodes, this can be done with Ansible by writing playbook Rundeck can be integrated with CI tool like Jenkins to do deploy work, we can also define a Jenkins job to run ansible-playbook to do the deploy work Different points Rundeck has the concept of Job, which Ansible does not Rundeck has Job Scheduler, which Ansible can only achieve this with other tools like Jenkins or Cron tasks Rundeck has Web UI by default for free, but you have to pay for Ansible Tower Seems both Ansible and Rundeck can be used to do configuration/management/deployment work, maybe in a different way. So my questions are: Are these two complementary tools or they are designed for different purposes? If they're complementary tools, why is Ansibl only compared to tools like Chef/Puppet/Slat but not with Rundeck? If they're not why they have so many similar functionalities? We're already using Jenkins for CI, to build a Continuous-Delivery pipeline, which tool(Ansible/Rundeck) is a better idea to use to do the deployment? If they can be used together, what's the best practice? Any suggestions and experience sharing are greatly appreciated.
|
Is it a good idea to make Ansible and Rundeck work together, or using either one is enough? Recently I'm looking at Ansible and want to use it in projects. And also there's another tool Rundeck can be used to do all kinds of Operations works. I have experience with neither tool and this is my current understanding about them: Similar points Both tools are agent-less and use SSH to execute commands on remote servers Rundeck's main concept is Node, the same as Ansible's inventory, the key idea is to define/manage/group the target servers Rundeck can execute ad-hoc commands on selected nodes, Ansible can also do this very conveniently. Rundeck can define workflow and do the execution on selected nodes, this can be done with Ansible by writing playbook Rundeck can be integrated with CI tool like Jenkins to do deploy work, we can also define a Jenkins job to run ansible-playbook to do the deploy work Different points Rundeck has the concept of Job, which Ansible does not Rundeck has Job Scheduler, which Ansible can only achieve this with other tools like Jenkins or Cron tasks Rundeck has Web UI by default for free, but you have to pay for Ansible Tower Seems both Ansible and Rundeck can be used to do configuration/management/deployment work, maybe in a different way. So my questions are: Are these two complementary tools or they are designed for different purposes? If they're complementary tools, why is Ansibl only compared to tools like Chef/Puppet/Slat but not with Rundeck? If they're not why they have so many similar functionalities? We're already using Jenkins for CI, to build a Continuous-Delivery pipeline, which tool(Ansible/Rundeck) is a better idea to use to do the deployment? If they can be used together, what's the best practice? Any suggestions and experience sharing are greatly appreciated.
|
jenkins, ansible, continuous-delivery, devops, rundeck
| 48
| 33,859
| 7
|
https://stackoverflow.com/questions/31152102/is-it-a-good-idea-to-make-ansible-and-rundeck-work-together-or-using-either-one
|
22,773,294
|
How to upload encrypted file using ansible vault?
|
Does anyone have an example of decrypting and uploading a file using ansible-vault . I am thinking about keeping my ssl certificates encrypted in source control. It seems something like the following should work. --- - name: upload ssl crt copy: src=../../vault/encrypted.crt dest=/usr/local/etc/ssl/domain.crt
|
How to upload encrypted file using ansible vault? Does anyone have an example of decrypting and uploading a file using ansible-vault . I am thinking about keeping my ssl certificates encrypted in source control. It seems something like the following should work. --- - name: upload ssl crt copy: src=../../vault/encrypted.crt dest=/usr/local/etc/ssl/domain.crt
|
ansible
| 47
| 44,056
| 11
|
https://stackoverflow.com/questions/22773294/how-to-upload-encrypted-file-using-ansible-vault
|
23,877,781
|
How to wait for server restart using Ansible?
|
I'm trying to restart the server and then wait, using this: - name: Restart server shell: reboot - name: Wait for server to restart wait_for: port=22 delay=1 timeout=300 But I get this error: TASK: [iptables | Wait for server to restart] ********************************* fatal: [example.com] => failed to transfer file to /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for: sftp> put /tmp/tmpApPR8k /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for Connected to example.com. Connection closed
|
How to wait for server restart using Ansible? I'm trying to restart the server and then wait, using this: - name: Restart server shell: reboot - name: Wait for server to restart wait_for: port=22 delay=1 timeout=300 But I get this error: TASK: [iptables | Wait for server to restart] ********************************* fatal: [example.com] => failed to transfer file to /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for: sftp> put /tmp/tmpApPR8k /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for Connected to example.com. Connection closed
|
linux, deployment, ssh, ansible
| 47
| 86,520
| 11
|
https://stackoverflow.com/questions/23877781/how-to-wait-for-server-restart-using-ansible
|
45,489,534
|
Best way currently to create an ansible inventory from terraform
|
I have a long list of machines, all of which are a little different in functionality in a system. I'd like to organize these machines and add to a hosts inventory file automatically so I can run ansible and manage inventory. Are there good solutions out there for this? I think ansible hosts should looks something like... [webservers] someip someip [integration] someip someip etc.. After asking the question, I currently am researching output vars and using those to render a template from a file.
|
Best way currently to create an ansible inventory from terraform I have a long list of machines, all of which are a little different in functionality in a system. I'd like to organize these machines and add to a hosts inventory file automatically so I can run ansible and manage inventory. Are there good solutions out there for this? I think ansible hosts should looks something like... [webservers] someip someip [integration] someip someip etc.. After asking the question, I currently am researching output vars and using those to render a template from a file.
|
ansible, terraform
| 47
| 43,722
| 8
|
https://stackoverflow.com/questions/45489534/best-way-currently-to-create-an-ansible-inventory-from-terraform
|
37,171,966
|
Clean error output in ansible-playbook
|
If any Ansible task fails, there is error output, the playbook will display it newlines escaped '\n'. For tracebacks, spanning multiple lines, this make it very hard to read. Is there a way to make ansible-playbook to display unescaped error output from shell , pip , git and other similar tasks?
|
Clean error output in ansible-playbook If any Ansible task fails, there is error output, the playbook will display it newlines escaped '\n'. For tracebacks, spanning multiple lines, this make it very hard to read. Is there a way to make ansible-playbook to display unescaped error output from shell , pip , git and other similar tasks?
|
ansible
| 47
| 17,270
| 6
|
https://stackoverflow.com/questions/37171966/clean-error-output-in-ansible-playbook
|
16,444,306
|
Ansible idempotent MySQL installation Playbook
|
I want to setup a MySQL server on AWS, using Ansible for the configuration management. I am using the default AMI from Amazon ( ami-3275ee5b ), which uses yum for package management. When the Playbook below is executed, all goes well. But when I run it for a second time, the task Configure the root credentials fails, because the old password of MySQL doesn't match anymore, since it has been updated the last time I ran this Playbook. This makes the Playbook non-idempotent, which I don't like. I want to be able to run the Playbook as many times as I want. - hosts: staging_mysql user: ec2-user sudo: yes tasks: - name: Install MySQL action: yum name=$item with_items: - MySQL-python - mysql - mysql-server - name: Start the MySQL service action: service name=mysqld state=started - name: Configure the root credentials action: command mysqladmin -u root -p $mysql_root_password What would be the best way to solve this, which means make the Playbook idempotent? Thanks in advance!
|
Ansible idempotent MySQL installation Playbook I want to setup a MySQL server on AWS, using Ansible for the configuration management. I am using the default AMI from Amazon ( ami-3275ee5b ), which uses yum for package management. When the Playbook below is executed, all goes well. But when I run it for a second time, the task Configure the root credentials fails, because the old password of MySQL doesn't match anymore, since it has been updated the last time I ran this Playbook. This makes the Playbook non-idempotent, which I don't like. I want to be able to run the Playbook as many times as I want. - hosts: staging_mysql user: ec2-user sudo: yes tasks: - name: Install MySQL action: yum name=$item with_items: - MySQL-python - mysql - mysql-server - name: Start the MySQL service action: service name=mysqld state=started - name: Configure the root credentials action: command mysqladmin -u root -p $mysql_root_password What would be the best way to solve this, which means make the Playbook idempotent? Thanks in advance!
|
mysql, command-line, amazon-web-services, amazon-ec2, ansible
| 47
| 49,999
| 13
|
https://stackoverflow.com/questions/16444306/ansible-idempotent-mysql-installation-playbook
|
31,045,106
|
Append list variable to another list in Ansible
|
is it possible to append a variable list to a static list in ansible? I can define the whole list as a variable: my_list: - 1 - 2 - 3 and then use it in a playbook as something: {{my_list}} But I cannot seem to find how to do this (pseudo code): list_to_append: - 3 - 4 and then in the playbook: something: - 1 - 2 - {{append: list_to_append}} If that is in fact impossible, what would you suggest for my use case? I have a list of items in a parameter, but some of them are optional and should be modifiable using variables. In other words: I have default values + optional values that could or could not be added via variables. The optional values are not known in advance, I could add 1, 2 or 100 of them, so they are not static. I basically have a default static list ++ a configurable variable list to append. edit: I found this but it's only for with_items and I need it in a normal parameter: with_flattened: - "{{list1}}" - "{{list2}}"
|
Append list variable to another list in Ansible is it possible to append a variable list to a static list in ansible? I can define the whole list as a variable: my_list: - 1 - 2 - 3 and then use it in a playbook as something: {{my_list}} But I cannot seem to find how to do this (pseudo code): list_to_append: - 3 - 4 and then in the playbook: something: - 1 - 2 - {{append: list_to_append}} If that is in fact impossible, what would you suggest for my use case? I have a list of items in a parameter, but some of them are optional and should be modifiable using variables. In other words: I have default values + optional values that could or could not be added via variables. The optional values are not known in advance, I could add 1, 2 or 100 of them, so they are not static. I basically have a default static list ++ a configurable variable list to append. edit: I found this but it's only for with_items and I need it in a normal parameter: with_flattened: - "{{list1}}" - "{{list2}}"
|
jinja2, ansible
| 47
| 98,389
| 4
|
https://stackoverflow.com/questions/31045106/append-list-variable-to-another-list-in-ansible
|
20,040,141
|
Ansible command from inside virtualenv?
|
This seems like it should be really simple: tasks: - name: install python packages pip: name=${item} virtualenv=~/buildbot-env with_items: [ buildbot ] - name: create buildbot master command: buildbot create-master ~/buildbot creates=~/buildbot/buildbot.tac However, the command will not succeed unless the virtualenv's activate script is sourced first, and there doesn't seem to be provision to do that in the Ansible command module . I've experimented with sourcing the activate script in various of .profile, .bashrc, .bash_login, etc, with no luck. Alternatively, there's the shell command, but it seems like kind of an awkward hack: - name: create buildbot master shell: source ~/buildbot-env/bin/activate && \ buildbot create-master ~/buildbot \ creates=~/buildbot/buildbot.tac executable=/bin/bash Is there a better way?
|
Ansible command from inside virtualenv? This seems like it should be really simple: tasks: - name: install python packages pip: name=${item} virtualenv=~/buildbot-env with_items: [ buildbot ] - name: create buildbot master command: buildbot create-master ~/buildbot creates=~/buildbot/buildbot.tac However, the command will not succeed unless the virtualenv's activate script is sourced first, and there doesn't seem to be provision to do that in the Ansible command module . I've experimented with sourcing the activate script in various of .profile, .bashrc, .bash_login, etc, with no luck. Alternatively, there's the shell command, but it seems like kind of an awkward hack: - name: create buildbot master shell: source ~/buildbot-env/bin/activate && \ buildbot create-master ~/buildbot \ creates=~/buildbot/buildbot.tac executable=/bin/bash Is there a better way?
|
virtualenv, ansible
| 47
| 48,705
| 5
|
https://stackoverflow.com/questions/20040141/ansible-command-from-inside-virtualenv
|
42,167,747
|
How to loop over this dictionary in Ansible?
|
Say I have this dictionary war_files: server1: - file1.war - file2.war server2: - file1.war - file2.war - file3.war and for now I just want to loop over each item (key), and then over each item in the key (value). I did this - name: Loop over the dictionary debug: msg="Key={{ item.key }} value={{ item.value }}" with_dict: "{{ war_files }}" And I get this. It is of course correct, but is NOT what I want. ok: [localhost] => (item={'value': [u'file1.war', u'file2.war'], 'key': u'server1'}) => { "item": { "key": "server1", "value": [ "file1.war", "file2.war" ] }, "msg": "Server=server1, WAR=[u'file1.war', u'file2.war']" } ok: [localhost] => (item={'value': [u'file1.war', u'file2.war', u'file3.war'], 'key': u'server2'}) => { "item": { "key": "server2", "value": [ "file1.war", "file2.war", "file3.war" ] }, "msg": "Server=server2, WAR=[u'file1.war', u'file2.war', u'file3.war']" } I want to get an output that says "msg": "Server=server1, WAR=file1.war" "msg": "Server=server1, WAR=file2.war" "msg": "Server=server2, WAR=file1.war" "msg": "Server=server2, WAR=file2.war" "msg": "Server=server2, WAR=file3.war" IOW, how can I write a task to iterates over the dictionary so it goes through each key, and then the items within each key? In essence, I have a nested array and want to iterate over it?
|
How to loop over this dictionary in Ansible? Say I have this dictionary war_files: server1: - file1.war - file2.war server2: - file1.war - file2.war - file3.war and for now I just want to loop over each item (key), and then over each item in the key (value). I did this - name: Loop over the dictionary debug: msg="Key={{ item.key }} value={{ item.value }}" with_dict: "{{ war_files }}" And I get this. It is of course correct, but is NOT what I want. ok: [localhost] => (item={'value': [u'file1.war', u'file2.war'], 'key': u'server1'}) => { "item": { "key": "server1", "value": [ "file1.war", "file2.war" ] }, "msg": "Server=server1, WAR=[u'file1.war', u'file2.war']" } ok: [localhost] => (item={'value': [u'file1.war', u'file2.war', u'file3.war'], 'key': u'server2'}) => { "item": { "key": "server2", "value": [ "file1.war", "file2.war", "file3.war" ] }, "msg": "Server=server2, WAR=[u'file1.war', u'file2.war', u'file3.war']" } I want to get an output that says "msg": "Server=server1, WAR=file1.war" "msg": "Server=server1, WAR=file2.war" "msg": "Server=server2, WAR=file1.war" "msg": "Server=server2, WAR=file2.war" "msg": "Server=server2, WAR=file3.war" IOW, how can I write a task to iterates over the dictionary so it goes through each key, and then the items within each key? In essence, I have a nested array and want to iterate over it?
|
ansible, ansible-2.x
| 46
| 202,865
| 7
|
https://stackoverflow.com/questions/42167747/how-to-loop-over-this-dictionary-in-ansible
|
25,466,675
|
Ansible to Conditionally Prompt for a Variable?
|
I would like to be able to prompt for my super secure password variable if it is not already in the environment variables. (I'm thinking that I might not want to put the definition into .bash_profile or one of the other spots.) This is not working. It always prompts me. vars: THISUSER: "{{ lookup('env','LOGNAME') }}" SSHPWD: "{{ lookup('env','MY_PWD') }}" vars_prompt: - name: "release_version" prompt: "Product release version" default: "1.0" when: SSHPWD == null NOTE: I'm on a Mac, but I'd like for any solutions to be platform-independent.
|
Ansible to Conditionally Prompt for a Variable? I would like to be able to prompt for my super secure password variable if it is not already in the environment variables. (I'm thinking that I might not want to put the definition into .bash_profile or one of the other spots.) This is not working. It always prompts me. vars: THISUSER: "{{ lookup('env','LOGNAME') }}" SSHPWD: "{{ lookup('env','MY_PWD') }}" vars_prompt: - name: "release_version" prompt: "Product release version" default: "1.0" when: SSHPWD == null NOTE: I'm on a Mac, but I'd like for any solutions to be platform-independent.
|
variables, ansible
| 46
| 55,991
| 8
|
https://stackoverflow.com/questions/25466675/ansible-to-conditionally-prompt-for-a-variable
|
27,590,039
|
Running ansible-playbook using Python API
|
How can I run a playbook in python script? What is the equivalent of the following using ansible module in python: ansible -i hosts dbservers -m setup ansible-playbook -i hosts -vvvv -k site.yml I was looking at their documenation in [URL] but they have very limited examples.
|
Running ansible-playbook using Python API How can I run a playbook in python script? What is the equivalent of the following using ansible module in python: ansible -i hosts dbservers -m setup ansible-playbook -i hosts -vvvv -k site.yml I was looking at their documenation in [URL] but they have very limited examples.
|
python, ansible, ansible-runner
| 46
| 112,835
| 5
|
https://stackoverflow.com/questions/27590039/running-ansible-playbook-using-python-api
|
42,417,079
|
How to debug Ansible issues?
|
Sometimes, ansible doesn't do what you want. And increasing verbosity doesn't help. For example, I'm now trying to start coturn server, which comes with init script on systemd OS (Debian Jessie). Ansible considers it running, but it's not. How do I look into what's happening under the hood? Which commands are executed, and what output/exit code?
|
How to debug Ansible issues? Sometimes, ansible doesn't do what you want. And increasing verbosity doesn't help. For example, I'm now trying to start coturn server, which comes with init script on systemd OS (Debian Jessie). Ansible considers it running, but it's not. How do I look into what's happening under the hood? Which commands are executed, and what output/exit code?
|
debugging, ansible
| 46
| 107,307
| 9
|
https://stackoverflow.com/questions/42417079/how-to-debug-ansible-issues
|
29,075,287
|
Ansible: Insert line if not exists
|
I'm trying insert a line in a property file using ansible. I want to add some property if it does not exist, but not replace it if such property already exists in the file. I add to my ansible role - name: add couchbase host to properties lineinfile: dest=/database.properties regexp="^couchbase.host" line="couchbase.host=127.0.0.1" But this replaces the property value back to 127.0.0.1 if it exists already in the file. What I'm doing wrong?
|
Ansible: Insert line if not exists I'm trying insert a line in a property file using ansible. I want to add some property if it does not exist, but not replace it if such property already exists in the file. I add to my ansible role - name: add couchbase host to properties lineinfile: dest=/database.properties regexp="^couchbase.host" line="couchbase.host=127.0.0.1" But this replaces the property value back to 127.0.0.1 if it exists already in the file. What I'm doing wrong?
|
ansible
| 46
| 126,118
| 10
|
https://stackoverflow.com/questions/29075287/ansible-insert-line-if-not-exists
|
34,340,562
|
Evaluating return code in ansible conditional
|
I'm working on automating a task which needs to append the latest version of software to a file. I don't want it to do this multiple times for the same version. It looks at the following example file: var software releases = new Array( "4.3.0", "4.4.0", "4.5.0", "4.7.0", "4.8.0", "4.11.0", "4.12.1", "4.14.0", "4.15.0", "4.16.0", ); the defaults main.yml would pass in something like VERSION: 4.16.2 code - name: register version check shell: cat /root/versions.js | grep -q {{VERSION}} register: current_version - debug: msg="The registered variable output is {{ current_version.rc }}" - name: append to versions.js lineinfile: dest: /root/versions.js regexp: '^\);' insertbefore: '^#\);' line: " \"{{VERSION}}\",\n);" owner: root state: present when: current_version.rc == 1 problem: the debug message is evaluating current_version.rc and showing me boolean values based on the grep commands output, but I can't re-use this in the when conditional to determine if the task should be run. Edit: the output: PLAY [localhost] ************************************************************** GATHERING FACTS *************************************************************** ok: [localhost] TASK: [test | register version check] ***************************************** failed: [localhost] => {"changed": true, "cmd": "cat /root/versions.js | grep -q 3.19.2", "delta": "0:00:00.003570", "end": "2015-12-17 00:24:49.729078", "rc": 1, "start": "2015-12-17 00:24:49.725508", "warnings": []} FATAL: all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/root/site.retry localhost : ok=1 changed=0 unreachable=0 failed=1
|
Evaluating return code in ansible conditional I'm working on automating a task which needs to append the latest version of software to a file. I don't want it to do this multiple times for the same version. It looks at the following example file: var software releases = new Array( "4.3.0", "4.4.0", "4.5.0", "4.7.0", "4.8.0", "4.11.0", "4.12.1", "4.14.0", "4.15.0", "4.16.0", ); the defaults main.yml would pass in something like VERSION: 4.16.2 code - name: register version check shell: cat /root/versions.js | grep -q {{VERSION}} register: current_version - debug: msg="The registered variable output is {{ current_version.rc }}" - name: append to versions.js lineinfile: dest: /root/versions.js regexp: '^\);' insertbefore: '^#\);' line: " \"{{VERSION}}\",\n);" owner: root state: present when: current_version.rc == 1 problem: the debug message is evaluating current_version.rc and showing me boolean values based on the grep commands output, but I can't re-use this in the when conditional to determine if the task should be run. Edit: the output: PLAY [localhost] ************************************************************** GATHERING FACTS *************************************************************** ok: [localhost] TASK: [test | register version check] ***************************************** failed: [localhost] => {"changed": true, "cmd": "cat /root/versions.js | grep -q 3.19.2", "delta": "0:00:00.003570", "end": "2015-12-17 00:24:49.729078", "rc": 1, "start": "2015-12-17 00:24:49.725508", "warnings": []} FATAL: all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/root/site.retry localhost : ok=1 changed=0 unreachable=0 failed=1
|
ansible
| 46
| 140,342
| 1
|
https://stackoverflow.com/questions/34340562/evaluating-return-code-in-ansible-conditional
|
40,113,964
|
How can I install a systemd service using Ansible?
|
I want to install a systemd service from a Jinja2 template. How do I do this? Do I have to use copy module to copy the file to /lib/systemd/system and then use systemd module to enable it? Is there a better way?
|
How can I install a systemd service using Ansible? I want to install a systemd service from a Jinja2 template. How do I do this? Do I have to use copy module to copy the file to /lib/systemd/system and then use systemd module to enable it? Is there a better way?
|
ansible, systemd
| 46
| 46,985
| 1
|
https://stackoverflow.com/questions/40113964/how-can-i-install-a-systemd-service-using-ansible
|
27,335,204
|
Ansible: check if variable equals string
|
I have an ansible variable passed in on the command line as such: ansible-playbook -e environment=staging ansible/make_server.yml I want to load in some variables in my role dependeing on the value of environment. I have tried a lot of different methods such as: - include_vars: staging_vars.yml when: environment | staging and - include_vars: staging_vars.yml when: "{{environment}} == "staging" and - include_vars: staging_vars.yml when: "{{environment}} | match('staging')" but nothing seems to work. How do I do this? Details: I am using ansible 1.7.2
|
Ansible: check if variable equals string I have an ansible variable passed in on the command line as such: ansible-playbook -e environment=staging ansible/make_server.yml I want to load in some variables in my role dependeing on the value of environment. I have tried a lot of different methods such as: - include_vars: staging_vars.yml when: environment | staging and - include_vars: staging_vars.yml when: "{{environment}} == "staging" and - include_vars: staging_vars.yml when: "{{environment}} | match('staging')" but nothing seems to work. How do I do this? Details: I am using ansible 1.7.2
|
variables, conditional-statements, ansible
| 46
| 169,987
| 1
|
https://stackoverflow.com/questions/27335204/ansible-check-if-variable-equals-string
|
30,785,281
|
One loop over multiple Ansible tasks
|
I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two tasks?). All I've been able to find so far is one loop for each individual task
|
One loop over multiple Ansible tasks I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two tasks?). All I've been able to find so far is one loop for each individual task
|
loops, ansible
| 46
| 93,968
| 3
|
https://stackoverflow.com/questions/30785281/one-loop-over-multiple-ansible-tasks
|
32,957,418
|
ansible - check if file exists on *local* machine
|
I have a situation where I need to check the status of a file on the local machine (the one where I will call ansible-playbook ... ). If a file that is created by the user exists, it needs to be copied over to the remote host(s). If it doesn't exist, then none of the remote hosts need it. I know I've done things like : - name: Check for ~/.blah/config stat: path=/home/ubuntu/.blah/config register: stat_blah_config - name: Do something with blah config shell: ~/do_something_with_config.sh when: stat_aws_config.stat.exists == true But that will only work if the file exists remotely. Is there a way to conditionally execute a task (like copy) only if the file exists locally (have the stat in the first task execute locally instead of remotely), and fail silently if it does not? I'm not sure if ansible has this kind of functionality, but it would be useful.
|
ansible - check if file exists on *local* machine I have a situation where I need to check the status of a file on the local machine (the one where I will call ansible-playbook ... ). If a file that is created by the user exists, it needs to be copied over to the remote host(s). If it doesn't exist, then none of the remote hosts need it. I know I've done things like : - name: Check for ~/.blah/config stat: path=/home/ubuntu/.blah/config register: stat_blah_config - name: Do something with blah config shell: ~/do_something_with_config.sh when: stat_aws_config.stat.exists == true But that will only work if the file exists remotely. Is there a way to conditionally execute a task (like copy) only if the file exists locally (have the stat in the first task execute locally instead of remotely), and fail silently if it does not? I'm not sure if ansible has this kind of functionality, but it would be useful.
|
ansible
| 46
| 46,051
| 2
|
https://stackoverflow.com/questions/32957418/ansible-check-if-file-exists-on-local-machine
|
34,290,525
|
pause ansible playbook for user confirmation, whether to run rest tasks
|
I am running an ansible-playbook which have many tasks listed. All of them use to get run one by one, but I want to pause the playbook after a particular tasks to asks the user if he wants to continue running the rest of the tasks or exit. I have seen the pause module of ansible but couldn't see any example which asks users for yes or no which in turn continue or exit the ansible-playbook accordingly.
|
pause ansible playbook for user confirmation, whether to run rest tasks I am running an ansible-playbook which have many tasks listed. All of them use to get run one by one, but I want to pause the playbook after a particular tasks to asks the user if he wants to continue running the rest of the tasks or exit. I have seen the pause module of ansible but couldn't see any example which asks users for yes or no which in turn continue or exit the ansible-playbook accordingly.
|
ansible
| 45
| 51,084
| 5
|
https://stackoverflow.com/questions/34290525/pause-ansible-playbook-for-user-confirmation-whether-to-run-rest-tasks
|
53,671,030
|
Replace character in a string with Ansible
|
I have this Ansible as a String: FUBAR={{ PREFIX }}_{{ CNAME }}{{ VERSION }} I want to replace all . in the concatenated string with '' , like this: FUBAR={{ {{ PREFIX }}_{{ CNAME }}{{ VERSION }} | replace('.','') }} I get the message: expected token ':', got '}' Could anyone give me a suggestion what's wrong?
|
Replace character in a string with Ansible I have this Ansible as a String: FUBAR={{ PREFIX }}_{{ CNAME }}{{ VERSION }} I want to replace all . in the concatenated string with '' , like this: FUBAR={{ {{ PREFIX }}_{{ CNAME }}{{ VERSION }} | replace('.','') }} I get the message: expected token ':', got '}' Could anyone give me a suggestion what's wrong?
|
ansible
| 45
| 130,315
| 1
|
https://stackoverflow.com/questions/53671030/replace-character-in-a-string-with-ansible
|
33,363,023
|
Is there any option to list groups in Ansible?
|
As far as i know, ansible has an option named --list-hosts for listing hosts. Is there any option for listing host groups? Or any other way to come through?
|
Is there any option to list groups in Ansible? As far as i know, ansible has an option named --list-hosts for listing hosts. Is there any option for listing host groups? Or any other way to come through?
|
ansible
| 45
| 89,586
| 7
|
https://stackoverflow.com/questions/33363023/is-there-any-option-to-list-groups-in-ansible
|
33,415,992
|
Ansible: How to iterate over a role with an array?
|
Is it possible to call a role multiple times in a loop like this: vars: my_array: - foo - bar - baz roles: - role: foobar with_items: my_array How can we do this?
|
Ansible: How to iterate over a role with an array? Is it possible to call a role multiple times in a loop like this: vars: my_array: - foo - bar - baz roles: - role: foobar with_items: my_array How can we do this?
|
ansible
| 45
| 68,817
| 5
|
https://stackoverflow.com/questions/33415992/ansible-how-to-iterate-over-a-role-with-an-array
|
49,677,591
|
Ansible - print gathered facts for debugging purposes
|
Is there exists some way to print on console gathered facts ? I mean gatering facts using setup module. I would like to print gathered facts. Is it possible ? If it is possible can someone show example?
|
Ansible - print gathered facts for debugging purposes Is there exists some way to print on console gathered facts ? I mean gatering facts using setup module. I would like to print gathered facts. Is it possible ? If it is possible can someone show example?
|
ansible
| 45
| 107,278
| 2
|
https://stackoverflow.com/questions/49677591/ansible-print-gathered-facts-for-debugging-purposes
|
32,232,221
|
How to pass variables to included tasks in ansible?
|
I have an ansible file ( my_file.yml ) that looks something like this: --- - name: The name hosts: all tasks: - include:my_tasks.yml vars: my_var: "{{ my_var }}" my_tasks.yml looks like this: - name: Install Curl apt: pkg=curl state=installed - name: My task command: bash -c "curl -sSL [URL] my_var }} > /tmp/file.deb" I'd like to pass my_var as a command-line argument to ansible so I do like this: ansible-playbook my_file.yml --extra-vars "my_var=1.2.3" But I end up with the following error: ... Failed to template {{ my_var }}: Failed to template {{ my_var }}: recursive loop detected in template string: {{ my_var }} If I the vars in my_file.yml to look like this: - include:my_tasks.yml vars: my_var: "1.2.3" it works! I've also tried changing the variable name to something that is not equal to my_var , for example: - include:my_tasks.yml vars: my_var: "{{ my_var0 }}" but then I end up with an error. It seems to me that the variable is not expanded and instead the string "{{ my_var }}" or {{ my_var0 }} is passed to my_tasks.yml . How do I solve this?
|
How to pass variables to included tasks in ansible? I have an ansible file ( my_file.yml ) that looks something like this: --- - name: The name hosts: all tasks: - include:my_tasks.yml vars: my_var: "{{ my_var }}" my_tasks.yml looks like this: - name: Install Curl apt: pkg=curl state=installed - name: My task command: bash -c "curl -sSL [URL] my_var }} > /tmp/file.deb" I'd like to pass my_var as a command-line argument to ansible so I do like this: ansible-playbook my_file.yml --extra-vars "my_var=1.2.3" But I end up with the following error: ... Failed to template {{ my_var }}: Failed to template {{ my_var }}: recursive loop detected in template string: {{ my_var }} If I the vars in my_file.yml to look like this: - include:my_tasks.yml vars: my_var: "1.2.3" it works! I've also tried changing the variable name to something that is not equal to my_var , for example: - include:my_tasks.yml vars: my_var: "{{ my_var0 }}" but then I end up with an error. It seems to me that the variable is not expanded and instead the string "{{ my_var }}" or {{ my_var0 }} is passed to my_tasks.yml . How do I solve this?
|
ansible
| 45
| 90,875
| 3
|
https://stackoverflow.com/questions/32232221/how-to-pass-variables-to-included-tasks-in-ansible
|
25,751,085
|
PostgreSQL failing peer authentication with Ansible
|
I am running PostgreSQL 9.3 on FreeBSD. FreeBSD uses pgsql as the default system user for PostgreSQL. My /usr/local/pgsql/data/pg_hba.conf looks like this: # TYPE DATABASE USER ADDRESS METHOD local all pgsql peer local all all md5 host all all 127.0.0.1/32 md5 host all all ::1/128 md5 With this configuration I can connect to the database as pgsql without a password. $ su pgsql $ psql template1 template1=# \l List of databases ... That works as intended. On a remote machine, I have an Ansible task to create a database on the FreeBSD server. - name: Create the postgresql database postgresql_db: name=mydatabase login_user=pgsql Executing this task fails with the error Peer authentication failed for user "pgsql" . PLAY [web] ******************************************************************** GATHERING FACTS *************************************************************** ok: [host.example.org] TASK: [database | Create the postgresql database] ***************************** failed: [host.example.org] => {"failed": true} msg: unable to connect to database: FATAL: Peer authentication failed for user "pgsql" FATAL: all hosts have already failed -- aborting Why does this fail when peer authentication for the user pgsql is clearly working?
|
PostgreSQL failing peer authentication with Ansible I am running PostgreSQL 9.3 on FreeBSD. FreeBSD uses pgsql as the default system user for PostgreSQL. My /usr/local/pgsql/data/pg_hba.conf looks like this: # TYPE DATABASE USER ADDRESS METHOD local all pgsql peer local all all md5 host all all 127.0.0.1/32 md5 host all all ::1/128 md5 With this configuration I can connect to the database as pgsql without a password. $ su pgsql $ psql template1 template1=# \l List of databases ... That works as intended. On a remote machine, I have an Ansible task to create a database on the FreeBSD server. - name: Create the postgresql database postgresql_db: name=mydatabase login_user=pgsql Executing this task fails with the error Peer authentication failed for user "pgsql" . PLAY [web] ******************************************************************** GATHERING FACTS *************************************************************** ok: [host.example.org] TASK: [database | Create the postgresql database] ***************************** failed: [host.example.org] => {"failed": true} msg: unable to connect to database: FATAL: Peer authentication failed for user "pgsql" FATAL: all hosts have already failed -- aborting Why does this fail when peer authentication for the user pgsql is clearly working?
|
postgresql, authentication, freebsd, ansible
| 44
| 25,947
| 10
|
https://stackoverflow.com/questions/25751085/postgresql-failing-peer-authentication-with-ansible
|
23,507,589
|
Is it possible to set a fact of a list in Ansible?
|
Is it possible to set a fact containing a list in Ansible using set_fact ? What's the correct syntax for it?
|
Is it possible to set a fact of a list in Ansible? Is it possible to set a fact containing a list in Ansible using set_fact ? What's the correct syntax for it?
|
ansible
| 44
| 90,139
| 6
|
https://stackoverflow.com/questions/23507589/is-it-possible-to-set-a-fact-of-a-list-in-ansible
|
26,142,343
|
Ansible conditional based on stdout of result?
|
How do I use the when statement based on the standard output of register: result? If standard output exists I want somecommand to run if no standard output exists I want someothercommand to run. - hosts: myhosts tasks: - name: echo hello command: echo hello register: result - command: somecommand {{ result.stdout }} when: result|success - command: someothercommand when: result|failed
|
Ansible conditional based on stdout of result? How do I use the when statement based on the standard output of register: result? If standard output exists I want somecommand to run if no standard output exists I want someothercommand to run. - hosts: myhosts tasks: - name: echo hello command: echo hello register: result - command: somecommand {{ result.stdout }} when: result|success - command: someothercommand when: result|failed
|
linux, ansible
| 44
| 99,819
| 4
|
https://stackoverflow.com/questions/26142343/ansible-conditional-based-on-stdout-of-result
|
23,264,226
|
How to write dynamic variable in Ansible playbook
|
Based on extra vars parameter I Need to write variable value in ansible playbook ansible-playbook playbook.yml -e "param1=value1 param2=value2 param3=value3" If only param1 passed myvariable: 'param1' If only param1,param2 passed myvariable: 'param1,param2' If param1,param2,param3 are passed then variable value will be myvariable: 'param1,param2,param3' When I try to create variable dynamically through template then my playbook always takes previous variable value. But inside dest=roles/myrole/vars/main.yml its writing correct value. What I make a try here - hosts: local user: roop gather_facts: yes connection: local tasks: - template: src=roles/myrole/templates/myvar.j2 dest=roles/myrole/vars/main.yml - debug: var=myvariable roles: - { role: myrole } So inside myrole directory I have created template and vars - roles - myrole - vars/main.yml - templates/myvar.j2 templates/myvar.j2 {% if param1 is defined and param2 is defined and param3 is defined %} myvariable: 'param1,param2,param3' {% elif param1 is defined and param2 is defined %} myvariable: 'param1,param2' {% elif param1 is defined %} myvariable: 'param1' {% else %} myvariable: 'default-param' {% endif %} As I know if only two condition then I can do this using inline expression like below {{ 'param1,param2' if param1 is defined and param2 is defined else 'default-param' }} <do something> if <something is true> else <do something else> Is it possible if - elif - else in inline expression like above. Or any other way to assign value dynamically in ansible playbook?
|
How to write dynamic variable in Ansible playbook Based on extra vars parameter I Need to write variable value in ansible playbook ansible-playbook playbook.yml -e "param1=value1 param2=value2 param3=value3" If only param1 passed myvariable: 'param1' If only param1,param2 passed myvariable: 'param1,param2' If param1,param2,param3 are passed then variable value will be myvariable: 'param1,param2,param3' When I try to create variable dynamically through template then my playbook always takes previous variable value. But inside dest=roles/myrole/vars/main.yml its writing correct value. What I make a try here - hosts: local user: roop gather_facts: yes connection: local tasks: - template: src=roles/myrole/templates/myvar.j2 dest=roles/myrole/vars/main.yml - debug: var=myvariable roles: - { role: myrole } So inside myrole directory I have created template and vars - roles - myrole - vars/main.yml - templates/myvar.j2 templates/myvar.j2 {% if param1 is defined and param2 is defined and param3 is defined %} myvariable: 'param1,param2,param3' {% elif param1 is defined and param2 is defined %} myvariable: 'param1,param2' {% elif param1 is defined %} myvariable: 'param1' {% else %} myvariable: 'default-param' {% endif %} As I know if only two condition then I can do this using inline expression like below {{ 'param1,param2' if param1 is defined and param2 is defined else 'default-param' }} <do something> if <something is true> else <do something else> Is it possible if - elif - else in inline expression like above. Or any other way to assign value dynamically in ansible playbook?
|
jinja2, ansible
| 44
| 152,475
| 3
|
https://stackoverflow.com/questions/23264226/how-to-write-dynamic-variable-in-ansible-playbook
|
54,944,080
|
Installing multiple packages in Ansible
|
I have this task in Ansible: - name: Install mongodb yum: name: - "mongodb-org-{{ mongodb_version }}" - "mongodb-org-server-{{ mongodb_version }}" - "mongodb-org-mongos-{{ mongodb_version }}" - "mongodb-org-shell-{{ mongodb_version }}" - "mongodb-org-tools-{{ mongodb_version }}" state: present notify: Restart mongodb Is there a way I can indicate the version without having to use a loop like this? What is a more "elegant" way of writing this? - name: Install mongodb yum: name: "{{ item }}-{{ mongodb_version }}" state: present loop: - mongodb-org-server - mongodb-org-mongos - mongodb-org-shell - mongodb-org-tools notify: Restart mongodb
|
Installing multiple packages in Ansible I have this task in Ansible: - name: Install mongodb yum: name: - "mongodb-org-{{ mongodb_version }}" - "mongodb-org-server-{{ mongodb_version }}" - "mongodb-org-mongos-{{ mongodb_version }}" - "mongodb-org-shell-{{ mongodb_version }}" - "mongodb-org-tools-{{ mongodb_version }}" state: present notify: Restart mongodb Is there a way I can indicate the version without having to use a loop like this? What is a more "elegant" way of writing this? - name: Install mongodb yum: name: "{{ item }}-{{ mongodb_version }}" state: present loop: - mongodb-org-server - mongodb-org-mongos - mongodb-org-shell - mongodb-org-tools notify: Restart mongodb
|
ansible
| 44
| 97,579
| 6
|
https://stackoverflow.com/questions/54944080/installing-multiple-packages-in-ansible
|
22,983,484
|
Ansible - Access inventory alias
|
Having an inventory file like: [my_hosts] my_host ansible_ssh_host=123.123.123.123 my_host2 ansible_ssh_host=234.234.234.234 I want to gather some debug information in my templates. How do I acces the alias variable in a playbook/template? I.e.: debug: msg=Myhost is {{ ansible_host_alias }} # Myhost is my_host # Myhost is myhost2 I tried to gather facts using ansible -m setup my_host . The variables ansible_hostname , HOSTNAME and HOST contain the machine's hostname, i.e. echo $HOSTNAME which differs from my ansible alias.
|
Ansible - Access inventory alias Having an inventory file like: [my_hosts] my_host ansible_ssh_host=123.123.123.123 my_host2 ansible_ssh_host=234.234.234.234 I want to gather some debug information in my templates. How do I acces the alias variable in a playbook/template? I.e.: debug: msg=Myhost is {{ ansible_host_alias }} # Myhost is my_host # Myhost is myhost2 I tried to gather facts using ansible -m setup my_host . The variables ansible_hostname , HOSTNAME and HOST contain the machine's hostname, i.e. echo $HOSTNAME which differs from my ansible alias.
|
ansible
| 44
| 61,837
| 2
|
https://stackoverflow.com/questions/22983484/ansible-access-inventory-alias
|
42,186,301
|
Ansible - Create multiple folders if don't exist
|
Goal: Create multiple directories if they don't exist. Don't change permissions of existing folder Current playbook: - name: stat directories if they exist stat: path: "{{ item }}" loop: - /data/directory - /data/another register: myvar - debug: msg: "{{ myvar.results }}" - name: create directory if they don't exist file: path: "{{ item.invocation.module_args.path }}" state: directory owner: root group: root mode: 0775 loop: "{{ stat.results }}" when: not myvar.results.stat.exists The when statement is wrong. I looked at the example provided . But this only works for a single folder.
|
Ansible - Create multiple folders if don't exist Goal: Create multiple directories if they don't exist. Don't change permissions of existing folder Current playbook: - name: stat directories if they exist stat: path: "{{ item }}" loop: - /data/directory - /data/another register: myvar - debug: msg: "{{ myvar.results }}" - name: create directory if they don't exist file: path: "{{ item.invocation.module_args.path }}" state: directory owner: root group: root mode: 0775 loop: "{{ stat.results }}" when: not myvar.results.stat.exists The when statement is wrong. I looked at the example provided . But this only works for a single folder.
|
ansible
| 43
| 121,557
| 4
|
https://stackoverflow.com/questions/42186301/ansible-create-multiple-folders-if-dont-exist
|
43,609,132
|
Ansible: How to call a playbook from another?
|
I have written a simple playbook to print java process ID and other information of that PID [root@server thebigone]# cat check_java_pid.yaml --- - hosts: all gather_facts: no tasks: - name: Check PID of existing Java process shell: "ps -ef | grep [j]ava" register: java_status - debug: var=java_status.stdout And when I am calling this with ansible-playbook check_java_pid.yaml it's working fine. Now I am trying to call the above playbook from another one but only for a specific host. So I have written the 2nd playbook as below [root@server thebigone]# cat instance_restart.yaml --- - hosts: instance_1 gather_facts: no tasks: - include: check_java_pid.yaml But while doing ansible-playbook instance_restart.yaml , I am getting below errors ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path. The error appears to have been in '/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: --- - hosts: all ^ here The error appears to have been in '/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: --- - hosts: all ^ here Its saying syntax error but there isn't one really AFAIK as I have executed Playbook check_java_pid.yaml without any issues. Requesting your help on understanding this issue.
|
Ansible: How to call a playbook from another? I have written a simple playbook to print java process ID and other information of that PID [root@server thebigone]# cat check_java_pid.yaml --- - hosts: all gather_facts: no tasks: - name: Check PID of existing Java process shell: "ps -ef | grep [j]ava" register: java_status - debug: var=java_status.stdout And when I am calling this with ansible-playbook check_java_pid.yaml it's working fine. Now I am trying to call the above playbook from another one but only for a specific host. So I have written the 2nd playbook as below [root@server thebigone]# cat instance_restart.yaml --- - hosts: instance_1 gather_facts: no tasks: - include: check_java_pid.yaml But while doing ansible-playbook instance_restart.yaml , I am getting below errors ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path. The error appears to have been in '/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: --- - hosts: all ^ here The error appears to have been in '/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: --- - hosts: all ^ here Its saying syntax error but there isn't one really AFAIK as I have executed Playbook check_java_pid.yaml without any issues. Requesting your help on understanding this issue.
|
ansible
| 43
| 136,734
| 2
|
https://stackoverflow.com/questions/43609132/ansible-how-to-call-a-playbook-from-another
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.